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/ComparisonCategories.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <map>
45 #include <set>
46 
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // CheckDefaultArgumentVisitor
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55   /// the default argument of a parameter to determine whether it
56   /// contains any ill-formed subexpressions. For example, this will
57   /// diagnose the use of local variables or parameters within the
58   /// default argument expression.
59   class CheckDefaultArgumentVisitor
60     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61     Expr *DefaultArg;
62     Sema *S;
63 
64   public:
65     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66       : DefaultArg(defarg), S(s) {}
67 
68     bool VisitExpr(Expr *Node);
69     bool VisitDeclRefExpr(DeclRefExpr *DRE);
70     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71     bool VisitLambdaExpr(LambdaExpr *Lambda);
72     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73   };
74 
75   /// VisitExpr - Visit all of the children of this expression.
76   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77     bool IsInvalid = false;
78     for (Stmt *SubStmt : Node->children())
79       IsInvalid |= Visit(SubStmt);
80     return IsInvalid;
81   }
82 
83   /// VisitDeclRefExpr - Visit a reference to a declaration, to
84   /// determine whether this declaration can be used in the default
85   /// argument expression.
86   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87     NamedDecl *Decl = DRE->getDecl();
88     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89       // C++ [dcl.fct.default]p9
90       //   Default arguments are evaluated each time the function is
91       //   called. The order of evaluation of function arguments is
92       //   unspecified. Consequently, parameters of a function shall not
93       //   be used in default argument expressions, even if they are not
94       //   evaluated. Parameters of a function declared before a default
95       //   argument expression are in scope and can hide namespace and
96       //   class member names.
97       return S->Diag(DRE->getBeginLoc(),
98                      diag::err_param_default_argument_references_param)
99              << Param->getDeclName() << DefaultArg->getSourceRange();
100     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101       // C++ [dcl.fct.default]p7
102       //   Local variables shall not be used in default argument
103       //   expressions.
104       if (VDecl->isLocalVarDecl())
105         return S->Diag(DRE->getBeginLoc(),
106                        diag::err_param_default_argument_references_local)
107                << VDecl->getDeclName() << DefaultArg->getSourceRange();
108     }
109 
110     return false;
111   }
112 
113   /// VisitCXXThisExpr - Visit a C++ "this" expression.
114   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115     // C++ [dcl.fct.default]p8:
116     //   The keyword this shall not be used in a default argument of a
117     //   member function.
118     return S->Diag(ThisE->getBeginLoc(),
119                    diag::err_param_default_argument_references_this)
120            << ThisE->getSourceRange();
121   }
122 
123   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124     bool Invalid = false;
125     for (PseudoObjectExpr::semantics_iterator
126            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127       Expr *E = *i;
128 
129       // Look through bindings.
130       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131         E = OVE->getSourceExpr();
132         assert(E && "pseudo-object binding without source expression?");
133       }
134 
135       Invalid |= Visit(E);
136     }
137     return Invalid;
138   }
139 
140   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141     // C++11 [expr.lambda.prim]p13:
142     //   A lambda-expression appearing in a default argument shall not
143     //   implicitly or explicitly capture any entity.
144     if (Lambda->capture_begin() == Lambda->capture_end())
145       return false;
146 
147     return S->Diag(Lambda->getBeginLoc(), 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   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171     EST = EST_BasicNoexcept;
172 
173   switch (EST) {
174   case EST_Unparsed:
175   case EST_Uninstantiated:
176   case EST_Unevaluated:
177     llvm_unreachable("should not see unresolved exception specs here");
178 
179   // If this function can throw any exceptions, make a note of that.
180   case EST_MSAny:
181   case EST_None:
182     // FIXME: Whichever we see last of MSAny and None determines our result.
183     // We should make a consistent, order-independent choice here.
184     ClearExceptions();
185     ComputedEST = EST;
186     return;
187   case EST_NoexceptFalse:
188     ClearExceptions();
189     ComputedEST = EST_None;
190     return;
191   // FIXME: If the call to this decl is using any of its default arguments, we
192   // need to search them for potentially-throwing calls.
193   // If this function has a basic noexcept, it doesn't affect the outcome.
194   case EST_BasicNoexcept:
195   case EST_NoexceptTrue:
196     return;
197   // If we're still at noexcept(true) and there's a throw() callee,
198   // change to that specification.
199   case EST_DynamicNone:
200     if (ComputedEST == EST_BasicNoexcept)
201       ComputedEST = EST_DynamicNone;
202     return;
203   case EST_DependentNoexcept:
204     llvm_unreachable(
205         "should not generate implicit declarations for dependent cases");
206   case EST_Dynamic:
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       // sufficient, 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 unless the new
551       // function is a friend declaration in a template class. In the latter
552       // case the default arguments will be inherited when the friend
553       // declaration will be instantiated.
554       if (New->getFriendObjectKind() == Decl::FOK_None ||
555           !New->getLexicalDeclContext()->isDependentContext()) {
556         // It's important to use getInit() here;  getDefaultArg()
557         // strips off any top-level ExprWithCleanups.
558         NewParam->setHasInheritedDefaultArg();
559         if (OldParam->hasUnparsedDefaultArg())
560           NewParam->setUnparsedDefaultArg();
561         else if (OldParam->hasUninstantiatedDefaultArg())
562           NewParam->setUninstantiatedDefaultArg(
563                                        OldParam->getUninstantiatedDefaultArg());
564         else
565           NewParam->setDefaultArg(OldParam->getInit());
566       }
567     } else if (NewParamHasDfl) {
568       if (New->getDescribedFunctionTemplate()) {
569         // Paragraph 4, quoted above, only applies to non-template functions.
570         Diag(NewParam->getLocation(),
571              diag::err_param_default_argument_template_redecl)
572           << NewParam->getDefaultArgRange();
573         Diag(PrevForDefaultArgs->getLocation(),
574              diag::note_template_prev_declaration)
575             << false;
576       } else if (New->getTemplateSpecializationKind()
577                    != TSK_ImplicitInstantiation &&
578                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
579         // C++ [temp.expr.spec]p21:
580         //   Default function arguments shall not be specified in a declaration
581         //   or a definition for one of the following explicit specializations:
582         //     - the explicit specialization of a function template;
583         //     - the explicit specialization of a member function template;
584         //     - the explicit specialization of a member function of a class
585         //       template where the class template specialization to which the
586         //       member function specialization belongs is implicitly
587         //       instantiated.
588         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590           << New->getDeclName()
591           << NewParam->getDefaultArgRange();
592       } else if (New->getDeclContext()->isDependentContext()) {
593         // C++ [dcl.fct.default]p6 (DR217):
594         //   Default arguments for a member function of a class template shall
595         //   be specified on the initial declaration of the member function
596         //   within the class template.
597         //
598         // Reading the tea leaves a bit in DR217 and its reference to DR205
599         // leads me to the conclusion that one cannot add default function
600         // arguments for an out-of-line definition of a member function of a
601         // dependent type.
602         int WhichKind = 2;
603         if (CXXRecordDecl *Record
604               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605           if (Record->getDescribedClassTemplate())
606             WhichKind = 0;
607           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608             WhichKind = 1;
609           else
610             WhichKind = 2;
611         }
612 
613         Diag(NewParam->getLocation(),
614              diag::err_param_default_argument_member_template_redecl)
615           << WhichKind
616           << NewParam->getDefaultArgRange();
617       }
618     }
619   }
620 
621   // DR1344: If a default argument is added outside a class definition and that
622   // default argument makes the function a special member function, the program
623   // is ill-formed. This can only happen for constructors.
624   if (isa<CXXConstructorDecl>(New) &&
625       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628     if (NewSM != OldSM) {
629       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630       assert(NewParam->hasDefaultArg());
631       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632         << NewParam->getDefaultArgRange() << NewSM;
633       Diag(Old->getLocation(), diag::note_previous_declaration);
634     }
635   }
636 
637   const FunctionDecl *Def;
638   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639   // template has a constexpr specifier then all its declarations shall
640   // contain the constexpr specifier.
641   if (New->isConstexpr() != Old->isConstexpr()) {
642     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643       << New << New->isConstexpr();
644     Diag(Old->getLocation(), diag::note_previous_declaration);
645     Invalid = true;
646   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647              Old->isDefined(Def) &&
648              // If a friend function is inlined but does not have 'inline'
649              // specifier, it is a definition. Do not report attribute conflict
650              // in this case, redefinition will be diagnosed later.
651              (New->isInlineSpecified() ||
652               New->getFriendObjectKind() == Decl::FOK_None)) {
653     // C++11 [dcl.fcn.spec]p4:
654     //   If the definition of a function appears in a translation unit before its
655     //   first declaration as inline, the program is ill-formed.
656     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657     Diag(Def->getLocation(), diag::note_previous_definition);
658     Invalid = true;
659   }
660 
661   // FIXME: It's not clear what should happen if multiple declarations of a
662   // deduction guide have different explicitness. For now at least we simply
663   // reject any case where the explicitness changes.
664   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
665   if (NewGuide && NewGuide->isExplicitSpecified() !=
666                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
667     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
668       << NewGuide->isExplicitSpecified();
669     Diag(Old->getLocation(), diag::note_previous_declaration);
670   }
671 
672   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673   // argument expression, that declaration shall be a definition and shall be
674   // the only declaration of the function or function template in the
675   // translation unit.
676   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
677       functionDeclHasDefaultArgument(Old)) {
678     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679     Diag(Old->getLocation(), diag::note_previous_declaration);
680     Invalid = true;
681   }
682 
683   return Invalid;
684 }
685 
686 NamedDecl *
687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
688                                    MultiTemplateParamsArg TemplateParamLists) {
689   assert(D.isDecompositionDeclarator());
690   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
691 
692   // The syntax only allows a decomposition declarator as a simple-declaration,
693   // a for-range-declaration, or a condition in Clang, but we parse it in more
694   // cases than that.
695   if (!D.mayHaveDecompositionDeclarator()) {
696     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
697       << Decomp.getSourceRange();
698     return nullptr;
699   }
700 
701   if (!TemplateParamLists.empty()) {
702     // FIXME: There's no rule against this, but there are also no rules that
703     // would actually make it usable, so we reject it for now.
704     Diag(TemplateParamLists.front()->getTemplateLoc(),
705          diag::err_decomp_decl_template);
706     return nullptr;
707   }
708 
709   Diag(Decomp.getLSquareLoc(),
710        !getLangOpts().CPlusPlus17
711            ? diag::ext_decomp_decl
712            : D.getContext() == DeclaratorContext::ConditionContext
713                  ? diag::ext_decomp_decl_cond
714                  : diag::warn_cxx14_compat_decomp_decl)
715       << Decomp.getSourceRange();
716 
717   // The semantic context is always just the current context.
718   DeclContext *const DC = CurContext;
719 
720   // C++1z [dcl.dcl]/8:
721   //   The decl-specifier-seq shall contain only the type-specifier auto
722   //   and cv-qualifiers.
723   auto &DS = D.getDeclSpec();
724   {
725     SmallVector<StringRef, 8> BadSpecifiers;
726     SmallVector<SourceLocation, 8> BadSpecifierLocs;
727     if (auto SCS = DS.getStorageClassSpec()) {
728       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
729       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
730     }
731     if (auto TSCS = DS.getThreadStorageClassSpec()) {
732       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
733       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
734     }
735     if (DS.isConstexprSpecified()) {
736       BadSpecifiers.push_back("constexpr");
737       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
738     }
739     if (DS.isInlineSpecified()) {
740       BadSpecifiers.push_back("inline");
741       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
742     }
743     if (!BadSpecifiers.empty()) {
744       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
745       Err << (int)BadSpecifiers.size()
746           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
747       // Don't add FixItHints to remove the specifiers; we do still respect
748       // them when building the underlying variable.
749       for (auto Loc : BadSpecifierLocs)
750         Err << SourceRange(Loc, Loc);
751     }
752     // We can't recover from it being declared as a typedef.
753     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
754       return nullptr;
755   }
756 
757   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
758   QualType R = TInfo->getType();
759 
760   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
761                                       UPPC_DeclarationType))
762     D.setInvalidType();
763 
764   // The syntax only allows a single ref-qualifier prior to the decomposition
765   // declarator. No other declarator chunks are permitted. Also check the type
766   // specifier here.
767   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
768       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
769       (D.getNumTypeObjects() == 1 &&
770        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
771     Diag(Decomp.getLSquareLoc(),
772          (D.hasGroupingParens() ||
773           (D.getNumTypeObjects() &&
774            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
775              ? diag::err_decomp_decl_parens
776              : diag::err_decomp_decl_type)
777         << R;
778 
779     // In most cases, there's no actual problem with an explicitly-specified
780     // type, but a function type won't work here, and ActOnVariableDeclarator
781     // shouldn't be called for such a type.
782     if (R->isFunctionType())
783       D.setInvalidType();
784   }
785 
786   // Build the BindingDecls.
787   SmallVector<BindingDecl*, 8> Bindings;
788 
789   // Build the BindingDecls.
790   for (auto &B : D.getDecompositionDeclarator().bindings()) {
791     // Check for name conflicts.
792     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
793     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
794                           ForVisibleRedeclaration);
795     LookupName(Previous, S,
796                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
797 
798     // It's not permitted to shadow a template parameter name.
799     if (Previous.isSingleResult() &&
800         Previous.getFoundDecl()->isTemplateParameter()) {
801       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
802                                       Previous.getFoundDecl());
803       Previous.clear();
804     }
805 
806     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
807                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
808     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
809                          /*AllowInlineNamespace*/false);
810     if (!Previous.empty()) {
811       auto *Old = Previous.getRepresentativeDecl();
812       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
813       Diag(Old->getLocation(), diag::note_previous_definition);
814     }
815 
816     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
817     PushOnScopeChains(BD, S, true);
818     Bindings.push_back(BD);
819     ParsingInitForAutoVars.insert(BD);
820   }
821 
822   // There are no prior lookup results for the variable itself, because it
823   // is unnamed.
824   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
825                                Decomp.getLSquareLoc());
826   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
827                         ForVisibleRedeclaration);
828 
829   // Build the variable that holds the non-decomposed object.
830   bool AddToScope = true;
831   NamedDecl *New =
832       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
833                               MultiTemplateParamsArg(), AddToScope, Bindings);
834   if (AddToScope) {
835     S->AddDecl(New);
836     CurContext->addHiddenDecl(New);
837   }
838 
839   if (isInOpenMPDeclareTargetContext())
840     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
841 
842   return New;
843 }
844 
845 static bool checkSimpleDecomposition(
846     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
847     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
848     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
849   if ((int64_t)Bindings.size() != NumElems) {
850     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
851         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
852         << (NumElems < Bindings.size());
853     return true;
854   }
855 
856   unsigned I = 0;
857   for (auto *B : Bindings) {
858     SourceLocation Loc = B->getLocation();
859     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
860     if (E.isInvalid())
861       return true;
862     E = GetInit(Loc, E.get(), I++);
863     if (E.isInvalid())
864       return true;
865     B->setBinding(ElemType, E.get());
866   }
867 
868   return false;
869 }
870 
871 static bool checkArrayLikeDecomposition(Sema &S,
872                                         ArrayRef<BindingDecl *> Bindings,
873                                         ValueDecl *Src, QualType DecompType,
874                                         const llvm::APSInt &NumElems,
875                                         QualType ElemType) {
876   return checkSimpleDecomposition(
877       S, Bindings, Src, DecompType, NumElems, ElemType,
878       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
879         ExprResult E = S.ActOnIntegerConstant(Loc, I);
880         if (E.isInvalid())
881           return ExprError();
882         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
883       });
884 }
885 
886 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
887                                     ValueDecl *Src, QualType DecompType,
888                                     const ConstantArrayType *CAT) {
889   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
890                                      llvm::APSInt(CAT->getSize()),
891                                      CAT->getElementType());
892 }
893 
894 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
895                                      ValueDecl *Src, QualType DecompType,
896                                      const VectorType *VT) {
897   return checkArrayLikeDecomposition(
898       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
899       S.Context.getQualifiedType(VT->getElementType(),
900                                  DecompType.getQualifiers()));
901 }
902 
903 static bool checkComplexDecomposition(Sema &S,
904                                       ArrayRef<BindingDecl *> Bindings,
905                                       ValueDecl *Src, QualType DecompType,
906                                       const ComplexType *CT) {
907   return checkSimpleDecomposition(
908       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
909       S.Context.getQualifiedType(CT->getElementType(),
910                                  DecompType.getQualifiers()),
911       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
912         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
913       });
914 }
915 
916 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
917                                      TemplateArgumentListInfo &Args) {
918   SmallString<128> SS;
919   llvm::raw_svector_ostream OS(SS);
920   bool First = true;
921   for (auto &Arg : Args.arguments()) {
922     if (!First)
923       OS << ", ";
924     Arg.getArgument().print(PrintingPolicy, OS);
925     First = false;
926   }
927   return OS.str();
928 }
929 
930 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
931                                      SourceLocation Loc, StringRef Trait,
932                                      TemplateArgumentListInfo &Args,
933                                      unsigned DiagID) {
934   auto DiagnoseMissing = [&] {
935     if (DiagID)
936       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
937                                                Args);
938     return true;
939   };
940 
941   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
942   NamespaceDecl *Std = S.getStdNamespace();
943   if (!Std)
944     return DiagnoseMissing();
945 
946   // Look up the trait itself, within namespace std. We can diagnose various
947   // problems with this lookup even if we've been asked to not diagnose a
948   // missing specialization, because this can only fail if the user has been
949   // declaring their own names in namespace std or we don't support the
950   // standard library implementation in use.
951   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
952                       Loc, Sema::LookupOrdinaryName);
953   if (!S.LookupQualifiedName(Result, Std))
954     return DiagnoseMissing();
955   if (Result.isAmbiguous())
956     return true;
957 
958   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
959   if (!TraitTD) {
960     Result.suppressDiagnostics();
961     NamedDecl *Found = *Result.begin();
962     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
963     S.Diag(Found->getLocation(), diag::note_declared_at);
964     return true;
965   }
966 
967   // Build the template-id.
968   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
969   if (TraitTy.isNull())
970     return true;
971   if (!S.isCompleteType(Loc, TraitTy)) {
972     if (DiagID)
973       S.RequireCompleteType(
974           Loc, TraitTy, DiagID,
975           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
976     return true;
977   }
978 
979   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
980   assert(RD && "specialization of class template is not a class?");
981 
982   // Look up the member of the trait type.
983   S.LookupQualifiedName(TraitMemberLookup, RD);
984   return TraitMemberLookup.isAmbiguous();
985 }
986 
987 static TemplateArgumentLoc
988 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
989                                    uint64_t I) {
990   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
991   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
992 }
993 
994 static TemplateArgumentLoc
995 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
996   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
997 }
998 
999 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1000 
1001 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1002                                llvm::APSInt &Size) {
1003   EnterExpressionEvaluationContext ContextRAII(
1004       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1005 
1006   DeclarationName Value = S.PP.getIdentifierInfo("value");
1007   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1008 
1009   // Form template argument list for tuple_size<T>.
1010   TemplateArgumentListInfo Args(Loc, Loc);
1011   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1012 
1013   // If there's no tuple_size specialization, it's not tuple-like.
1014   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1015     return IsTupleLike::NotTupleLike;
1016 
1017   // If we get this far, we've committed to the tuple interpretation, but
1018   // we can still fail if there actually isn't a usable ::value.
1019 
1020   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1021     LookupResult &R;
1022     TemplateArgumentListInfo &Args;
1023     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1024         : R(R), Args(Args) {}
1025     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1026       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1027           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1028     }
1029   } Diagnoser(R, Args);
1030 
1031   if (R.empty()) {
1032     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1033     return IsTupleLike::Error;
1034   }
1035 
1036   ExprResult E =
1037       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1038   if (E.isInvalid())
1039     return IsTupleLike::Error;
1040 
1041   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1042   if (E.isInvalid())
1043     return IsTupleLike::Error;
1044 
1045   return IsTupleLike::TupleLike;
1046 }
1047 
1048 /// \return std::tuple_element<I, T>::type.
1049 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1050                                         unsigned I, QualType T) {
1051   // Form template argument list for tuple_element<I, T>.
1052   TemplateArgumentListInfo Args(Loc, Loc);
1053   Args.addArgument(
1054       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1055   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1056 
1057   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1058   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1059   if (lookupStdTypeTraitMember(
1060           S, R, Loc, "tuple_element", Args,
1061           diag::err_decomp_decl_std_tuple_element_not_specialized))
1062     return QualType();
1063 
1064   auto *TD = R.getAsSingle<TypeDecl>();
1065   if (!TD) {
1066     R.suppressDiagnostics();
1067     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1068       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1069     if (!R.empty())
1070       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1071     return QualType();
1072   }
1073 
1074   return S.Context.getTypeDeclType(TD);
1075 }
1076 
1077 namespace {
1078 struct BindingDiagnosticTrap {
1079   Sema &S;
1080   DiagnosticErrorTrap Trap;
1081   BindingDecl *BD;
1082 
1083   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1084       : S(S), Trap(S.Diags), BD(BD) {}
1085   ~BindingDiagnosticTrap() {
1086     if (Trap.hasErrorOccurred())
1087       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1088   }
1089 };
1090 }
1091 
1092 static bool checkTupleLikeDecomposition(Sema &S,
1093                                         ArrayRef<BindingDecl *> Bindings,
1094                                         VarDecl *Src, QualType DecompType,
1095                                         const llvm::APSInt &TupleSize) {
1096   if ((int64_t)Bindings.size() != TupleSize) {
1097     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1098         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1099         << (TupleSize < Bindings.size());
1100     return true;
1101   }
1102 
1103   if (Bindings.empty())
1104     return false;
1105 
1106   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1107 
1108   // [dcl.decomp]p3:
1109   //   The unqualified-id get is looked up in the scope of E by class member
1110   //   access lookup ...
1111   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1112   bool UseMemberGet = false;
1113   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1114     if (auto *RD = DecompType->getAsCXXRecordDecl())
1115       S.LookupQualifiedName(MemberGet, RD);
1116     if (MemberGet.isAmbiguous())
1117       return true;
1118     //   ... and if that finds at least one declaration that is a function
1119     //   template whose first template parameter is a non-type parameter ...
1120     for (NamedDecl *D : MemberGet) {
1121       if (FunctionTemplateDecl *FTD =
1122               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1123         TemplateParameterList *TPL = FTD->getTemplateParameters();
1124         if (TPL->size() != 0 &&
1125             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1126           //   ... the initializer is e.get<i>().
1127           UseMemberGet = true;
1128           break;
1129         }
1130       }
1131     }
1132     S.FilterAcceptableTemplateNames(MemberGet);
1133   }
1134 
1135   unsigned I = 0;
1136   for (auto *B : Bindings) {
1137     BindingDiagnosticTrap Trap(S, B);
1138     SourceLocation Loc = B->getLocation();
1139 
1140     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1141     if (E.isInvalid())
1142       return true;
1143 
1144     //   e is an lvalue if the type of the entity is an lvalue reference and
1145     //   an xvalue otherwise
1146     if (!Src->getType()->isLValueReferenceType())
1147       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1148                                    E.get(), nullptr, VK_XValue);
1149 
1150     TemplateArgumentListInfo Args(Loc, Loc);
1151     Args.addArgument(
1152         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1153 
1154     if (UseMemberGet) {
1155       //   if [lookup of member get] finds at least one declaration, the
1156       //   initializer is e.get<i-1>().
1157       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1158                                      CXXScopeSpec(), SourceLocation(), nullptr,
1159                                      MemberGet, &Args, nullptr);
1160       if (E.isInvalid())
1161         return true;
1162 
1163       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1164     } else {
1165       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1166       //   in the associated namespaces.
1167       Expr *Get = UnresolvedLookupExpr::Create(
1168           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1169           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1170           UnresolvedSetIterator(), UnresolvedSetIterator());
1171 
1172       Expr *Arg = E.get();
1173       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1174     }
1175     if (E.isInvalid())
1176       return true;
1177     Expr *Init = E.get();
1178 
1179     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1180     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1181     if (T.isNull())
1182       return true;
1183 
1184     //   each vi is a variable of type "reference to T" initialized with the
1185     //   initializer, where the reference is an lvalue reference if the
1186     //   initializer is an lvalue and an rvalue reference otherwise
1187     QualType RefType =
1188         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1189     if (RefType.isNull())
1190       return true;
1191     auto *RefVD = VarDecl::Create(
1192         S.Context, Src->getDeclContext(), Loc, Loc,
1193         B->getDeclName().getAsIdentifierInfo(), RefType,
1194         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1195     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1196     RefVD->setTSCSpec(Src->getTSCSpec());
1197     RefVD->setImplicit();
1198     if (Src->isInlineSpecified())
1199       RefVD->setInlineSpecified();
1200     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1201 
1202     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1203     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1204     InitializationSequence Seq(S, Entity, Kind, Init);
1205     E = Seq.Perform(S, Entity, Kind, Init);
1206     if (E.isInvalid())
1207       return true;
1208     E = S.ActOnFinishFullExpr(E.get(), Loc);
1209     if (E.isInvalid())
1210       return true;
1211     RefVD->setInit(E.get());
1212     RefVD->checkInitIsICE();
1213 
1214     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1215                                    DeclarationNameInfo(B->getDeclName(), Loc),
1216                                    RefVD);
1217     if (E.isInvalid())
1218       return true;
1219 
1220     B->setBinding(T, E.get());
1221     I++;
1222   }
1223 
1224   return false;
1225 }
1226 
1227 /// Find the base class to decompose in a built-in decomposition of a class type.
1228 /// This base class search is, unfortunately, not quite like any other that we
1229 /// perform anywhere else in C++.
1230 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1231                                                 const CXXRecordDecl *RD,
1232                                                 CXXCastPath &BasePath) {
1233   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1234                           CXXBasePath &Path) {
1235     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1236   };
1237 
1238   const CXXRecordDecl *ClassWithFields = nullptr;
1239   AccessSpecifier AS = AS_public;
1240   if (RD->hasDirectFields())
1241     // [dcl.decomp]p4:
1242     //   Otherwise, all of E's non-static data members shall be public direct
1243     //   members of E ...
1244     ClassWithFields = RD;
1245   else {
1246     //   ... or of ...
1247     CXXBasePaths Paths;
1248     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1249     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1250       // If no classes have fields, just decompose RD itself. (This will work
1251       // if and only if zero bindings were provided.)
1252       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1253     }
1254 
1255     CXXBasePath *BestPath = nullptr;
1256     for (auto &P : Paths) {
1257       if (!BestPath)
1258         BestPath = &P;
1259       else if (!S.Context.hasSameType(P.back().Base->getType(),
1260                                       BestPath->back().Base->getType())) {
1261         //   ... the same ...
1262         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1263           << false << RD << BestPath->back().Base->getType()
1264           << P.back().Base->getType();
1265         return DeclAccessPair();
1266       } else if (P.Access < BestPath->Access) {
1267         BestPath = &P;
1268       }
1269     }
1270 
1271     //   ... unambiguous ...
1272     QualType BaseType = BestPath->back().Base->getType();
1273     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1274       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1275         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1276       return DeclAccessPair();
1277     }
1278 
1279     //   ... [accessible, implied by other rules] base class of E.
1280     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1281                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1282     AS = BestPath->Access;
1283 
1284     ClassWithFields = BaseType->getAsCXXRecordDecl();
1285     S.BuildBasePathArray(Paths, BasePath);
1286   }
1287 
1288   // The above search did not check whether the selected class itself has base
1289   // classes with fields, so check that now.
1290   CXXBasePaths Paths;
1291   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293       << (ClassWithFields == RD) << RD << ClassWithFields
1294       << Paths.front().back().Base->getType();
1295     return DeclAccessPair();
1296   }
1297 
1298   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1299 }
1300 
1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1302                                      ValueDecl *Src, QualType DecompType,
1303                                      const CXXRecordDecl *OrigRD) {
1304   CXXCastPath BasePath;
1305   DeclAccessPair BasePair =
1306       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1307   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1308   if (!RD)
1309     return true;
1310   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1311                                                  DecompType.getQualifiers());
1312 
1313   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1314     unsigned NumFields =
1315         std::count_if(RD->field_begin(), RD->field_end(),
1316                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1317     assert(Bindings.size() != NumFields);
1318     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1319         << DecompType << (unsigned)Bindings.size() << NumFields
1320         << (NumFields < Bindings.size());
1321     return true;
1322   };
1323 
1324   //   all of E's non-static data members shall be [...] well-formed
1325   //   when named as e.name in the context of the structured binding,
1326   //   E shall not have an anonymous union member, ...
1327   unsigned I = 0;
1328   for (auto *FD : RD->fields()) {
1329     if (FD->isUnnamedBitfield())
1330       continue;
1331 
1332     if (FD->isAnonymousStructOrUnion()) {
1333       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1334         << DecompType << FD->getType()->isUnionType();
1335       S.Diag(FD->getLocation(), diag::note_declared_at);
1336       return true;
1337     }
1338 
1339     // We have a real field to bind.
1340     if (I >= Bindings.size())
1341       return DiagnoseBadNumberOfBindings();
1342     auto *B = Bindings[I++];
1343     SourceLocation Loc = B->getLocation();
1344 
1345     // The field must be accessible in the context of the structured binding.
1346     // We already checked that the base class is accessible.
1347     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1348     // const_cast here.
1349     S.CheckStructuredBindingMemberAccess(
1350         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1351         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1352                                      BasePair.getAccess(), FD->getAccess())));
1353 
1354     // Initialize the binding to Src.FD.
1355     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1356     if (E.isInvalid())
1357       return true;
1358     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1359                             VK_LValue, &BasePath);
1360     if (E.isInvalid())
1361       return true;
1362     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1363                                   CXXScopeSpec(), FD,
1364                                   DeclAccessPair::make(FD, FD->getAccess()),
1365                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1366     if (E.isInvalid())
1367       return true;
1368 
1369     // If the type of the member is T, the referenced type is cv T, where cv is
1370     // the cv-qualification of the decomposition expression.
1371     //
1372     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1373     // 'const' to the type of the field.
1374     Qualifiers Q = DecompType.getQualifiers();
1375     if (FD->isMutable())
1376       Q.removeConst();
1377     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1378   }
1379 
1380   if (I != Bindings.size())
1381     return DiagnoseBadNumberOfBindings();
1382 
1383   return false;
1384 }
1385 
1386 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1387   QualType DecompType = DD->getType();
1388 
1389   // If the type of the decomposition is dependent, then so is the type of
1390   // each binding.
1391   if (DecompType->isDependentType()) {
1392     for (auto *B : DD->bindings())
1393       B->setType(Context.DependentTy);
1394     return;
1395   }
1396 
1397   DecompType = DecompType.getNonReferenceType();
1398   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1399 
1400   // C++1z [dcl.decomp]/2:
1401   //   If E is an array type [...]
1402   // As an extension, we also support decomposition of built-in complex and
1403   // vector types.
1404   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1405     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1406       DD->setInvalidDecl();
1407     return;
1408   }
1409   if (auto *VT = DecompType->getAs<VectorType>()) {
1410     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1411       DD->setInvalidDecl();
1412     return;
1413   }
1414   if (auto *CT = DecompType->getAs<ComplexType>()) {
1415     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1416       DD->setInvalidDecl();
1417     return;
1418   }
1419 
1420   // C++1z [dcl.decomp]/3:
1421   //   if the expression std::tuple_size<E>::value is a well-formed integral
1422   //   constant expression, [...]
1423   llvm::APSInt TupleSize(32);
1424   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1425   case IsTupleLike::Error:
1426     DD->setInvalidDecl();
1427     return;
1428 
1429   case IsTupleLike::TupleLike:
1430     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1431       DD->setInvalidDecl();
1432     return;
1433 
1434   case IsTupleLike::NotTupleLike:
1435     break;
1436   }
1437 
1438   // C++1z [dcl.dcl]/8:
1439   //   [E shall be of array or non-union class type]
1440   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1441   if (!RD || RD->isUnion()) {
1442     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1443         << DD << !RD << DecompType;
1444     DD->setInvalidDecl();
1445     return;
1446   }
1447 
1448   // C++1z [dcl.decomp]/4:
1449   //   all of E's non-static data members shall be [...] direct members of
1450   //   E or of the same unambiguous public base class of E, ...
1451   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1452     DD->setInvalidDecl();
1453 }
1454 
1455 /// Merge the exception specifications of two variable declarations.
1456 ///
1457 /// This is called when there's a redeclaration of a VarDecl. The function
1458 /// checks if the redeclaration might have an exception specification and
1459 /// validates compatibility and merges the specs if necessary.
1460 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1461   // Shortcut if exceptions are disabled.
1462   if (!getLangOpts().CXXExceptions)
1463     return;
1464 
1465   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1466          "Should only be called if types are otherwise the same.");
1467 
1468   QualType NewType = New->getType();
1469   QualType OldType = Old->getType();
1470 
1471   // We're only interested in pointers and references to functions, as well
1472   // as pointers to member functions.
1473   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1474     NewType = R->getPointeeType();
1475     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1476   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1477     NewType = P->getPointeeType();
1478     OldType = OldType->getAs<PointerType>()->getPointeeType();
1479   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1480     NewType = M->getPointeeType();
1481     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1482   }
1483 
1484   if (!NewType->isFunctionProtoType())
1485     return;
1486 
1487   // There's lots of special cases for functions. For function pointers, system
1488   // libraries are hopefully not as broken so that we don't need these
1489   // workarounds.
1490   if (CheckEquivalentExceptionSpec(
1491         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1492         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1493     New->setInvalidDecl();
1494   }
1495 }
1496 
1497 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1498 /// function declaration are well-formed according to C++
1499 /// [dcl.fct.default].
1500 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1501   unsigned NumParams = FD->getNumParams();
1502   unsigned p;
1503 
1504   // Find first parameter with a default argument
1505   for (p = 0; p < NumParams; ++p) {
1506     ParmVarDecl *Param = FD->getParamDecl(p);
1507     if (Param->hasDefaultArg())
1508       break;
1509   }
1510 
1511   // C++11 [dcl.fct.default]p4:
1512   //   In a given function declaration, each parameter subsequent to a parameter
1513   //   with a default argument shall have a default argument supplied in this or
1514   //   a previous declaration or shall be a function parameter pack. A default
1515   //   argument shall not be redefined by a later declaration (not even to the
1516   //   same value).
1517   unsigned LastMissingDefaultArg = 0;
1518   for (; p < NumParams; ++p) {
1519     ParmVarDecl *Param = FD->getParamDecl(p);
1520     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1521       if (Param->isInvalidDecl())
1522         /* We already complained about this parameter. */;
1523       else if (Param->getIdentifier())
1524         Diag(Param->getLocation(),
1525              diag::err_param_default_argument_missing_name)
1526           << Param->getIdentifier();
1527       else
1528         Diag(Param->getLocation(),
1529              diag::err_param_default_argument_missing);
1530 
1531       LastMissingDefaultArg = p;
1532     }
1533   }
1534 
1535   if (LastMissingDefaultArg > 0) {
1536     // Some default arguments were missing. Clear out all of the
1537     // default arguments up to (and including) the last missing
1538     // default argument, so that we leave the function parameters
1539     // in a semantically valid state.
1540     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1541       ParmVarDecl *Param = FD->getParamDecl(p);
1542       if (Param->hasDefaultArg()) {
1543         Param->setDefaultArg(nullptr);
1544       }
1545     }
1546   }
1547 }
1548 
1549 // CheckConstexprParameterTypes - Check whether a function's parameter types
1550 // are all literal types. If so, return true. If not, produce a suitable
1551 // diagnostic and return false.
1552 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1553                                          const FunctionDecl *FD) {
1554   unsigned ArgIndex = 0;
1555   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1556   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1557                                               e = FT->param_type_end();
1558        i != e; ++i, ++ArgIndex) {
1559     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1560     SourceLocation ParamLoc = PD->getLocation();
1561     if (!(*i)->isDependentType() &&
1562         SemaRef.RequireLiteralType(ParamLoc, *i,
1563                                    diag::err_constexpr_non_literal_param,
1564                                    ArgIndex+1, PD->getSourceRange(),
1565                                    isa<CXXConstructorDecl>(FD)))
1566       return false;
1567   }
1568   return true;
1569 }
1570 
1571 /// Get diagnostic %select index for tag kind for
1572 /// record diagnostic message.
1573 /// WARNING: Indexes apply to particular diagnostics only!
1574 ///
1575 /// \returns diagnostic %select index.
1576 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1577   switch (Tag) {
1578   case TTK_Struct: return 0;
1579   case TTK_Interface: return 1;
1580   case TTK_Class:  return 2;
1581   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1582   }
1583 }
1584 
1585 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1586 // the requirements of a constexpr function definition or a constexpr
1587 // constructor definition. If so, return true. If not, produce appropriate
1588 // diagnostics and return false.
1589 //
1590 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1591 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1592   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1593   if (MD && MD->isInstance()) {
1594     // C++11 [dcl.constexpr]p4:
1595     //  The definition of a constexpr constructor shall satisfy the following
1596     //  constraints:
1597     //  - the class shall not have any virtual base classes;
1598     const CXXRecordDecl *RD = MD->getParent();
1599     if (RD->getNumVBases()) {
1600       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1601         << isa<CXXConstructorDecl>(NewFD)
1602         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1603       for (const auto &I : RD->vbases())
1604         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1605             << I.getSourceRange();
1606       return false;
1607     }
1608   }
1609 
1610   if (!isa<CXXConstructorDecl>(NewFD)) {
1611     // C++11 [dcl.constexpr]p3:
1612     //  The definition of a constexpr function shall satisfy the following
1613     //  constraints:
1614     // - it shall not be virtual;
1615     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1616     if (Method && Method->isVirtual()) {
1617       Method = Method->getCanonicalDecl();
1618       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1619 
1620       // If it's not obvious why this function is virtual, find an overridden
1621       // function which uses the 'virtual' keyword.
1622       const CXXMethodDecl *WrittenVirtual = Method;
1623       while (!WrittenVirtual->isVirtualAsWritten())
1624         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1625       if (WrittenVirtual != Method)
1626         Diag(WrittenVirtual->getLocation(),
1627              diag::note_overridden_virtual_function);
1628       return false;
1629     }
1630 
1631     // - its return type shall be a literal type;
1632     QualType RT = NewFD->getReturnType();
1633     if (!RT->isDependentType() &&
1634         RequireLiteralType(NewFD->getLocation(), RT,
1635                            diag::err_constexpr_non_literal_return))
1636       return false;
1637   }
1638 
1639   // - each of its parameter types shall be a literal type;
1640   if (!CheckConstexprParameterTypes(*this, NewFD))
1641     return false;
1642 
1643   return true;
1644 }
1645 
1646 /// Check the given declaration statement is legal within a constexpr function
1647 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1648 ///
1649 /// \return true if the body is OK (maybe only as an extension), false if we
1650 ///         have diagnosed a problem.
1651 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1652                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1653   // C++11 [dcl.constexpr]p3 and p4:
1654   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1655   //  contain only
1656   for (const auto *DclIt : DS->decls()) {
1657     switch (DclIt->getKind()) {
1658     case Decl::StaticAssert:
1659     case Decl::Using:
1660     case Decl::UsingShadow:
1661     case Decl::UsingDirective:
1662     case Decl::UnresolvedUsingTypename:
1663     case Decl::UnresolvedUsingValue:
1664       //   - static_assert-declarations
1665       //   - using-declarations,
1666       //   - using-directives,
1667       continue;
1668 
1669     case Decl::Typedef:
1670     case Decl::TypeAlias: {
1671       //   - typedef declarations and alias-declarations that do not define
1672       //     classes or enumerations,
1673       const auto *TN = cast<TypedefNameDecl>(DclIt);
1674       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1675         // Don't allow variably-modified types in constexpr functions.
1676         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1677         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1678           << TL.getSourceRange() << TL.getType()
1679           << isa<CXXConstructorDecl>(Dcl);
1680         return false;
1681       }
1682       continue;
1683     }
1684 
1685     case Decl::Enum:
1686     case Decl::CXXRecord:
1687       // C++1y allows types to be defined, not just declared.
1688       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1689         SemaRef.Diag(DS->getBeginLoc(),
1690                      SemaRef.getLangOpts().CPlusPlus14
1691                          ? diag::warn_cxx11_compat_constexpr_type_definition
1692                          : diag::ext_constexpr_type_definition)
1693             << isa<CXXConstructorDecl>(Dcl);
1694       continue;
1695 
1696     case Decl::EnumConstant:
1697     case Decl::IndirectField:
1698     case Decl::ParmVar:
1699       // These can only appear with other declarations which are banned in
1700       // C++11 and permitted in C++1y, so ignore them.
1701       continue;
1702 
1703     case Decl::Var:
1704     case Decl::Decomposition: {
1705       // C++1y [dcl.constexpr]p3 allows anything except:
1706       //   a definition of a variable of non-literal type or of static or
1707       //   thread storage duration or for which no initialization is performed.
1708       const auto *VD = cast<VarDecl>(DclIt);
1709       if (VD->isThisDeclarationADefinition()) {
1710         if (VD->isStaticLocal()) {
1711           SemaRef.Diag(VD->getLocation(),
1712                        diag::err_constexpr_local_var_static)
1713             << isa<CXXConstructorDecl>(Dcl)
1714             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1715           return false;
1716         }
1717         if (!VD->getType()->isDependentType() &&
1718             SemaRef.RequireLiteralType(
1719               VD->getLocation(), VD->getType(),
1720               diag::err_constexpr_local_var_non_literal_type,
1721               isa<CXXConstructorDecl>(Dcl)))
1722           return false;
1723         if (!VD->getType()->isDependentType() &&
1724             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1725           SemaRef.Diag(VD->getLocation(),
1726                        diag::err_constexpr_local_var_no_init)
1727             << isa<CXXConstructorDecl>(Dcl);
1728           return false;
1729         }
1730       }
1731       SemaRef.Diag(VD->getLocation(),
1732                    SemaRef.getLangOpts().CPlusPlus14
1733                     ? diag::warn_cxx11_compat_constexpr_local_var
1734                     : diag::ext_constexpr_local_var)
1735         << isa<CXXConstructorDecl>(Dcl);
1736       continue;
1737     }
1738 
1739     case Decl::NamespaceAlias:
1740     case Decl::Function:
1741       // These are disallowed in C++11 and permitted in C++1y. Allow them
1742       // everywhere as an extension.
1743       if (!Cxx1yLoc.isValid())
1744         Cxx1yLoc = DS->getBeginLoc();
1745       continue;
1746 
1747     default:
1748       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1749           << isa<CXXConstructorDecl>(Dcl);
1750       return false;
1751     }
1752   }
1753 
1754   return true;
1755 }
1756 
1757 /// Check that the given field is initialized within a constexpr constructor.
1758 ///
1759 /// \param Dcl The constexpr constructor being checked.
1760 /// \param Field The field being checked. This may be a member of an anonymous
1761 ///        struct or union nested within the class being checked.
1762 /// \param Inits All declarations, including anonymous struct/union members and
1763 ///        indirect members, for which any initialization was provided.
1764 /// \param Diagnosed Set to true if an error is produced.
1765 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1766                                           const FunctionDecl *Dcl,
1767                                           FieldDecl *Field,
1768                                           llvm::SmallSet<Decl*, 16> &Inits,
1769                                           bool &Diagnosed) {
1770   if (Field->isInvalidDecl())
1771     return;
1772 
1773   if (Field->isUnnamedBitfield())
1774     return;
1775 
1776   // Anonymous unions with no variant members and empty anonymous structs do not
1777   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1778   // indirect fields don't need initializing.
1779   if (Field->isAnonymousStructOrUnion() &&
1780       (Field->getType()->isUnionType()
1781            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1782            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1783     return;
1784 
1785   if (!Inits.count(Field)) {
1786     if (!Diagnosed) {
1787       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1788       Diagnosed = true;
1789     }
1790     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1791   } else if (Field->isAnonymousStructOrUnion()) {
1792     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1793     for (auto *I : RD->fields())
1794       // If an anonymous union contains an anonymous struct of which any member
1795       // is initialized, all members must be initialized.
1796       if (!RD->isUnion() || Inits.count(I))
1797         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1798   }
1799 }
1800 
1801 /// Check the provided statement is allowed in a constexpr function
1802 /// definition.
1803 static bool
1804 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1805                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1806                            SourceLocation &Cxx1yLoc) {
1807   // - its function-body shall be [...] a compound-statement that contains only
1808   switch (S->getStmtClass()) {
1809   case Stmt::NullStmtClass:
1810     //   - null statements,
1811     return true;
1812 
1813   case Stmt::DeclStmtClass:
1814     //   - static_assert-declarations
1815     //   - using-declarations,
1816     //   - using-directives,
1817     //   - typedef declarations and alias-declarations that do not define
1818     //     classes or enumerations,
1819     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1820       return false;
1821     return true;
1822 
1823   case Stmt::ReturnStmtClass:
1824     //   - and exactly one return statement;
1825     if (isa<CXXConstructorDecl>(Dcl)) {
1826       // C++1y allows return statements in constexpr constructors.
1827       if (!Cxx1yLoc.isValid())
1828         Cxx1yLoc = S->getBeginLoc();
1829       return true;
1830     }
1831 
1832     ReturnStmts.push_back(S->getBeginLoc());
1833     return true;
1834 
1835   case Stmt::CompoundStmtClass: {
1836     // C++1y allows compound-statements.
1837     if (!Cxx1yLoc.isValid())
1838       Cxx1yLoc = S->getBeginLoc();
1839 
1840     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1841     for (auto *BodyIt : CompStmt->body()) {
1842       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1843                                       Cxx1yLoc))
1844         return false;
1845     }
1846     return true;
1847   }
1848 
1849   case Stmt::AttributedStmtClass:
1850     if (!Cxx1yLoc.isValid())
1851       Cxx1yLoc = S->getBeginLoc();
1852     return true;
1853 
1854   case Stmt::IfStmtClass: {
1855     // C++1y allows if-statements.
1856     if (!Cxx1yLoc.isValid())
1857       Cxx1yLoc = S->getBeginLoc();
1858 
1859     IfStmt *If = cast<IfStmt>(S);
1860     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1861                                     Cxx1yLoc))
1862       return false;
1863     if (If->getElse() &&
1864         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1865                                     Cxx1yLoc))
1866       return false;
1867     return true;
1868   }
1869 
1870   case Stmt::WhileStmtClass:
1871   case Stmt::DoStmtClass:
1872   case Stmt::ForStmtClass:
1873   case Stmt::CXXForRangeStmtClass:
1874   case Stmt::ContinueStmtClass:
1875     // C++1y allows all of these. We don't allow them as extensions in C++11,
1876     // because they don't make sense without variable mutation.
1877     if (!SemaRef.getLangOpts().CPlusPlus14)
1878       break;
1879     if (!Cxx1yLoc.isValid())
1880       Cxx1yLoc = S->getBeginLoc();
1881     for (Stmt *SubStmt : S->children())
1882       if (SubStmt &&
1883           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1884                                       Cxx1yLoc))
1885         return false;
1886     return true;
1887 
1888   case Stmt::SwitchStmtClass:
1889   case Stmt::CaseStmtClass:
1890   case Stmt::DefaultStmtClass:
1891   case Stmt::BreakStmtClass:
1892     // C++1y allows switch-statements, and since they don't need variable
1893     // mutation, we can reasonably allow them in C++11 as an extension.
1894     if (!Cxx1yLoc.isValid())
1895       Cxx1yLoc = S->getBeginLoc();
1896     for (Stmt *SubStmt : S->children())
1897       if (SubStmt &&
1898           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1899                                       Cxx1yLoc))
1900         return false;
1901     return true;
1902 
1903   default:
1904     if (!isa<Expr>(S))
1905       break;
1906 
1907     // C++1y allows expression-statements.
1908     if (!Cxx1yLoc.isValid())
1909       Cxx1yLoc = S->getBeginLoc();
1910     return true;
1911   }
1912 
1913   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1914       << isa<CXXConstructorDecl>(Dcl);
1915   return false;
1916 }
1917 
1918 /// Check the body for the given constexpr function declaration only contains
1919 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1920 ///
1921 /// \return true if the body is OK, false if we have diagnosed a problem.
1922 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1923   if (isa<CXXTryStmt>(Body)) {
1924     // C++11 [dcl.constexpr]p3:
1925     //  The definition of a constexpr function shall satisfy the following
1926     //  constraints: [...]
1927     // - its function-body shall be = delete, = default, or a
1928     //   compound-statement
1929     //
1930     // C++11 [dcl.constexpr]p4:
1931     //  In the definition of a constexpr constructor, [...]
1932     // - its function-body shall not be a function-try-block;
1933     Diag(Body->getBeginLoc(), diag::err_constexpr_function_try_block)
1934         << isa<CXXConstructorDecl>(Dcl);
1935     return false;
1936   }
1937 
1938   SmallVector<SourceLocation, 4> ReturnStmts;
1939 
1940   // - its function-body shall be [...] a compound-statement that contains only
1941   //   [... list of cases ...]
1942   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1943   SourceLocation Cxx1yLoc;
1944   for (auto *BodyIt : CompBody->body()) {
1945     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1946       return false;
1947   }
1948 
1949   if (Cxx1yLoc.isValid())
1950     Diag(Cxx1yLoc,
1951          getLangOpts().CPlusPlus14
1952            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1953            : diag::ext_constexpr_body_invalid_stmt)
1954       << isa<CXXConstructorDecl>(Dcl);
1955 
1956   if (const CXXConstructorDecl *Constructor
1957         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1958     const CXXRecordDecl *RD = Constructor->getParent();
1959     // DR1359:
1960     // - every non-variant non-static data member and base class sub-object
1961     //   shall be initialized;
1962     // DR1460:
1963     // - if the class is a union having variant members, exactly one of them
1964     //   shall be initialized;
1965     if (RD->isUnion()) {
1966       if (Constructor->getNumCtorInitializers() == 0 &&
1967           RD->hasVariantMembers()) {
1968         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1969         return false;
1970       }
1971     } else if (!Constructor->isDependentContext() &&
1972                !Constructor->isDelegatingConstructor()) {
1973       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1974 
1975       // Skip detailed checking if we have enough initializers, and we would
1976       // allow at most one initializer per member.
1977       bool AnyAnonStructUnionMembers = false;
1978       unsigned Fields = 0;
1979       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1980            E = RD->field_end(); I != E; ++I, ++Fields) {
1981         if (I->isAnonymousStructOrUnion()) {
1982           AnyAnonStructUnionMembers = true;
1983           break;
1984         }
1985       }
1986       // DR1460:
1987       // - if the class is a union-like class, but is not a union, for each of
1988       //   its anonymous union members having variant members, exactly one of
1989       //   them shall be initialized;
1990       if (AnyAnonStructUnionMembers ||
1991           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1992         // Check initialization of non-static data members. Base classes are
1993         // always initialized so do not need to be checked. Dependent bases
1994         // might not have initializers in the member initializer list.
1995         llvm::SmallSet<Decl*, 16> Inits;
1996         for (const auto *I: Constructor->inits()) {
1997           if (FieldDecl *FD = I->getMember())
1998             Inits.insert(FD);
1999           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2000             Inits.insert(ID->chain_begin(), ID->chain_end());
2001         }
2002 
2003         bool Diagnosed = false;
2004         for (auto *I : RD->fields())
2005           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2006         if (Diagnosed)
2007           return false;
2008       }
2009     }
2010   } else {
2011     if (ReturnStmts.empty()) {
2012       // C++1y doesn't require constexpr functions to contain a 'return'
2013       // statement. We still do, unless the return type might be void, because
2014       // otherwise if there's no return statement, the function cannot
2015       // be used in a core constant expression.
2016       bool OK = getLangOpts().CPlusPlus14 &&
2017                 (Dcl->getReturnType()->isVoidType() ||
2018                  Dcl->getReturnType()->isDependentType());
2019       Diag(Dcl->getLocation(),
2020            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2021               : diag::err_constexpr_body_no_return);
2022       if (!OK)
2023         return false;
2024     } else if (ReturnStmts.size() > 1) {
2025       Diag(ReturnStmts.back(),
2026            getLangOpts().CPlusPlus14
2027              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2028              : diag::ext_constexpr_body_multiple_return);
2029       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2030         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2031     }
2032   }
2033 
2034   // C++11 [dcl.constexpr]p5:
2035   //   if no function argument values exist such that the function invocation
2036   //   substitution would produce a constant expression, the program is
2037   //   ill-formed; no diagnostic required.
2038   // C++11 [dcl.constexpr]p3:
2039   //   - every constructor call and implicit conversion used in initializing the
2040   //     return value shall be one of those allowed in a constant expression.
2041   // C++11 [dcl.constexpr]p4:
2042   //   - every constructor involved in initializing non-static data members and
2043   //     base class sub-objects shall be a constexpr constructor.
2044   SmallVector<PartialDiagnosticAt, 8> Diags;
2045   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2046     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2047       << isa<CXXConstructorDecl>(Dcl);
2048     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2049       Diag(Diags[I].first, Diags[I].second);
2050     // Don't return false here: we allow this for compatibility in
2051     // system headers.
2052   }
2053 
2054   return true;
2055 }
2056 
2057 /// Get the class that is directly named by the current context. This is the
2058 /// class for which an unqualified-id in this scope could name a constructor
2059 /// or destructor.
2060 ///
2061 /// If the scope specifier denotes a class, this will be that class.
2062 /// If the scope specifier is empty, this will be the class whose
2063 /// member-specification we are currently within. Otherwise, there
2064 /// is no such class.
2065 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2066   assert(getLangOpts().CPlusPlus && "No class names in C!");
2067 
2068   if (SS && SS->isInvalid())
2069     return nullptr;
2070 
2071   if (SS && SS->isNotEmpty()) {
2072     DeclContext *DC = computeDeclContext(*SS, true);
2073     return dyn_cast_or_null<CXXRecordDecl>(DC);
2074   }
2075 
2076   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2077 }
2078 
2079 /// isCurrentClassName - Determine whether the identifier II is the
2080 /// name of the class type currently being defined. In the case of
2081 /// nested classes, this will only return true if II is the name of
2082 /// the innermost class.
2083 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2084                               const CXXScopeSpec *SS) {
2085   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2086   return CurDecl && &II == CurDecl->getIdentifier();
2087 }
2088 
2089 /// Determine whether the identifier II is a typo for the name of
2090 /// the class type currently being defined. If so, update it to the identifier
2091 /// that should have been used.
2092 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2093   assert(getLangOpts().CPlusPlus && "No class names in C!");
2094 
2095   if (!getLangOpts().SpellChecking)
2096     return false;
2097 
2098   CXXRecordDecl *CurDecl;
2099   if (SS && SS->isSet() && !SS->isInvalid()) {
2100     DeclContext *DC = computeDeclContext(*SS, true);
2101     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2102   } else
2103     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2104 
2105   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2106       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2107           < II->getLength()) {
2108     II = CurDecl->getIdentifier();
2109     return true;
2110   }
2111 
2112   return false;
2113 }
2114 
2115 /// Determine whether the given class is a base class of the given
2116 /// class, including looking at dependent bases.
2117 static bool findCircularInheritance(const CXXRecordDecl *Class,
2118                                     const CXXRecordDecl *Current) {
2119   SmallVector<const CXXRecordDecl*, 8> Queue;
2120 
2121   Class = Class->getCanonicalDecl();
2122   while (true) {
2123     for (const auto &I : Current->bases()) {
2124       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2125       if (!Base)
2126         continue;
2127 
2128       Base = Base->getDefinition();
2129       if (!Base)
2130         continue;
2131 
2132       if (Base->getCanonicalDecl() == Class)
2133         return true;
2134 
2135       Queue.push_back(Base);
2136     }
2137 
2138     if (Queue.empty())
2139       return false;
2140 
2141     Current = Queue.pop_back_val();
2142   }
2143 
2144   return false;
2145 }
2146 
2147 /// Check the validity of a C++ base class specifier.
2148 ///
2149 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2150 /// and returns NULL otherwise.
2151 CXXBaseSpecifier *
2152 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2153                          SourceRange SpecifierRange,
2154                          bool Virtual, AccessSpecifier Access,
2155                          TypeSourceInfo *TInfo,
2156                          SourceLocation EllipsisLoc) {
2157   QualType BaseType = TInfo->getType();
2158 
2159   // C++ [class.union]p1:
2160   //   A union shall not have base classes.
2161   if (Class->isUnion()) {
2162     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2163       << SpecifierRange;
2164     return nullptr;
2165   }
2166 
2167   if (EllipsisLoc.isValid() &&
2168       !TInfo->getType()->containsUnexpandedParameterPack()) {
2169     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2170       << TInfo->getTypeLoc().getSourceRange();
2171     EllipsisLoc = SourceLocation();
2172   }
2173 
2174   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2175 
2176   if (BaseType->isDependentType()) {
2177     // Make sure that we don't have circular inheritance among our dependent
2178     // bases. For non-dependent bases, the check for completeness below handles
2179     // this.
2180     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2181       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2182           ((BaseDecl = BaseDecl->getDefinition()) &&
2183            findCircularInheritance(Class, BaseDecl))) {
2184         Diag(BaseLoc, diag::err_circular_inheritance)
2185           << BaseType << Context.getTypeDeclType(Class);
2186 
2187         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2188           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2189             << BaseType;
2190 
2191         return nullptr;
2192       }
2193     }
2194 
2195     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2196                                           Class->getTagKind() == TTK_Class,
2197                                           Access, TInfo, EllipsisLoc);
2198   }
2199 
2200   // Base specifiers must be record types.
2201   if (!BaseType->isRecordType()) {
2202     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2203     return nullptr;
2204   }
2205 
2206   // C++ [class.union]p1:
2207   //   A union shall not be used as a base class.
2208   if (BaseType->isUnionType()) {
2209     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2210     return nullptr;
2211   }
2212 
2213   // For the MS ABI, propagate DLL attributes to base class templates.
2214   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2215     if (Attr *ClassAttr = getDLLAttr(Class)) {
2216       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2217               BaseType->getAsCXXRecordDecl())) {
2218         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2219                                             BaseLoc);
2220       }
2221     }
2222   }
2223 
2224   // C++ [class.derived]p2:
2225   //   The class-name in a base-specifier shall not be an incompletely
2226   //   defined class.
2227   if (RequireCompleteType(BaseLoc, BaseType,
2228                           diag::err_incomplete_base_class, SpecifierRange)) {
2229     Class->setInvalidDecl();
2230     return nullptr;
2231   }
2232 
2233   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2234   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2235   assert(BaseDecl && "Record type has no declaration");
2236   BaseDecl = BaseDecl->getDefinition();
2237   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2238   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2239   assert(CXXBaseDecl && "Base type is not a C++ type");
2240 
2241   // Microsoft docs say:
2242   // "If a base-class has a code_seg attribute, derived classes must have the
2243   // same attribute."
2244   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2245   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2246   if ((DerivedCSA || BaseCSA) &&
2247       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2248     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2249     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2250       << CXXBaseDecl;
2251     return nullptr;
2252   }
2253 
2254   // A class which contains a flexible array member is not suitable for use as a
2255   // base class:
2256   //   - If the layout determines that a base comes before another base,
2257   //     the flexible array member would index into the subsequent base.
2258   //   - If the layout determines that base comes before the derived class,
2259   //     the flexible array member would index into the derived class.
2260   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2261     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2262       << CXXBaseDecl->getDeclName();
2263     return nullptr;
2264   }
2265 
2266   // C++ [class]p3:
2267   //   If a class is marked final and it appears as a base-type-specifier in
2268   //   base-clause, the program is ill-formed.
2269   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2270     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2271       << CXXBaseDecl->getDeclName()
2272       << FA->isSpelledAsSealed();
2273     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2274         << CXXBaseDecl->getDeclName() << FA->getRange();
2275     return nullptr;
2276   }
2277 
2278   if (BaseDecl->isInvalidDecl())
2279     Class->setInvalidDecl();
2280 
2281   // Create the base specifier.
2282   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2283                                         Class->getTagKind() == TTK_Class,
2284                                         Access, TInfo, EllipsisLoc);
2285 }
2286 
2287 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2288 /// one entry in the base class list of a class specifier, for
2289 /// example:
2290 ///    class foo : public bar, virtual private baz {
2291 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2292 BaseResult
2293 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2294                          ParsedAttributes &Attributes,
2295                          bool Virtual, AccessSpecifier Access,
2296                          ParsedType basetype, SourceLocation BaseLoc,
2297                          SourceLocation EllipsisLoc) {
2298   if (!classdecl)
2299     return true;
2300 
2301   AdjustDeclIfTemplate(classdecl);
2302   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2303   if (!Class)
2304     return true;
2305 
2306   // We haven't yet attached the base specifiers.
2307   Class->setIsParsingBaseSpecifiers();
2308 
2309   // We do not support any C++11 attributes on base-specifiers yet.
2310   // Diagnose any attributes we see.
2311   for (const ParsedAttr &AL : Attributes) {
2312     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2313       continue;
2314     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2315                           ? diag::warn_unknown_attribute_ignored
2316                           : diag::err_base_specifier_attribute)
2317         << AL.getName();
2318   }
2319 
2320   TypeSourceInfo *TInfo = nullptr;
2321   GetTypeFromParser(basetype, &TInfo);
2322 
2323   if (EllipsisLoc.isInvalid() &&
2324       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2325                                       UPPC_BaseType))
2326     return true;
2327 
2328   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2329                                                       Virtual, Access, TInfo,
2330                                                       EllipsisLoc))
2331     return BaseSpec;
2332   else
2333     Class->setInvalidDecl();
2334 
2335   return true;
2336 }
2337 
2338 /// Use small set to collect indirect bases.  As this is only used
2339 /// locally, there's no need to abstract the small size parameter.
2340 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2341 
2342 /// Recursively add the bases of Type.  Don't add Type itself.
2343 static void
2344 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2345                   const QualType &Type)
2346 {
2347   // Even though the incoming type is a base, it might not be
2348   // a class -- it could be a template parm, for instance.
2349   if (auto Rec = Type->getAs<RecordType>()) {
2350     auto Decl = Rec->getAsCXXRecordDecl();
2351 
2352     // Iterate over its bases.
2353     for (const auto &BaseSpec : Decl->bases()) {
2354       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2355         .getUnqualifiedType();
2356       if (Set.insert(Base).second)
2357         // If we've not already seen it, recurse.
2358         NoteIndirectBases(Context, Set, Base);
2359     }
2360   }
2361 }
2362 
2363 /// Performs the actual work of attaching the given base class
2364 /// specifiers to a C++ class.
2365 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2366                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2367  if (Bases.empty())
2368     return false;
2369 
2370   // Used to keep track of which base types we have already seen, so
2371   // that we can properly diagnose redundant direct base types. Note
2372   // that the key is always the unqualified canonical type of the base
2373   // class.
2374   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2375 
2376   // Used to track indirect bases so we can see if a direct base is
2377   // ambiguous.
2378   IndirectBaseSet IndirectBaseTypes;
2379 
2380   // Copy non-redundant base specifiers into permanent storage.
2381   unsigned NumGoodBases = 0;
2382   bool Invalid = false;
2383   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2384     QualType NewBaseType
2385       = Context.getCanonicalType(Bases[idx]->getType());
2386     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2387 
2388     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2389     if (KnownBase) {
2390       // C++ [class.mi]p3:
2391       //   A class shall not be specified as a direct base class of a
2392       //   derived class more than once.
2393       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2394           << KnownBase->getType() << Bases[idx]->getSourceRange();
2395 
2396       // Delete the duplicate base class specifier; we're going to
2397       // overwrite its pointer later.
2398       Context.Deallocate(Bases[idx]);
2399 
2400       Invalid = true;
2401     } else {
2402       // Okay, add this new base class.
2403       KnownBase = Bases[idx];
2404       Bases[NumGoodBases++] = Bases[idx];
2405 
2406       // Note this base's direct & indirect bases, if there could be ambiguity.
2407       if (Bases.size() > 1)
2408         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2409 
2410       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2411         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2412         if (Class->isInterface() &&
2413               (!RD->isInterfaceLike() ||
2414                KnownBase->getAccessSpecifier() != AS_public)) {
2415           // The Microsoft extension __interface does not permit bases that
2416           // are not themselves public interfaces.
2417           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2418               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2419               << RD->getSourceRange();
2420           Invalid = true;
2421         }
2422         if (RD->hasAttr<WeakAttr>())
2423           Class->addAttr(WeakAttr::CreateImplicit(Context));
2424       }
2425     }
2426   }
2427 
2428   // Attach the remaining base class specifiers to the derived class.
2429   Class->setBases(Bases.data(), NumGoodBases);
2430 
2431   // Check that the only base classes that are duplicate are virtual.
2432   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2433     // Check whether this direct base is inaccessible due to ambiguity.
2434     QualType BaseType = Bases[idx]->getType();
2435 
2436     // Skip all dependent types in templates being used as base specifiers.
2437     // Checks below assume that the base specifier is a CXXRecord.
2438     if (BaseType->isDependentType())
2439       continue;
2440 
2441     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2442       .getUnqualifiedType();
2443 
2444     if (IndirectBaseTypes.count(CanonicalBase)) {
2445       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2446                          /*DetectVirtual=*/true);
2447       bool found
2448         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2449       assert(found);
2450       (void)found;
2451 
2452       if (Paths.isAmbiguous(CanonicalBase))
2453         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2454             << BaseType << getAmbiguousPathsDisplayString(Paths)
2455             << Bases[idx]->getSourceRange();
2456       else
2457         assert(Bases[idx]->isVirtual());
2458     }
2459 
2460     // Delete the base class specifier, since its data has been copied
2461     // into the CXXRecordDecl.
2462     Context.Deallocate(Bases[idx]);
2463   }
2464 
2465   return Invalid;
2466 }
2467 
2468 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2469 /// class, after checking whether there are any duplicate base
2470 /// classes.
2471 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2472                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2473   if (!ClassDecl || Bases.empty())
2474     return;
2475 
2476   AdjustDeclIfTemplate(ClassDecl);
2477   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2478 }
2479 
2480 /// Determine whether the type \p Derived is a C++ class that is
2481 /// derived from the type \p Base.
2482 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2483   if (!getLangOpts().CPlusPlus)
2484     return false;
2485 
2486   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2487   if (!DerivedRD)
2488     return false;
2489 
2490   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2491   if (!BaseRD)
2492     return false;
2493 
2494   // If either the base or the derived type is invalid, don't try to
2495   // check whether one is derived from the other.
2496   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2497     return false;
2498 
2499   // FIXME: In a modules build, do we need the entire path to be visible for us
2500   // to be able to use the inheritance relationship?
2501   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2502     return false;
2503 
2504   return DerivedRD->isDerivedFrom(BaseRD);
2505 }
2506 
2507 /// Determine whether the type \p Derived is a C++ class that is
2508 /// derived from the type \p Base.
2509 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2510                          CXXBasePaths &Paths) {
2511   if (!getLangOpts().CPlusPlus)
2512     return false;
2513 
2514   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2515   if (!DerivedRD)
2516     return false;
2517 
2518   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2519   if (!BaseRD)
2520     return false;
2521 
2522   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2523     return false;
2524 
2525   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2526 }
2527 
2528 static void BuildBasePathArray(const CXXBasePath &Path,
2529                                CXXCastPath &BasePathArray) {
2530   // We first go backward and check if we have a virtual base.
2531   // FIXME: It would be better if CXXBasePath had the base specifier for
2532   // the nearest virtual base.
2533   unsigned Start = 0;
2534   for (unsigned I = Path.size(); I != 0; --I) {
2535     if (Path[I - 1].Base->isVirtual()) {
2536       Start = I - 1;
2537       break;
2538     }
2539   }
2540 
2541   // Now add all bases.
2542   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2543     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2544 }
2545 
2546 
2547 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2548                               CXXCastPath &BasePathArray) {
2549   assert(BasePathArray.empty() && "Base path array must be empty!");
2550   assert(Paths.isRecordingPaths() && "Must record paths!");
2551   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2552 }
2553 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2554 /// conversion (where Derived and Base are class types) is
2555 /// well-formed, meaning that the conversion is unambiguous (and
2556 /// that all of the base classes are accessible). Returns true
2557 /// and emits a diagnostic if the code is ill-formed, returns false
2558 /// otherwise. Loc is the location where this routine should point to
2559 /// if there is an error, and Range is the source range to highlight
2560 /// if there is an error.
2561 ///
2562 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2563 /// diagnostic for the respective type of error will be suppressed, but the
2564 /// check for ill-formed code will still be performed.
2565 bool
2566 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2567                                    unsigned InaccessibleBaseID,
2568                                    unsigned AmbigiousBaseConvID,
2569                                    SourceLocation Loc, SourceRange Range,
2570                                    DeclarationName Name,
2571                                    CXXCastPath *BasePath,
2572                                    bool IgnoreAccess) {
2573   // First, determine whether the path from Derived to Base is
2574   // ambiguous. This is slightly more expensive than checking whether
2575   // the Derived to Base conversion exists, because here we need to
2576   // explore multiple paths to determine if there is an ambiguity.
2577   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2578                      /*DetectVirtual=*/false);
2579   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2580   if (!DerivationOkay)
2581     return true;
2582 
2583   const CXXBasePath *Path = nullptr;
2584   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2585     Path = &Paths.front();
2586 
2587   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2588   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2589   // user to access such bases.
2590   if (!Path && getLangOpts().MSVCCompat) {
2591     for (const CXXBasePath &PossiblePath : Paths) {
2592       if (PossiblePath.size() == 1) {
2593         Path = &PossiblePath;
2594         if (AmbigiousBaseConvID)
2595           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2596               << Base << Derived << Range;
2597         break;
2598       }
2599     }
2600   }
2601 
2602   if (Path) {
2603     if (!IgnoreAccess) {
2604       // Check that the base class can be accessed.
2605       switch (
2606           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2607       case AR_inaccessible:
2608         return true;
2609       case AR_accessible:
2610       case AR_dependent:
2611       case AR_delayed:
2612         break;
2613       }
2614     }
2615 
2616     // Build a base path if necessary.
2617     if (BasePath)
2618       ::BuildBasePathArray(*Path, *BasePath);
2619     return false;
2620   }
2621 
2622   if (AmbigiousBaseConvID) {
2623     // We know that the derived-to-base conversion is ambiguous, and
2624     // we're going to produce a diagnostic. Perform the derived-to-base
2625     // search just one more time to compute all of the possible paths so
2626     // that we can print them out. This is more expensive than any of
2627     // the previous derived-to-base checks we've done, but at this point
2628     // performance isn't as much of an issue.
2629     Paths.clear();
2630     Paths.setRecordingPaths(true);
2631     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2632     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2633     (void)StillOkay;
2634 
2635     // Build up a textual representation of the ambiguous paths, e.g.,
2636     // D -> B -> A, that will be used to illustrate the ambiguous
2637     // conversions in the diagnostic. We only print one of the paths
2638     // to each base class subobject.
2639     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2640 
2641     Diag(Loc, AmbigiousBaseConvID)
2642     << Derived << Base << PathDisplayStr << Range << Name;
2643   }
2644   return true;
2645 }
2646 
2647 bool
2648 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2649                                    SourceLocation Loc, SourceRange Range,
2650                                    CXXCastPath *BasePath,
2651                                    bool IgnoreAccess) {
2652   return CheckDerivedToBaseConversion(
2653       Derived, Base, diag::err_upcast_to_inaccessible_base,
2654       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2655       BasePath, IgnoreAccess);
2656 }
2657 
2658 
2659 /// Builds a string representing ambiguous paths from a
2660 /// specific derived class to different subobjects of the same base
2661 /// class.
2662 ///
2663 /// This function builds a string that can be used in error messages
2664 /// to show the different paths that one can take through the
2665 /// inheritance hierarchy to go from the derived class to different
2666 /// subobjects of a base class. The result looks something like this:
2667 /// @code
2668 /// struct D -> struct B -> struct A
2669 /// struct D -> struct C -> struct A
2670 /// @endcode
2671 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2672   std::string PathDisplayStr;
2673   std::set<unsigned> DisplayedPaths;
2674   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2675        Path != Paths.end(); ++Path) {
2676     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2677       // We haven't displayed a path to this particular base
2678       // class subobject yet.
2679       PathDisplayStr += "\n    ";
2680       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2681       for (CXXBasePath::const_iterator Element = Path->begin();
2682            Element != Path->end(); ++Element)
2683         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2684     }
2685   }
2686 
2687   return PathDisplayStr;
2688 }
2689 
2690 //===----------------------------------------------------------------------===//
2691 // C++ class member Handling
2692 //===----------------------------------------------------------------------===//
2693 
2694 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2695 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2696                                 SourceLocation ColonLoc,
2697                                 const ParsedAttributesView &Attrs) {
2698   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2699   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2700                                                   ASLoc, ColonLoc);
2701   CurContext->addHiddenDecl(ASDecl);
2702   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2703 }
2704 
2705 /// CheckOverrideControl - Check C++11 override control semantics.
2706 void Sema::CheckOverrideControl(NamedDecl *D) {
2707   if (D->isInvalidDecl())
2708     return;
2709 
2710   // We only care about "override" and "final" declarations.
2711   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2712     return;
2713 
2714   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2715 
2716   // We can't check dependent instance methods.
2717   if (MD && MD->isInstance() &&
2718       (MD->getParent()->hasAnyDependentBases() ||
2719        MD->getType()->isDependentType()))
2720     return;
2721 
2722   if (MD && !MD->isVirtual()) {
2723     // If we have a non-virtual method, check if if hides a virtual method.
2724     // (In that case, it's most likely the method has the wrong type.)
2725     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2726     FindHiddenVirtualMethods(MD, OverloadedMethods);
2727 
2728     if (!OverloadedMethods.empty()) {
2729       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2730         Diag(OA->getLocation(),
2731              diag::override_keyword_hides_virtual_member_function)
2732           << "override" << (OverloadedMethods.size() > 1);
2733       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2734         Diag(FA->getLocation(),
2735              diag::override_keyword_hides_virtual_member_function)
2736           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2737           << (OverloadedMethods.size() > 1);
2738       }
2739       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2740       MD->setInvalidDecl();
2741       return;
2742     }
2743     // Fall through into the general case diagnostic.
2744     // FIXME: We might want to attempt typo correction here.
2745   }
2746 
2747   if (!MD || !MD->isVirtual()) {
2748     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2749       Diag(OA->getLocation(),
2750            diag::override_keyword_only_allowed_on_virtual_member_functions)
2751         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2752       D->dropAttr<OverrideAttr>();
2753     }
2754     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2755       Diag(FA->getLocation(),
2756            diag::override_keyword_only_allowed_on_virtual_member_functions)
2757         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2758         << FixItHint::CreateRemoval(FA->getLocation());
2759       D->dropAttr<FinalAttr>();
2760     }
2761     return;
2762   }
2763 
2764   // C++11 [class.virtual]p5:
2765   //   If a function is marked with the virt-specifier override and
2766   //   does not override a member function of a base class, the program is
2767   //   ill-formed.
2768   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2769   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2770     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2771       << MD->getDeclName();
2772 }
2773 
2774 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2775   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2776     return;
2777   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2778   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2779     return;
2780 
2781   SourceLocation Loc = MD->getLocation();
2782   SourceLocation SpellingLoc = Loc;
2783   if (getSourceManager().isMacroArgExpansion(Loc))
2784     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2785   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2786   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2787       return;
2788 
2789   if (MD->size_overridden_methods() > 0) {
2790     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2791                           ? diag::warn_destructor_marked_not_override_overriding
2792                           : diag::warn_function_marked_not_override_overriding;
2793     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2794     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2795     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2796   }
2797 }
2798 
2799 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2800 /// function overrides a virtual member function marked 'final', according to
2801 /// C++11 [class.virtual]p4.
2802 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2803                                                   const CXXMethodDecl *Old) {
2804   FinalAttr *FA = Old->getAttr<FinalAttr>();
2805   if (!FA)
2806     return false;
2807 
2808   Diag(New->getLocation(), diag::err_final_function_overridden)
2809     << New->getDeclName()
2810     << FA->isSpelledAsSealed();
2811   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2812   return true;
2813 }
2814 
2815 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2816   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2817   // FIXME: Destruction of ObjC lifetime types has side-effects.
2818   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2819     return !RD->isCompleteDefinition() ||
2820            !RD->hasTrivialDefaultConstructor() ||
2821            !RD->hasTrivialDestructor();
2822   return false;
2823 }
2824 
2825 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2826   ParsedAttributesView::const_iterator Itr =
2827       llvm::find_if(list, [](const ParsedAttr &AL) {
2828         return AL.isDeclspecPropertyAttribute();
2829       });
2830   if (Itr != list.end())
2831     return &*Itr;
2832   return nullptr;
2833 }
2834 
2835 // Check if there is a field shadowing.
2836 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2837                                       DeclarationName FieldName,
2838                                       const CXXRecordDecl *RD,
2839                                       bool DeclIsField) {
2840   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2841     return;
2842 
2843   // To record a shadowed field in a base
2844   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2845   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2846                            CXXBasePath &Path) {
2847     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2848     // Record an ambiguous path directly
2849     if (Bases.find(Base) != Bases.end())
2850       return true;
2851     for (const auto Field : Base->lookup(FieldName)) {
2852       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2853           Field->getAccess() != AS_private) {
2854         assert(Field->getAccess() != AS_none);
2855         assert(Bases.find(Base) == Bases.end());
2856         Bases[Base] = Field;
2857         return true;
2858       }
2859     }
2860     return false;
2861   };
2862 
2863   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2864                      /*DetectVirtual=*/true);
2865   if (!RD->lookupInBases(FieldShadowed, Paths))
2866     return;
2867 
2868   for (const auto &P : Paths) {
2869     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2870     auto It = Bases.find(Base);
2871     // Skip duplicated bases
2872     if (It == Bases.end())
2873       continue;
2874     auto BaseField = It->second;
2875     assert(BaseField->getAccess() != AS_private);
2876     if (AS_none !=
2877         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2878       Diag(Loc, diag::warn_shadow_field)
2879         << FieldName << RD << Base << DeclIsField;
2880       Diag(BaseField->getLocation(), diag::note_shadow_field);
2881       Bases.erase(It);
2882     }
2883   }
2884 }
2885 
2886 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2887 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2888 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2889 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2890 /// present (but parsing it has been deferred).
2891 NamedDecl *
2892 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2893                                MultiTemplateParamsArg TemplateParameterLists,
2894                                Expr *BW, const VirtSpecifiers &VS,
2895                                InClassInitStyle InitStyle) {
2896   const DeclSpec &DS = D.getDeclSpec();
2897   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2898   DeclarationName Name = NameInfo.getName();
2899   SourceLocation Loc = NameInfo.getLoc();
2900 
2901   // For anonymous bitfields, the location should point to the type.
2902   if (Loc.isInvalid())
2903     Loc = D.getBeginLoc();
2904 
2905   Expr *BitWidth = static_cast<Expr*>(BW);
2906 
2907   assert(isa<CXXRecordDecl>(CurContext));
2908   assert(!DS.isFriendSpecified());
2909 
2910   bool isFunc = D.isDeclarationOfFunction();
2911   const ParsedAttr *MSPropertyAttr =
2912       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2913 
2914   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2915     // The Microsoft extension __interface only permits public member functions
2916     // and prohibits constructors, destructors, operators, non-public member
2917     // functions, static methods and data members.
2918     unsigned InvalidDecl;
2919     bool ShowDeclName = true;
2920     if (!isFunc &&
2921         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2922       InvalidDecl = 0;
2923     else if (!isFunc)
2924       InvalidDecl = 1;
2925     else if (AS != AS_public)
2926       InvalidDecl = 2;
2927     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2928       InvalidDecl = 3;
2929     else switch (Name.getNameKind()) {
2930       case DeclarationName::CXXConstructorName:
2931         InvalidDecl = 4;
2932         ShowDeclName = false;
2933         break;
2934 
2935       case DeclarationName::CXXDestructorName:
2936         InvalidDecl = 5;
2937         ShowDeclName = false;
2938         break;
2939 
2940       case DeclarationName::CXXOperatorName:
2941       case DeclarationName::CXXConversionFunctionName:
2942         InvalidDecl = 6;
2943         break;
2944 
2945       default:
2946         InvalidDecl = 0;
2947         break;
2948     }
2949 
2950     if (InvalidDecl) {
2951       if (ShowDeclName)
2952         Diag(Loc, diag::err_invalid_member_in_interface)
2953           << (InvalidDecl-1) << Name;
2954       else
2955         Diag(Loc, diag::err_invalid_member_in_interface)
2956           << (InvalidDecl-1) << "";
2957       return nullptr;
2958     }
2959   }
2960 
2961   // C++ 9.2p6: A member shall not be declared to have automatic storage
2962   // duration (auto, register) or with the extern storage-class-specifier.
2963   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2964   // data members and cannot be applied to names declared const or static,
2965   // and cannot be applied to reference members.
2966   switch (DS.getStorageClassSpec()) {
2967   case DeclSpec::SCS_unspecified:
2968   case DeclSpec::SCS_typedef:
2969   case DeclSpec::SCS_static:
2970     break;
2971   case DeclSpec::SCS_mutable:
2972     if (isFunc) {
2973       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2974 
2975       // FIXME: It would be nicer if the keyword was ignored only for this
2976       // declarator. Otherwise we could get follow-up errors.
2977       D.getMutableDeclSpec().ClearStorageClassSpecs();
2978     }
2979     break;
2980   default:
2981     Diag(DS.getStorageClassSpecLoc(),
2982          diag::err_storageclass_invalid_for_member);
2983     D.getMutableDeclSpec().ClearStorageClassSpecs();
2984     break;
2985   }
2986 
2987   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2988                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2989                       !isFunc);
2990 
2991   if (DS.isConstexprSpecified() && isInstField) {
2992     SemaDiagnosticBuilder B =
2993         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2994     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2995     if (InitStyle == ICIS_NoInit) {
2996       B << 0 << 0;
2997       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2998         B << FixItHint::CreateRemoval(ConstexprLoc);
2999       else {
3000         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3001         D.getMutableDeclSpec().ClearConstexprSpec();
3002         const char *PrevSpec;
3003         unsigned DiagID;
3004         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3005             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3006         (void)Failed;
3007         assert(!Failed && "Making a constexpr member const shouldn't fail");
3008       }
3009     } else {
3010       B << 1;
3011       const char *PrevSpec;
3012       unsigned DiagID;
3013       if (D.getMutableDeclSpec().SetStorageClassSpec(
3014           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3015           Context.getPrintingPolicy())) {
3016         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3017                "This is the only DeclSpec that should fail to be applied");
3018         B << 1;
3019       } else {
3020         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3021         isInstField = false;
3022       }
3023     }
3024   }
3025 
3026   NamedDecl *Member;
3027   if (isInstField) {
3028     CXXScopeSpec &SS = D.getCXXScopeSpec();
3029 
3030     // Data members must have identifiers for names.
3031     if (!Name.isIdentifier()) {
3032       Diag(Loc, diag::err_bad_variable_name)
3033         << Name;
3034       return nullptr;
3035     }
3036 
3037     IdentifierInfo *II = Name.getAsIdentifierInfo();
3038 
3039     // Member field could not be with "template" keyword.
3040     // So TemplateParameterLists should be empty in this case.
3041     if (TemplateParameterLists.size()) {
3042       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3043       if (TemplateParams->size()) {
3044         // There is no such thing as a member field template.
3045         Diag(D.getIdentifierLoc(), diag::err_template_member)
3046             << II
3047             << SourceRange(TemplateParams->getTemplateLoc(),
3048                 TemplateParams->getRAngleLoc());
3049       } else {
3050         // There is an extraneous 'template<>' for this member.
3051         Diag(TemplateParams->getTemplateLoc(),
3052             diag::err_template_member_noparams)
3053             << II
3054             << SourceRange(TemplateParams->getTemplateLoc(),
3055                 TemplateParams->getRAngleLoc());
3056       }
3057       return nullptr;
3058     }
3059 
3060     if (SS.isSet() && !SS.isInvalid()) {
3061       // The user provided a superfluous scope specifier inside a class
3062       // definition:
3063       //
3064       // class X {
3065       //   int X::member;
3066       // };
3067       if (DeclContext *DC = computeDeclContext(SS, false))
3068         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3069                                      D.getName().getKind() ==
3070                                          UnqualifiedIdKind::IK_TemplateId);
3071       else
3072         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3073           << Name << SS.getRange();
3074 
3075       SS.clear();
3076     }
3077 
3078     if (MSPropertyAttr) {
3079       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3080                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3081       if (!Member)
3082         return nullptr;
3083       isInstField = false;
3084     } else {
3085       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3086                                 BitWidth, InitStyle, AS);
3087       if (!Member)
3088         return nullptr;
3089     }
3090 
3091     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3092   } else {
3093     Member = HandleDeclarator(S, D, TemplateParameterLists);
3094     if (!Member)
3095       return nullptr;
3096 
3097     // Non-instance-fields can't have a bitfield.
3098     if (BitWidth) {
3099       if (Member->isInvalidDecl()) {
3100         // don't emit another diagnostic.
3101       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3102         // C++ 9.6p3: A bit-field shall not be a static member.
3103         // "static member 'A' cannot be a bit-field"
3104         Diag(Loc, diag::err_static_not_bitfield)
3105           << Name << BitWidth->getSourceRange();
3106       } else if (isa<TypedefDecl>(Member)) {
3107         // "typedef member 'x' cannot be a bit-field"
3108         Diag(Loc, diag::err_typedef_not_bitfield)
3109           << Name << BitWidth->getSourceRange();
3110       } else {
3111         // A function typedef ("typedef int f(); f a;").
3112         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3113         Diag(Loc, diag::err_not_integral_type_bitfield)
3114           << Name << cast<ValueDecl>(Member)->getType()
3115           << BitWidth->getSourceRange();
3116       }
3117 
3118       BitWidth = nullptr;
3119       Member->setInvalidDecl();
3120     }
3121 
3122     NamedDecl *NonTemplateMember = Member;
3123     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3124       NonTemplateMember = FunTmpl->getTemplatedDecl();
3125     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3126       NonTemplateMember = VarTmpl->getTemplatedDecl();
3127 
3128     Member->setAccess(AS);
3129 
3130     // If we have declared a member function template or static data member
3131     // template, set the access of the templated declaration as well.
3132     if (NonTemplateMember != Member)
3133       NonTemplateMember->setAccess(AS);
3134 
3135     // C++ [temp.deduct.guide]p3:
3136     //   A deduction guide [...] for a member class template [shall be
3137     //   declared] with the same access [as the template].
3138     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3139       auto *TD = DG->getDeducedTemplate();
3140       if (AS != TD->getAccess()) {
3141         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3142         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3143             << TD->getAccess();
3144         const AccessSpecDecl *LastAccessSpec = nullptr;
3145         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3146           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3147             LastAccessSpec = AccessSpec;
3148         }
3149         assert(LastAccessSpec && "differing access with no access specifier");
3150         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3151             << AS;
3152       }
3153     }
3154   }
3155 
3156   if (VS.isOverrideSpecified())
3157     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3158   if (VS.isFinalSpecified())
3159     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3160                                             VS.isFinalSpelledSealed()));
3161 
3162   if (VS.getLastLocation().isValid()) {
3163     // Update the end location of a method that has a virt-specifiers.
3164     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3165       MD->setRangeEnd(VS.getLastLocation());
3166   }
3167 
3168   CheckOverrideControl(Member);
3169 
3170   assert((Name || isInstField) && "No identifier for non-field ?");
3171 
3172   if (isInstField) {
3173     FieldDecl *FD = cast<FieldDecl>(Member);
3174     FieldCollector->Add(FD);
3175 
3176     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3177       // Remember all explicit private FieldDecls that have a name, no side
3178       // effects and are not part of a dependent type declaration.
3179       if (!FD->isImplicit() && FD->getDeclName() &&
3180           FD->getAccess() == AS_private &&
3181           !FD->hasAttr<UnusedAttr>() &&
3182           !FD->getParent()->isDependentContext() &&
3183           !InitializationHasSideEffects(*FD))
3184         UnusedPrivateFields.insert(FD);
3185     }
3186   }
3187 
3188   return Member;
3189 }
3190 
3191 namespace {
3192   class UninitializedFieldVisitor
3193       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3194     Sema &S;
3195     // List of Decls to generate a warning on.  Also remove Decls that become
3196     // initialized.
3197     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3198     // List of base classes of the record.  Classes are removed after their
3199     // initializers.
3200     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3201     // Vector of decls to be removed from the Decl set prior to visiting the
3202     // nodes.  These Decls may have been initialized in the prior initializer.
3203     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3204     // If non-null, add a note to the warning pointing back to the constructor.
3205     const CXXConstructorDecl *Constructor;
3206     // Variables to hold state when processing an initializer list.  When
3207     // InitList is true, special case initialization of FieldDecls matching
3208     // InitListFieldDecl.
3209     bool InitList;
3210     FieldDecl *InitListFieldDecl;
3211     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3212 
3213   public:
3214     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3215     UninitializedFieldVisitor(Sema &S,
3216                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3217                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3218       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3219         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3220 
3221     // Returns true if the use of ME is not an uninitialized use.
3222     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3223                                          bool CheckReferenceOnly) {
3224       llvm::SmallVector<FieldDecl*, 4> Fields;
3225       bool ReferenceField = false;
3226       while (ME) {
3227         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3228         if (!FD)
3229           return false;
3230         Fields.push_back(FD);
3231         if (FD->getType()->isReferenceType())
3232           ReferenceField = true;
3233         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3234       }
3235 
3236       // Binding a reference to an unintialized field is not an
3237       // uninitialized use.
3238       if (CheckReferenceOnly && !ReferenceField)
3239         return true;
3240 
3241       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3242       // Discard the first field since it is the field decl that is being
3243       // initialized.
3244       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3245         UsedFieldIndex.push_back((*I)->getFieldIndex());
3246       }
3247 
3248       for (auto UsedIter = UsedFieldIndex.begin(),
3249                 UsedEnd = UsedFieldIndex.end(),
3250                 OrigIter = InitFieldIndex.begin(),
3251                 OrigEnd = InitFieldIndex.end();
3252            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3253         if (*UsedIter < *OrigIter)
3254           return true;
3255         if (*UsedIter > *OrigIter)
3256           break;
3257       }
3258 
3259       return false;
3260     }
3261 
3262     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3263                           bool AddressOf) {
3264       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3265         return;
3266 
3267       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3268       // or union.
3269       MemberExpr *FieldME = ME;
3270 
3271       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3272 
3273       Expr *Base = ME;
3274       while (MemberExpr *SubME =
3275                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3276 
3277         if (isa<VarDecl>(SubME->getMemberDecl()))
3278           return;
3279 
3280         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3281           if (!FD->isAnonymousStructOrUnion())
3282             FieldME = SubME;
3283 
3284         if (!FieldME->getType().isPODType(S.Context))
3285           AllPODFields = false;
3286 
3287         Base = SubME->getBase();
3288       }
3289 
3290       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3291         return;
3292 
3293       if (AddressOf && AllPODFields)
3294         return;
3295 
3296       ValueDecl* FoundVD = FieldME->getMemberDecl();
3297 
3298       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3299         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3300           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3301         }
3302 
3303         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3304           QualType T = BaseCast->getType();
3305           if (T->isPointerType() &&
3306               BaseClasses.count(T->getPointeeType())) {
3307             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3308                 << T->getPointeeType() << FoundVD;
3309           }
3310         }
3311       }
3312 
3313       if (!Decls.count(FoundVD))
3314         return;
3315 
3316       const bool IsReference = FoundVD->getType()->isReferenceType();
3317 
3318       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3319         // Special checking for initializer lists.
3320         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3321           return;
3322         }
3323       } else {
3324         // Prevent double warnings on use of unbounded references.
3325         if (CheckReferenceOnly && !IsReference)
3326           return;
3327       }
3328 
3329       unsigned diag = IsReference
3330           ? diag::warn_reference_field_is_uninit
3331           : diag::warn_field_is_uninit;
3332       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3333       if (Constructor)
3334         S.Diag(Constructor->getLocation(),
3335                diag::note_uninit_in_this_constructor)
3336           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3337 
3338     }
3339 
3340     void HandleValue(Expr *E, bool AddressOf) {
3341       E = E->IgnoreParens();
3342 
3343       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3344         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3345                          AddressOf /*AddressOf*/);
3346         return;
3347       }
3348 
3349       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3350         Visit(CO->getCond());
3351         HandleValue(CO->getTrueExpr(), AddressOf);
3352         HandleValue(CO->getFalseExpr(), AddressOf);
3353         return;
3354       }
3355 
3356       if (BinaryConditionalOperator *BCO =
3357               dyn_cast<BinaryConditionalOperator>(E)) {
3358         Visit(BCO->getCond());
3359         HandleValue(BCO->getFalseExpr(), AddressOf);
3360         return;
3361       }
3362 
3363       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3364         HandleValue(OVE->getSourceExpr(), AddressOf);
3365         return;
3366       }
3367 
3368       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3369         switch (BO->getOpcode()) {
3370         default:
3371           break;
3372         case(BO_PtrMemD):
3373         case(BO_PtrMemI):
3374           HandleValue(BO->getLHS(), AddressOf);
3375           Visit(BO->getRHS());
3376           return;
3377         case(BO_Comma):
3378           Visit(BO->getLHS());
3379           HandleValue(BO->getRHS(), AddressOf);
3380           return;
3381         }
3382       }
3383 
3384       Visit(E);
3385     }
3386 
3387     void CheckInitListExpr(InitListExpr *ILE) {
3388       InitFieldIndex.push_back(0);
3389       for (auto Child : ILE->children()) {
3390         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3391           CheckInitListExpr(SubList);
3392         } else {
3393           Visit(Child);
3394         }
3395         ++InitFieldIndex.back();
3396       }
3397       InitFieldIndex.pop_back();
3398     }
3399 
3400     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3401                           FieldDecl *Field, const Type *BaseClass) {
3402       // Remove Decls that may have been initialized in the previous
3403       // initializer.
3404       for (ValueDecl* VD : DeclsToRemove)
3405         Decls.erase(VD);
3406       DeclsToRemove.clear();
3407 
3408       Constructor = FieldConstructor;
3409       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3410 
3411       if (ILE && Field) {
3412         InitList = true;
3413         InitListFieldDecl = Field;
3414         InitFieldIndex.clear();
3415         CheckInitListExpr(ILE);
3416       } else {
3417         InitList = false;
3418         Visit(E);
3419       }
3420 
3421       if (Field)
3422         Decls.erase(Field);
3423       if (BaseClass)
3424         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3425     }
3426 
3427     void VisitMemberExpr(MemberExpr *ME) {
3428       // All uses of unbounded reference fields will warn.
3429       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3430     }
3431 
3432     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3433       if (E->getCastKind() == CK_LValueToRValue) {
3434         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3435         return;
3436       }
3437 
3438       Inherited::VisitImplicitCastExpr(E);
3439     }
3440 
3441     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3442       if (E->getConstructor()->isCopyConstructor()) {
3443         Expr *ArgExpr = E->getArg(0);
3444         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3445           if (ILE->getNumInits() == 1)
3446             ArgExpr = ILE->getInit(0);
3447         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3448           if (ICE->getCastKind() == CK_NoOp)
3449             ArgExpr = ICE->getSubExpr();
3450         HandleValue(ArgExpr, false /*AddressOf*/);
3451         return;
3452       }
3453       Inherited::VisitCXXConstructExpr(E);
3454     }
3455 
3456     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3457       Expr *Callee = E->getCallee();
3458       if (isa<MemberExpr>(Callee)) {
3459         HandleValue(Callee, false /*AddressOf*/);
3460         for (auto Arg : E->arguments())
3461           Visit(Arg);
3462         return;
3463       }
3464 
3465       Inherited::VisitCXXMemberCallExpr(E);
3466     }
3467 
3468     void VisitCallExpr(CallExpr *E) {
3469       // Treat std::move as a use.
3470       if (E->isCallToStdMove()) {
3471         HandleValue(E->getArg(0), /*AddressOf=*/false);
3472         return;
3473       }
3474 
3475       Inherited::VisitCallExpr(E);
3476     }
3477 
3478     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3479       Expr *Callee = E->getCallee();
3480 
3481       if (isa<UnresolvedLookupExpr>(Callee))
3482         return Inherited::VisitCXXOperatorCallExpr(E);
3483 
3484       Visit(Callee);
3485       for (auto Arg : E->arguments())
3486         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3487     }
3488 
3489     void VisitBinaryOperator(BinaryOperator *E) {
3490       // If a field assignment is detected, remove the field from the
3491       // uninitiailized field set.
3492       if (E->getOpcode() == BO_Assign)
3493         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3494           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3495             if (!FD->getType()->isReferenceType())
3496               DeclsToRemove.push_back(FD);
3497 
3498       if (E->isCompoundAssignmentOp()) {
3499         HandleValue(E->getLHS(), false /*AddressOf*/);
3500         Visit(E->getRHS());
3501         return;
3502       }
3503 
3504       Inherited::VisitBinaryOperator(E);
3505     }
3506 
3507     void VisitUnaryOperator(UnaryOperator *E) {
3508       if (E->isIncrementDecrementOp()) {
3509         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3510         return;
3511       }
3512       if (E->getOpcode() == UO_AddrOf) {
3513         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3514           HandleValue(ME->getBase(), true /*AddressOf*/);
3515           return;
3516         }
3517       }
3518 
3519       Inherited::VisitUnaryOperator(E);
3520     }
3521   };
3522 
3523   // Diagnose value-uses of fields to initialize themselves, e.g.
3524   //   foo(foo)
3525   // where foo is not also a parameter to the constructor.
3526   // Also diagnose across field uninitialized use such as
3527   //   x(y), y(x)
3528   // TODO: implement -Wuninitialized and fold this into that framework.
3529   static void DiagnoseUninitializedFields(
3530       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3531 
3532     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3533                                            Constructor->getLocation())) {
3534       return;
3535     }
3536 
3537     if (Constructor->isInvalidDecl())
3538       return;
3539 
3540     const CXXRecordDecl *RD = Constructor->getParent();
3541 
3542     if (RD->getDescribedClassTemplate())
3543       return;
3544 
3545     // Holds fields that are uninitialized.
3546     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3547 
3548     // At the beginning, all fields are uninitialized.
3549     for (auto *I : RD->decls()) {
3550       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3551         UninitializedFields.insert(FD);
3552       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3553         UninitializedFields.insert(IFD->getAnonField());
3554       }
3555     }
3556 
3557     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3558     for (auto I : RD->bases())
3559       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3560 
3561     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3562       return;
3563 
3564     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3565                                                    UninitializedFields,
3566                                                    UninitializedBaseClasses);
3567 
3568     for (const auto *FieldInit : Constructor->inits()) {
3569       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3570         break;
3571 
3572       Expr *InitExpr = FieldInit->getInit();
3573       if (!InitExpr)
3574         continue;
3575 
3576       if (CXXDefaultInitExpr *Default =
3577               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3578         InitExpr = Default->getExpr();
3579         if (!InitExpr)
3580           continue;
3581         // In class initializers will point to the constructor.
3582         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3583                                               FieldInit->getAnyMember(),
3584                                               FieldInit->getBaseClass());
3585       } else {
3586         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3587                                               FieldInit->getAnyMember(),
3588                                               FieldInit->getBaseClass());
3589       }
3590     }
3591   }
3592 } // namespace
3593 
3594 /// Enter a new C++ default initializer scope. After calling this, the
3595 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3596 /// parsing or instantiating the initializer failed.
3597 void Sema::ActOnStartCXXInClassMemberInitializer() {
3598   // Create a synthetic function scope to represent the call to the constructor
3599   // that notionally surrounds a use of this initializer.
3600   PushFunctionScope();
3601 }
3602 
3603 /// This is invoked after parsing an in-class initializer for a
3604 /// non-static C++ class member, and after instantiating an in-class initializer
3605 /// in a class template. Such actions are deferred until the class is complete.
3606 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3607                                                   SourceLocation InitLoc,
3608                                                   Expr *InitExpr) {
3609   // Pop the notional constructor scope we created earlier.
3610   PopFunctionScopeInfo(nullptr, D);
3611 
3612   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3613   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3614          "must set init style when field is created");
3615 
3616   if (!InitExpr) {
3617     D->setInvalidDecl();
3618     if (FD)
3619       FD->removeInClassInitializer();
3620     return;
3621   }
3622 
3623   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3624     FD->setInvalidDecl();
3625     FD->removeInClassInitializer();
3626     return;
3627   }
3628 
3629   ExprResult Init = InitExpr;
3630   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3631     InitializedEntity Entity =
3632         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3633     InitializationKind Kind =
3634         FD->getInClassInitStyle() == ICIS_ListInit
3635             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3636                                                    InitExpr->getBeginLoc(),
3637                                                    InitExpr->getEndLoc())
3638             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3639     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3640     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3641     if (Init.isInvalid()) {
3642       FD->setInvalidDecl();
3643       return;
3644     }
3645   }
3646 
3647   // C++11 [class.base.init]p7:
3648   //   The initialization of each base and member constitutes a
3649   //   full-expression.
3650   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3651   if (Init.isInvalid()) {
3652     FD->setInvalidDecl();
3653     return;
3654   }
3655 
3656   InitExpr = Init.get();
3657 
3658   FD->setInClassInitializer(InitExpr);
3659 }
3660 
3661 /// Find the direct and/or virtual base specifiers that
3662 /// correspond to the given base type, for use in base initialization
3663 /// within a constructor.
3664 static bool FindBaseInitializer(Sema &SemaRef,
3665                                 CXXRecordDecl *ClassDecl,
3666                                 QualType BaseType,
3667                                 const CXXBaseSpecifier *&DirectBaseSpec,
3668                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3669   // First, check for a direct base class.
3670   DirectBaseSpec = nullptr;
3671   for (const auto &Base : ClassDecl->bases()) {
3672     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3673       // We found a direct base of this type. That's what we're
3674       // initializing.
3675       DirectBaseSpec = &Base;
3676       break;
3677     }
3678   }
3679 
3680   // Check for a virtual base class.
3681   // FIXME: We might be able to short-circuit this if we know in advance that
3682   // there are no virtual bases.
3683   VirtualBaseSpec = nullptr;
3684   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3685     // We haven't found a base yet; search the class hierarchy for a
3686     // virtual base class.
3687     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3688                        /*DetectVirtual=*/false);
3689     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3690                               SemaRef.Context.getTypeDeclType(ClassDecl),
3691                               BaseType, Paths)) {
3692       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3693            Path != Paths.end(); ++Path) {
3694         if (Path->back().Base->isVirtual()) {
3695           VirtualBaseSpec = Path->back().Base;
3696           break;
3697         }
3698       }
3699     }
3700   }
3701 
3702   return DirectBaseSpec || VirtualBaseSpec;
3703 }
3704 
3705 /// Handle a C++ member initializer using braced-init-list syntax.
3706 MemInitResult
3707 Sema::ActOnMemInitializer(Decl *ConstructorD,
3708                           Scope *S,
3709                           CXXScopeSpec &SS,
3710                           IdentifierInfo *MemberOrBase,
3711                           ParsedType TemplateTypeTy,
3712                           const DeclSpec &DS,
3713                           SourceLocation IdLoc,
3714                           Expr *InitList,
3715                           SourceLocation EllipsisLoc) {
3716   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3717                              DS, IdLoc, InitList,
3718                              EllipsisLoc);
3719 }
3720 
3721 /// Handle a C++ member initializer using parentheses syntax.
3722 MemInitResult
3723 Sema::ActOnMemInitializer(Decl *ConstructorD,
3724                           Scope *S,
3725                           CXXScopeSpec &SS,
3726                           IdentifierInfo *MemberOrBase,
3727                           ParsedType TemplateTypeTy,
3728                           const DeclSpec &DS,
3729                           SourceLocation IdLoc,
3730                           SourceLocation LParenLoc,
3731                           ArrayRef<Expr *> Args,
3732                           SourceLocation RParenLoc,
3733                           SourceLocation EllipsisLoc) {
3734   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3735   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3736                              DS, IdLoc, List, EllipsisLoc);
3737 }
3738 
3739 namespace {
3740 
3741 // Callback to only accept typo corrections that can be a valid C++ member
3742 // intializer: either a non-static field member or a base class.
3743 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3744 public:
3745   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3746       : ClassDecl(ClassDecl) {}
3747 
3748   bool ValidateCandidate(const TypoCorrection &candidate) override {
3749     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3750       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3751         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3752       return isa<TypeDecl>(ND);
3753     }
3754     return false;
3755   }
3756 
3757 private:
3758   CXXRecordDecl *ClassDecl;
3759 };
3760 
3761 }
3762 
3763 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3764                                              CXXScopeSpec &SS,
3765                                              ParsedType TemplateTypeTy,
3766                                              IdentifierInfo *MemberOrBase) {
3767   if (SS.getScopeRep() || TemplateTypeTy)
3768     return nullptr;
3769   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3770   if (Result.empty())
3771     return nullptr;
3772   ValueDecl *Member;
3773   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3774       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3775     return Member;
3776   return nullptr;
3777 }
3778 
3779 /// Handle a C++ member initializer.
3780 MemInitResult
3781 Sema::BuildMemInitializer(Decl *ConstructorD,
3782                           Scope *S,
3783                           CXXScopeSpec &SS,
3784                           IdentifierInfo *MemberOrBase,
3785                           ParsedType TemplateTypeTy,
3786                           const DeclSpec &DS,
3787                           SourceLocation IdLoc,
3788                           Expr *Init,
3789                           SourceLocation EllipsisLoc) {
3790   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3791   if (!Res.isUsable())
3792     return true;
3793   Init = Res.get();
3794 
3795   if (!ConstructorD)
3796     return true;
3797 
3798   AdjustDeclIfTemplate(ConstructorD);
3799 
3800   CXXConstructorDecl *Constructor
3801     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3802   if (!Constructor) {
3803     // The user wrote a constructor initializer on a function that is
3804     // not a C++ constructor. Ignore the error for now, because we may
3805     // have more member initializers coming; we'll diagnose it just
3806     // once in ActOnMemInitializers.
3807     return true;
3808   }
3809 
3810   CXXRecordDecl *ClassDecl = Constructor->getParent();
3811 
3812   // C++ [class.base.init]p2:
3813   //   Names in a mem-initializer-id are looked up in the scope of the
3814   //   constructor's class and, if not found in that scope, are looked
3815   //   up in the scope containing the constructor's definition.
3816   //   [Note: if the constructor's class contains a member with the
3817   //   same name as a direct or virtual base class of the class, a
3818   //   mem-initializer-id naming the member or base class and composed
3819   //   of a single identifier refers to the class member. A
3820   //   mem-initializer-id for the hidden base class may be specified
3821   //   using a qualified name. ]
3822 
3823   // Look for a member, first.
3824   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3825           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3826     if (EllipsisLoc.isValid())
3827       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3828           << MemberOrBase
3829           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3830 
3831     return BuildMemberInitializer(Member, Init, IdLoc);
3832   }
3833   // It didn't name a member, so see if it names a class.
3834   QualType BaseType;
3835   TypeSourceInfo *TInfo = nullptr;
3836 
3837   if (TemplateTypeTy) {
3838     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3839   } else if (DS.getTypeSpecType() == TST_decltype) {
3840     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3841   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3842     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3843     return true;
3844   } else {
3845     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3846     LookupParsedName(R, S, &SS);
3847 
3848     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3849     if (!TyD) {
3850       if (R.isAmbiguous()) return true;
3851 
3852       // We don't want access-control diagnostics here.
3853       R.suppressDiagnostics();
3854 
3855       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3856         bool NotUnknownSpecialization = false;
3857         DeclContext *DC = computeDeclContext(SS, false);
3858         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3859           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3860 
3861         if (!NotUnknownSpecialization) {
3862           // When the scope specifier can refer to a member of an unknown
3863           // specialization, we take it as a type name.
3864           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3865                                        SS.getWithLocInContext(Context),
3866                                        *MemberOrBase, IdLoc);
3867           if (BaseType.isNull())
3868             return true;
3869 
3870           TInfo = Context.CreateTypeSourceInfo(BaseType);
3871           DependentNameTypeLoc TL =
3872               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3873           if (!TL.isNull()) {
3874             TL.setNameLoc(IdLoc);
3875             TL.setElaboratedKeywordLoc(SourceLocation());
3876             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3877           }
3878 
3879           R.clear();
3880           R.setLookupName(MemberOrBase);
3881         }
3882       }
3883 
3884       // If no results were found, try to correct typos.
3885       TypoCorrection Corr;
3886       if (R.empty() && BaseType.isNull() &&
3887           (Corr = CorrectTypo(
3888                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3889                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3890                CTK_ErrorRecovery, ClassDecl))) {
3891         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3892           // We have found a non-static data member with a similar
3893           // name to what was typed; complain and initialize that
3894           // member.
3895           diagnoseTypo(Corr,
3896                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3897                          << MemberOrBase << true);
3898           return BuildMemberInitializer(Member, Init, IdLoc);
3899         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3900           const CXXBaseSpecifier *DirectBaseSpec;
3901           const CXXBaseSpecifier *VirtualBaseSpec;
3902           if (FindBaseInitializer(*this, ClassDecl,
3903                                   Context.getTypeDeclType(Type),
3904                                   DirectBaseSpec, VirtualBaseSpec)) {
3905             // We have found a direct or virtual base class with a
3906             // similar name to what was typed; complain and initialize
3907             // that base class.
3908             diagnoseTypo(Corr,
3909                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3910                            << MemberOrBase << false,
3911                          PDiag() /*Suppress note, we provide our own.*/);
3912 
3913             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3914                                                               : VirtualBaseSpec;
3915             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3916                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3917 
3918             TyD = Type;
3919           }
3920         }
3921       }
3922 
3923       if (!TyD && BaseType.isNull()) {
3924         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3925           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3926         return true;
3927       }
3928     }
3929 
3930     if (BaseType.isNull()) {
3931       BaseType = Context.getTypeDeclType(TyD);
3932       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3933       if (SS.isSet()) {
3934         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3935                                              BaseType);
3936         TInfo = Context.CreateTypeSourceInfo(BaseType);
3937         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3938         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3939         TL.setElaboratedKeywordLoc(SourceLocation());
3940         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3941       }
3942     }
3943   }
3944 
3945   if (!TInfo)
3946     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3947 
3948   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3949 }
3950 
3951 MemInitResult
3952 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3953                              SourceLocation IdLoc) {
3954   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3955   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3956   assert((DirectMember || IndirectMember) &&
3957          "Member must be a FieldDecl or IndirectFieldDecl");
3958 
3959   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3960     return true;
3961 
3962   if (Member->isInvalidDecl())
3963     return true;
3964 
3965   MultiExprArg Args;
3966   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3967     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3968   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3969     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3970   } else {
3971     // Template instantiation doesn't reconstruct ParenListExprs for us.
3972     Args = Init;
3973   }
3974 
3975   SourceRange InitRange = Init->getSourceRange();
3976 
3977   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3978     // Can't check initialization for a member of dependent type or when
3979     // any of the arguments are type-dependent expressions.
3980     DiscardCleanupsInEvaluationContext();
3981   } else {
3982     bool InitList = false;
3983     if (isa<InitListExpr>(Init)) {
3984       InitList = true;
3985       Args = Init;
3986     }
3987 
3988     // Initialize the member.
3989     InitializedEntity MemberEntity =
3990       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3991                    : InitializedEntity::InitializeMember(IndirectMember,
3992                                                          nullptr);
3993     InitializationKind Kind =
3994         InitList ? InitializationKind::CreateDirectList(
3995                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
3996                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3997                                                     InitRange.getEnd());
3998 
3999     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4000     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4001                                             nullptr);
4002     if (MemberInit.isInvalid())
4003       return true;
4004 
4005     // C++11 [class.base.init]p7:
4006     //   The initialization of each base and member constitutes a
4007     //   full-expression.
4008     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4009     if (MemberInit.isInvalid())
4010       return true;
4011 
4012     Init = MemberInit.get();
4013   }
4014 
4015   if (DirectMember) {
4016     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4017                                             InitRange.getBegin(), Init,
4018                                             InitRange.getEnd());
4019   } else {
4020     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4021                                             InitRange.getBegin(), Init,
4022                                             InitRange.getEnd());
4023   }
4024 }
4025 
4026 MemInitResult
4027 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4028                                  CXXRecordDecl *ClassDecl) {
4029   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4030   if (!LangOpts.CPlusPlus11)
4031     return Diag(NameLoc, diag::err_delegating_ctor)
4032       << TInfo->getTypeLoc().getLocalSourceRange();
4033   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4034 
4035   bool InitList = true;
4036   MultiExprArg Args = Init;
4037   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4038     InitList = false;
4039     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4040   }
4041 
4042   SourceRange InitRange = Init->getSourceRange();
4043   // Initialize the object.
4044   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4045                                      QualType(ClassDecl->getTypeForDecl(), 0));
4046   InitializationKind Kind =
4047       InitList ? InitializationKind::CreateDirectList(
4048                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4049                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4050                                                   InitRange.getEnd());
4051   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4052   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4053                                               Args, nullptr);
4054   if (DelegationInit.isInvalid())
4055     return true;
4056 
4057   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4058          "Delegating constructor with no target?");
4059 
4060   // C++11 [class.base.init]p7:
4061   //   The initialization of each base and member constitutes a
4062   //   full-expression.
4063   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4064                                        InitRange.getBegin());
4065   if (DelegationInit.isInvalid())
4066     return true;
4067 
4068   // If we are in a dependent context, template instantiation will
4069   // perform this type-checking again. Just save the arguments that we
4070   // received in a ParenListExpr.
4071   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4072   // of the information that we have about the base
4073   // initializer. However, deconstructing the ASTs is a dicey process,
4074   // and this approach is far more likely to get the corner cases right.
4075   if (CurContext->isDependentContext())
4076     DelegationInit = Init;
4077 
4078   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4079                                           DelegationInit.getAs<Expr>(),
4080                                           InitRange.getEnd());
4081 }
4082 
4083 MemInitResult
4084 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4085                            Expr *Init, CXXRecordDecl *ClassDecl,
4086                            SourceLocation EllipsisLoc) {
4087   SourceLocation BaseLoc
4088     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4089 
4090   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4091     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4092              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4093 
4094   // C++ [class.base.init]p2:
4095   //   [...] Unless the mem-initializer-id names a nonstatic data
4096   //   member of the constructor's class or a direct or virtual base
4097   //   of that class, the mem-initializer is ill-formed. A
4098   //   mem-initializer-list can initialize a base class using any
4099   //   name that denotes that base class type.
4100   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4101 
4102   SourceRange InitRange = Init->getSourceRange();
4103   if (EllipsisLoc.isValid()) {
4104     // This is a pack expansion.
4105     if (!BaseType->containsUnexpandedParameterPack())  {
4106       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4107         << SourceRange(BaseLoc, InitRange.getEnd());
4108 
4109       EllipsisLoc = SourceLocation();
4110     }
4111   } else {
4112     // Check for any unexpanded parameter packs.
4113     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4114       return true;
4115 
4116     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4117       return true;
4118   }
4119 
4120   // Check for direct and virtual base classes.
4121   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4122   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4123   if (!Dependent) {
4124     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4125                                        BaseType))
4126       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4127 
4128     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4129                         VirtualBaseSpec);
4130 
4131     // C++ [base.class.init]p2:
4132     // Unless the mem-initializer-id names a nonstatic data member of the
4133     // constructor's class or a direct or virtual base of that class, the
4134     // mem-initializer is ill-formed.
4135     if (!DirectBaseSpec && !VirtualBaseSpec) {
4136       // If the class has any dependent bases, then it's possible that
4137       // one of those types will resolve to the same type as
4138       // BaseType. Therefore, just treat this as a dependent base
4139       // class initialization.  FIXME: Should we try to check the
4140       // initialization anyway? It seems odd.
4141       if (ClassDecl->hasAnyDependentBases())
4142         Dependent = true;
4143       else
4144         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4145           << BaseType << Context.getTypeDeclType(ClassDecl)
4146           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4147     }
4148   }
4149 
4150   if (Dependent) {
4151     DiscardCleanupsInEvaluationContext();
4152 
4153     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4154                                             /*IsVirtual=*/false,
4155                                             InitRange.getBegin(), Init,
4156                                             InitRange.getEnd(), EllipsisLoc);
4157   }
4158 
4159   // C++ [base.class.init]p2:
4160   //   If a mem-initializer-id is ambiguous because it designates both
4161   //   a direct non-virtual base class and an inherited virtual base
4162   //   class, the mem-initializer is ill-formed.
4163   if (DirectBaseSpec && VirtualBaseSpec)
4164     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4165       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4166 
4167   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4168   if (!BaseSpec)
4169     BaseSpec = VirtualBaseSpec;
4170 
4171   // Initialize the base.
4172   bool InitList = true;
4173   MultiExprArg Args = Init;
4174   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4175     InitList = false;
4176     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4177   }
4178 
4179   InitializedEntity BaseEntity =
4180     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4181   InitializationKind Kind =
4182       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4183                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4184                                                   InitRange.getEnd());
4185   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4186   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4187   if (BaseInit.isInvalid())
4188     return true;
4189 
4190   // C++11 [class.base.init]p7:
4191   //   The initialization of each base and member constitutes a
4192   //   full-expression.
4193   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4194   if (BaseInit.isInvalid())
4195     return true;
4196 
4197   // If we are in a dependent context, template instantiation will
4198   // perform this type-checking again. Just save the arguments that we
4199   // received in a ParenListExpr.
4200   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4201   // of the information that we have about the base
4202   // initializer. However, deconstructing the ASTs is a dicey process,
4203   // and this approach is far more likely to get the corner cases right.
4204   if (CurContext->isDependentContext())
4205     BaseInit = Init;
4206 
4207   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4208                                           BaseSpec->isVirtual(),
4209                                           InitRange.getBegin(),
4210                                           BaseInit.getAs<Expr>(),
4211                                           InitRange.getEnd(), EllipsisLoc);
4212 }
4213 
4214 // Create a static_cast\<T&&>(expr).
4215 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4216   if (T.isNull()) T = E->getType();
4217   QualType TargetType = SemaRef.BuildReferenceType(
4218       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4219   SourceLocation ExprLoc = E->getBeginLoc();
4220   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4221       TargetType, ExprLoc);
4222 
4223   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4224                                    SourceRange(ExprLoc, ExprLoc),
4225                                    E->getSourceRange()).get();
4226 }
4227 
4228 /// ImplicitInitializerKind - How an implicit base or member initializer should
4229 /// initialize its base or member.
4230 enum ImplicitInitializerKind {
4231   IIK_Default,
4232   IIK_Copy,
4233   IIK_Move,
4234   IIK_Inherit
4235 };
4236 
4237 static bool
4238 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4239                              ImplicitInitializerKind ImplicitInitKind,
4240                              CXXBaseSpecifier *BaseSpec,
4241                              bool IsInheritedVirtualBase,
4242                              CXXCtorInitializer *&CXXBaseInit) {
4243   InitializedEntity InitEntity
4244     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4245                                         IsInheritedVirtualBase);
4246 
4247   ExprResult BaseInit;
4248 
4249   switch (ImplicitInitKind) {
4250   case IIK_Inherit:
4251   case IIK_Default: {
4252     InitializationKind InitKind
4253       = InitializationKind::CreateDefault(Constructor->getLocation());
4254     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4255     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4256     break;
4257   }
4258 
4259   case IIK_Move:
4260   case IIK_Copy: {
4261     bool Moving = ImplicitInitKind == IIK_Move;
4262     ParmVarDecl *Param = Constructor->getParamDecl(0);
4263     QualType ParamType = Param->getType().getNonReferenceType();
4264 
4265     Expr *CopyCtorArg =
4266       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4267                           SourceLocation(), Param, false,
4268                           Constructor->getLocation(), ParamType,
4269                           VK_LValue, nullptr);
4270 
4271     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4272 
4273     // Cast to the base class to avoid ambiguities.
4274     QualType ArgTy =
4275       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4276                                        ParamType.getQualifiers());
4277 
4278     if (Moving) {
4279       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4280     }
4281 
4282     CXXCastPath BasePath;
4283     BasePath.push_back(BaseSpec);
4284     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4285                                             CK_UncheckedDerivedToBase,
4286                                             Moving ? VK_XValue : VK_LValue,
4287                                             &BasePath).get();
4288 
4289     InitializationKind InitKind
4290       = InitializationKind::CreateDirect(Constructor->getLocation(),
4291                                          SourceLocation(), SourceLocation());
4292     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4293     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4294     break;
4295   }
4296   }
4297 
4298   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4299   if (BaseInit.isInvalid())
4300     return true;
4301 
4302   CXXBaseInit =
4303     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4304                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4305                                                         SourceLocation()),
4306                                              BaseSpec->isVirtual(),
4307                                              SourceLocation(),
4308                                              BaseInit.getAs<Expr>(),
4309                                              SourceLocation(),
4310                                              SourceLocation());
4311 
4312   return false;
4313 }
4314 
4315 static bool RefersToRValueRef(Expr *MemRef) {
4316   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4317   return Referenced->getType()->isRValueReferenceType();
4318 }
4319 
4320 static bool
4321 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4322                                ImplicitInitializerKind ImplicitInitKind,
4323                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4324                                CXXCtorInitializer *&CXXMemberInit) {
4325   if (Field->isInvalidDecl())
4326     return true;
4327 
4328   SourceLocation Loc = Constructor->getLocation();
4329 
4330   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4331     bool Moving = ImplicitInitKind == IIK_Move;
4332     ParmVarDecl *Param = Constructor->getParamDecl(0);
4333     QualType ParamType = Param->getType().getNonReferenceType();
4334 
4335     // Suppress copying zero-width bitfields.
4336     if (Field->isZeroLengthBitField(SemaRef.Context))
4337       return false;
4338 
4339     Expr *MemberExprBase =
4340       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4341                           SourceLocation(), Param, false,
4342                           Loc, ParamType, VK_LValue, nullptr);
4343 
4344     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4345 
4346     if (Moving) {
4347       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4348     }
4349 
4350     // Build a reference to this field within the parameter.
4351     CXXScopeSpec SS;
4352     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4353                               Sema::LookupMemberName);
4354     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4355                                   : cast<ValueDecl>(Field), AS_public);
4356     MemberLookup.resolveKind();
4357     ExprResult CtorArg
4358       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4359                                          ParamType, Loc,
4360                                          /*IsArrow=*/false,
4361                                          SS,
4362                                          /*TemplateKWLoc=*/SourceLocation(),
4363                                          /*FirstQualifierInScope=*/nullptr,
4364                                          MemberLookup,
4365                                          /*TemplateArgs=*/nullptr,
4366                                          /*S*/nullptr);
4367     if (CtorArg.isInvalid())
4368       return true;
4369 
4370     // C++11 [class.copy]p15:
4371     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4372     //     with static_cast<T&&>(x.m);
4373     if (RefersToRValueRef(CtorArg.get())) {
4374       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4375     }
4376 
4377     InitializedEntity Entity =
4378         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4379                                                        /*Implicit*/ true)
4380                  : InitializedEntity::InitializeMember(Field, nullptr,
4381                                                        /*Implicit*/ true);
4382 
4383     // Direct-initialize to use the copy constructor.
4384     InitializationKind InitKind =
4385       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4386 
4387     Expr *CtorArgE = CtorArg.getAs<Expr>();
4388     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4389     ExprResult MemberInit =
4390         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4391     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4392     if (MemberInit.isInvalid())
4393       return true;
4394 
4395     if (Indirect)
4396       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4397           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4398     else
4399       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4400           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4401     return false;
4402   }
4403 
4404   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4405          "Unhandled implicit init kind!");
4406 
4407   QualType FieldBaseElementType =
4408     SemaRef.Context.getBaseElementType(Field->getType());
4409 
4410   if (FieldBaseElementType->isRecordType()) {
4411     InitializedEntity InitEntity =
4412         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4413                                                        /*Implicit*/ true)
4414                  : InitializedEntity::InitializeMember(Field, nullptr,
4415                                                        /*Implicit*/ true);
4416     InitializationKind InitKind =
4417       InitializationKind::CreateDefault(Loc);
4418 
4419     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4420     ExprResult MemberInit =
4421       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4422 
4423     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4424     if (MemberInit.isInvalid())
4425       return true;
4426 
4427     if (Indirect)
4428       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4429                                                                Indirect, Loc,
4430                                                                Loc,
4431                                                                MemberInit.get(),
4432                                                                Loc);
4433     else
4434       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4435                                                                Field, Loc, Loc,
4436                                                                MemberInit.get(),
4437                                                                Loc);
4438     return false;
4439   }
4440 
4441   if (!Field->getParent()->isUnion()) {
4442     if (FieldBaseElementType->isReferenceType()) {
4443       SemaRef.Diag(Constructor->getLocation(),
4444                    diag::err_uninitialized_member_in_ctor)
4445       << (int)Constructor->isImplicit()
4446       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4447       << 0 << Field->getDeclName();
4448       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4449       return true;
4450     }
4451 
4452     if (FieldBaseElementType.isConstQualified()) {
4453       SemaRef.Diag(Constructor->getLocation(),
4454                    diag::err_uninitialized_member_in_ctor)
4455       << (int)Constructor->isImplicit()
4456       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4457       << 1 << Field->getDeclName();
4458       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4459       return true;
4460     }
4461   }
4462 
4463   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4464     // ARC and Weak:
4465     //   Default-initialize Objective-C pointers to NULL.
4466     CXXMemberInit
4467       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4468                                                  Loc, Loc,
4469                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4470                                                  Loc);
4471     return false;
4472   }
4473 
4474   // Nothing to initialize.
4475   CXXMemberInit = nullptr;
4476   return false;
4477 }
4478 
4479 namespace {
4480 struct BaseAndFieldInfo {
4481   Sema &S;
4482   CXXConstructorDecl *Ctor;
4483   bool AnyErrorsInInits;
4484   ImplicitInitializerKind IIK;
4485   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4486   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4487   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4488 
4489   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4490     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4491     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4492     if (Ctor->getInheritedConstructor())
4493       IIK = IIK_Inherit;
4494     else if (Generated && Ctor->isCopyConstructor())
4495       IIK = IIK_Copy;
4496     else if (Generated && Ctor->isMoveConstructor())
4497       IIK = IIK_Move;
4498     else
4499       IIK = IIK_Default;
4500   }
4501 
4502   bool isImplicitCopyOrMove() const {
4503     switch (IIK) {
4504     case IIK_Copy:
4505     case IIK_Move:
4506       return true;
4507 
4508     case IIK_Default:
4509     case IIK_Inherit:
4510       return false;
4511     }
4512 
4513     llvm_unreachable("Invalid ImplicitInitializerKind!");
4514   }
4515 
4516   bool addFieldInitializer(CXXCtorInitializer *Init) {
4517     AllToInit.push_back(Init);
4518 
4519     // Check whether this initializer makes the field "used".
4520     if (Init->getInit()->HasSideEffects(S.Context))
4521       S.UnusedPrivateFields.remove(Init->getAnyMember());
4522 
4523     return false;
4524   }
4525 
4526   bool isInactiveUnionMember(FieldDecl *Field) {
4527     RecordDecl *Record = Field->getParent();
4528     if (!Record->isUnion())
4529       return false;
4530 
4531     if (FieldDecl *Active =
4532             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4533       return Active != Field->getCanonicalDecl();
4534 
4535     // In an implicit copy or move constructor, ignore any in-class initializer.
4536     if (isImplicitCopyOrMove())
4537       return true;
4538 
4539     // If there's no explicit initialization, the field is active only if it
4540     // has an in-class initializer...
4541     if (Field->hasInClassInitializer())
4542       return false;
4543     // ... or it's an anonymous struct or union whose class has an in-class
4544     // initializer.
4545     if (!Field->isAnonymousStructOrUnion())
4546       return true;
4547     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4548     return !FieldRD->hasInClassInitializer();
4549   }
4550 
4551   /// Determine whether the given field is, or is within, a union member
4552   /// that is inactive (because there was an initializer given for a different
4553   /// member of the union, or because the union was not initialized at all).
4554   bool isWithinInactiveUnionMember(FieldDecl *Field,
4555                                    IndirectFieldDecl *Indirect) {
4556     if (!Indirect)
4557       return isInactiveUnionMember(Field);
4558 
4559     for (auto *C : Indirect->chain()) {
4560       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4561       if (Field && isInactiveUnionMember(Field))
4562         return true;
4563     }
4564     return false;
4565   }
4566 };
4567 }
4568 
4569 /// Determine whether the given type is an incomplete or zero-lenfgth
4570 /// array type.
4571 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4572   if (T->isIncompleteArrayType())
4573     return true;
4574 
4575   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4576     if (!ArrayT->getSize())
4577       return true;
4578 
4579     T = ArrayT->getElementType();
4580   }
4581 
4582   return false;
4583 }
4584 
4585 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4586                                     FieldDecl *Field,
4587                                     IndirectFieldDecl *Indirect = nullptr) {
4588   if (Field->isInvalidDecl())
4589     return false;
4590 
4591   // Overwhelmingly common case: we have a direct initializer for this field.
4592   if (CXXCtorInitializer *Init =
4593           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4594     return Info.addFieldInitializer(Init);
4595 
4596   // C++11 [class.base.init]p8:
4597   //   if the entity is a non-static data member that has a
4598   //   brace-or-equal-initializer and either
4599   //   -- the constructor's class is a union and no other variant member of that
4600   //      union is designated by a mem-initializer-id or
4601   //   -- the constructor's class is not a union, and, if the entity is a member
4602   //      of an anonymous union, no other member of that union is designated by
4603   //      a mem-initializer-id,
4604   //   the entity is initialized as specified in [dcl.init].
4605   //
4606   // We also apply the same rules to handle anonymous structs within anonymous
4607   // unions.
4608   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4609     return false;
4610 
4611   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4612     ExprResult DIE =
4613         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4614     if (DIE.isInvalid())
4615       return true;
4616 
4617     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4618     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4619 
4620     CXXCtorInitializer *Init;
4621     if (Indirect)
4622       Init = new (SemaRef.Context)
4623           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4624                              SourceLocation(), DIE.get(), SourceLocation());
4625     else
4626       Init = new (SemaRef.Context)
4627           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4628                              SourceLocation(), DIE.get(), SourceLocation());
4629     return Info.addFieldInitializer(Init);
4630   }
4631 
4632   // Don't initialize incomplete or zero-length arrays.
4633   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4634     return false;
4635 
4636   // Don't try to build an implicit initializer if there were semantic
4637   // errors in any of the initializers (and therefore we might be
4638   // missing some that the user actually wrote).
4639   if (Info.AnyErrorsInInits)
4640     return false;
4641 
4642   CXXCtorInitializer *Init = nullptr;
4643   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4644                                      Indirect, Init))
4645     return true;
4646 
4647   if (!Init)
4648     return false;
4649 
4650   return Info.addFieldInitializer(Init);
4651 }
4652 
4653 bool
4654 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4655                                CXXCtorInitializer *Initializer) {
4656   assert(Initializer->isDelegatingInitializer());
4657   Constructor->setNumCtorInitializers(1);
4658   CXXCtorInitializer **initializer =
4659     new (Context) CXXCtorInitializer*[1];
4660   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4661   Constructor->setCtorInitializers(initializer);
4662 
4663   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4664     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4665     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4666   }
4667 
4668   DelegatingCtorDecls.push_back(Constructor);
4669 
4670   DiagnoseUninitializedFields(*this, Constructor);
4671 
4672   return false;
4673 }
4674 
4675 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4676                                ArrayRef<CXXCtorInitializer *> Initializers) {
4677   if (Constructor->isDependentContext()) {
4678     // Just store the initializers as written, they will be checked during
4679     // instantiation.
4680     if (!Initializers.empty()) {
4681       Constructor->setNumCtorInitializers(Initializers.size());
4682       CXXCtorInitializer **baseOrMemberInitializers =
4683         new (Context) CXXCtorInitializer*[Initializers.size()];
4684       memcpy(baseOrMemberInitializers, Initializers.data(),
4685              Initializers.size() * sizeof(CXXCtorInitializer*));
4686       Constructor->setCtorInitializers(baseOrMemberInitializers);
4687     }
4688 
4689     // Let template instantiation know whether we had errors.
4690     if (AnyErrors)
4691       Constructor->setInvalidDecl();
4692 
4693     return false;
4694   }
4695 
4696   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4697 
4698   // We need to build the initializer AST according to order of construction
4699   // and not what user specified in the Initializers list.
4700   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4701   if (!ClassDecl)
4702     return true;
4703 
4704   bool HadError = false;
4705 
4706   for (unsigned i = 0; i < Initializers.size(); i++) {
4707     CXXCtorInitializer *Member = Initializers[i];
4708 
4709     if (Member->isBaseInitializer())
4710       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4711     else {
4712       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4713 
4714       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4715         for (auto *C : F->chain()) {
4716           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4717           if (FD && FD->getParent()->isUnion())
4718             Info.ActiveUnionMember.insert(std::make_pair(
4719                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4720         }
4721       } else if (FieldDecl *FD = Member->getMember()) {
4722         if (FD->getParent()->isUnion())
4723           Info.ActiveUnionMember.insert(std::make_pair(
4724               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4725       }
4726     }
4727   }
4728 
4729   // Keep track of the direct virtual bases.
4730   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4731   for (auto &I : ClassDecl->bases()) {
4732     if (I.isVirtual())
4733       DirectVBases.insert(&I);
4734   }
4735 
4736   // Push virtual bases before others.
4737   for (auto &VBase : ClassDecl->vbases()) {
4738     if (CXXCtorInitializer *Value
4739         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4740       // [class.base.init]p7, per DR257:
4741       //   A mem-initializer where the mem-initializer-id names a virtual base
4742       //   class is ignored during execution of a constructor of any class that
4743       //   is not the most derived class.
4744       if (ClassDecl->isAbstract()) {
4745         // FIXME: Provide a fixit to remove the base specifier. This requires
4746         // tracking the location of the associated comma for a base specifier.
4747         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4748           << VBase.getType() << ClassDecl;
4749         DiagnoseAbstractType(ClassDecl);
4750       }
4751 
4752       Info.AllToInit.push_back(Value);
4753     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4754       // [class.base.init]p8, per DR257:
4755       //   If a given [...] base class is not named by a mem-initializer-id
4756       //   [...] and the entity is not a virtual base class of an abstract
4757       //   class, then [...] the entity is default-initialized.
4758       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4759       CXXCtorInitializer *CXXBaseInit;
4760       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4761                                        &VBase, IsInheritedVirtualBase,
4762                                        CXXBaseInit)) {
4763         HadError = true;
4764         continue;
4765       }
4766 
4767       Info.AllToInit.push_back(CXXBaseInit);
4768     }
4769   }
4770 
4771   // Non-virtual bases.
4772   for (auto &Base : ClassDecl->bases()) {
4773     // Virtuals are in the virtual base list and already constructed.
4774     if (Base.isVirtual())
4775       continue;
4776 
4777     if (CXXCtorInitializer *Value
4778           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4779       Info.AllToInit.push_back(Value);
4780     } else if (!AnyErrors) {
4781       CXXCtorInitializer *CXXBaseInit;
4782       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4783                                        &Base, /*IsInheritedVirtualBase=*/false,
4784                                        CXXBaseInit)) {
4785         HadError = true;
4786         continue;
4787       }
4788 
4789       Info.AllToInit.push_back(CXXBaseInit);
4790     }
4791   }
4792 
4793   // Fields.
4794   for (auto *Mem : ClassDecl->decls()) {
4795     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4796       // C++ [class.bit]p2:
4797       //   A declaration for a bit-field that omits the identifier declares an
4798       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4799       //   initialized.
4800       if (F->isUnnamedBitfield())
4801         continue;
4802 
4803       // If we're not generating the implicit copy/move constructor, then we'll
4804       // handle anonymous struct/union fields based on their individual
4805       // indirect fields.
4806       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4807         continue;
4808 
4809       if (CollectFieldInitializer(*this, Info, F))
4810         HadError = true;
4811       continue;
4812     }
4813 
4814     // Beyond this point, we only consider default initialization.
4815     if (Info.isImplicitCopyOrMove())
4816       continue;
4817 
4818     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4819       if (F->getType()->isIncompleteArrayType()) {
4820         assert(ClassDecl->hasFlexibleArrayMember() &&
4821                "Incomplete array type is not valid");
4822         continue;
4823       }
4824 
4825       // Initialize each field of an anonymous struct individually.
4826       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4827         HadError = true;
4828 
4829       continue;
4830     }
4831   }
4832 
4833   unsigned NumInitializers = Info.AllToInit.size();
4834   if (NumInitializers > 0) {
4835     Constructor->setNumCtorInitializers(NumInitializers);
4836     CXXCtorInitializer **baseOrMemberInitializers =
4837       new (Context) CXXCtorInitializer*[NumInitializers];
4838     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4839            NumInitializers * sizeof(CXXCtorInitializer*));
4840     Constructor->setCtorInitializers(baseOrMemberInitializers);
4841 
4842     // Constructors implicitly reference the base and member
4843     // destructors.
4844     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4845                                            Constructor->getParent());
4846   }
4847 
4848   return HadError;
4849 }
4850 
4851 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4852   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4853     const RecordDecl *RD = RT->getDecl();
4854     if (RD->isAnonymousStructOrUnion()) {
4855       for (auto *Field : RD->fields())
4856         PopulateKeysForFields(Field, IdealInits);
4857       return;
4858     }
4859   }
4860   IdealInits.push_back(Field->getCanonicalDecl());
4861 }
4862 
4863 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4864   return Context.getCanonicalType(BaseType).getTypePtr();
4865 }
4866 
4867 static const void *GetKeyForMember(ASTContext &Context,
4868                                    CXXCtorInitializer *Member) {
4869   if (!Member->isAnyMemberInitializer())
4870     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4871 
4872   return Member->getAnyMember()->getCanonicalDecl();
4873 }
4874 
4875 static void DiagnoseBaseOrMemInitializerOrder(
4876     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4877     ArrayRef<CXXCtorInitializer *> Inits) {
4878   if (Constructor->getDeclContext()->isDependentContext())
4879     return;
4880 
4881   // Don't check initializers order unless the warning is enabled at the
4882   // location of at least one initializer.
4883   bool ShouldCheckOrder = false;
4884   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4885     CXXCtorInitializer *Init = Inits[InitIndex];
4886     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4887                                  Init->getSourceLocation())) {
4888       ShouldCheckOrder = true;
4889       break;
4890     }
4891   }
4892   if (!ShouldCheckOrder)
4893     return;
4894 
4895   // Build the list of bases and members in the order that they'll
4896   // actually be initialized.  The explicit initializers should be in
4897   // this same order but may be missing things.
4898   SmallVector<const void*, 32> IdealInitKeys;
4899 
4900   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4901 
4902   // 1. Virtual bases.
4903   for (const auto &VBase : ClassDecl->vbases())
4904     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4905 
4906   // 2. Non-virtual bases.
4907   for (const auto &Base : ClassDecl->bases()) {
4908     if (Base.isVirtual())
4909       continue;
4910     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4911   }
4912 
4913   // 3. Direct fields.
4914   for (auto *Field : ClassDecl->fields()) {
4915     if (Field->isUnnamedBitfield())
4916       continue;
4917 
4918     PopulateKeysForFields(Field, IdealInitKeys);
4919   }
4920 
4921   unsigned NumIdealInits = IdealInitKeys.size();
4922   unsigned IdealIndex = 0;
4923 
4924   CXXCtorInitializer *PrevInit = nullptr;
4925   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4926     CXXCtorInitializer *Init = Inits[InitIndex];
4927     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4928 
4929     // Scan forward to try to find this initializer in the idealized
4930     // initializers list.
4931     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4932       if (InitKey == IdealInitKeys[IdealIndex])
4933         break;
4934 
4935     // If we didn't find this initializer, it must be because we
4936     // scanned past it on a previous iteration.  That can only
4937     // happen if we're out of order;  emit a warning.
4938     if (IdealIndex == NumIdealInits && PrevInit) {
4939       Sema::SemaDiagnosticBuilder D =
4940         SemaRef.Diag(PrevInit->getSourceLocation(),
4941                      diag::warn_initializer_out_of_order);
4942 
4943       if (PrevInit->isAnyMemberInitializer())
4944         D << 0 << PrevInit->getAnyMember()->getDeclName();
4945       else
4946         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4947 
4948       if (Init->isAnyMemberInitializer())
4949         D << 0 << Init->getAnyMember()->getDeclName();
4950       else
4951         D << 1 << Init->getTypeSourceInfo()->getType();
4952 
4953       // Move back to the initializer's location in the ideal list.
4954       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4955         if (InitKey == IdealInitKeys[IdealIndex])
4956           break;
4957 
4958       assert(IdealIndex < NumIdealInits &&
4959              "initializer not found in initializer list");
4960     }
4961 
4962     PrevInit = Init;
4963   }
4964 }
4965 
4966 namespace {
4967 bool CheckRedundantInit(Sema &S,
4968                         CXXCtorInitializer *Init,
4969                         CXXCtorInitializer *&PrevInit) {
4970   if (!PrevInit) {
4971     PrevInit = Init;
4972     return false;
4973   }
4974 
4975   if (FieldDecl *Field = Init->getAnyMember())
4976     S.Diag(Init->getSourceLocation(),
4977            diag::err_multiple_mem_initialization)
4978       << Field->getDeclName()
4979       << Init->getSourceRange();
4980   else {
4981     const Type *BaseClass = Init->getBaseClass();
4982     assert(BaseClass && "neither field nor base");
4983     S.Diag(Init->getSourceLocation(),
4984            diag::err_multiple_base_initialization)
4985       << QualType(BaseClass, 0)
4986       << Init->getSourceRange();
4987   }
4988   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4989     << 0 << PrevInit->getSourceRange();
4990 
4991   return true;
4992 }
4993 
4994 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4995 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4996 
4997 bool CheckRedundantUnionInit(Sema &S,
4998                              CXXCtorInitializer *Init,
4999                              RedundantUnionMap &Unions) {
5000   FieldDecl *Field = Init->getAnyMember();
5001   RecordDecl *Parent = Field->getParent();
5002   NamedDecl *Child = Field;
5003 
5004   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5005     if (Parent->isUnion()) {
5006       UnionEntry &En = Unions[Parent];
5007       if (En.first && En.first != Child) {
5008         S.Diag(Init->getSourceLocation(),
5009                diag::err_multiple_mem_union_initialization)
5010           << Field->getDeclName()
5011           << Init->getSourceRange();
5012         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5013           << 0 << En.second->getSourceRange();
5014         return true;
5015       }
5016       if (!En.first) {
5017         En.first = Child;
5018         En.second = Init;
5019       }
5020       if (!Parent->isAnonymousStructOrUnion())
5021         return false;
5022     }
5023 
5024     Child = Parent;
5025     Parent = cast<RecordDecl>(Parent->getDeclContext());
5026   }
5027 
5028   return false;
5029 }
5030 }
5031 
5032 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5033 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5034                                 SourceLocation ColonLoc,
5035                                 ArrayRef<CXXCtorInitializer*> MemInits,
5036                                 bool AnyErrors) {
5037   if (!ConstructorDecl)
5038     return;
5039 
5040   AdjustDeclIfTemplate(ConstructorDecl);
5041 
5042   CXXConstructorDecl *Constructor
5043     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5044 
5045   if (!Constructor) {
5046     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5047     return;
5048   }
5049 
5050   // Mapping for the duplicate initializers check.
5051   // For member initializers, this is keyed with a FieldDecl*.
5052   // For base initializers, this is keyed with a Type*.
5053   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5054 
5055   // Mapping for the inconsistent anonymous-union initializers check.
5056   RedundantUnionMap MemberUnions;
5057 
5058   bool HadError = false;
5059   for (unsigned i = 0; i < MemInits.size(); i++) {
5060     CXXCtorInitializer *Init = MemInits[i];
5061 
5062     // Set the source order index.
5063     Init->setSourceOrder(i);
5064 
5065     if (Init->isAnyMemberInitializer()) {
5066       const void *Key = GetKeyForMember(Context, Init);
5067       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5068           CheckRedundantUnionInit(*this, Init, MemberUnions))
5069         HadError = true;
5070     } else if (Init->isBaseInitializer()) {
5071       const void *Key = GetKeyForMember(Context, Init);
5072       if (CheckRedundantInit(*this, Init, Members[Key]))
5073         HadError = true;
5074     } else {
5075       assert(Init->isDelegatingInitializer());
5076       // This must be the only initializer
5077       if (MemInits.size() != 1) {
5078         Diag(Init->getSourceLocation(),
5079              diag::err_delegating_initializer_alone)
5080           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5081         // We will treat this as being the only initializer.
5082       }
5083       SetDelegatingInitializer(Constructor, MemInits[i]);
5084       // Return immediately as the initializer is set.
5085       return;
5086     }
5087   }
5088 
5089   if (HadError)
5090     return;
5091 
5092   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5093 
5094   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5095 
5096   DiagnoseUninitializedFields(*this, Constructor);
5097 }
5098 
5099 void
5100 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5101                                              CXXRecordDecl *ClassDecl) {
5102   // Ignore dependent contexts. Also ignore unions, since their members never
5103   // have destructors implicitly called.
5104   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5105     return;
5106 
5107   // FIXME: all the access-control diagnostics are positioned on the
5108   // field/base declaration.  That's probably good; that said, the
5109   // user might reasonably want to know why the destructor is being
5110   // emitted, and we currently don't say.
5111 
5112   // Non-static data members.
5113   for (auto *Field : ClassDecl->fields()) {
5114     if (Field->isInvalidDecl())
5115       continue;
5116 
5117     // Don't destroy incomplete or zero-length arrays.
5118     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5119       continue;
5120 
5121     QualType FieldType = Context.getBaseElementType(Field->getType());
5122 
5123     const RecordType* RT = FieldType->getAs<RecordType>();
5124     if (!RT)
5125       continue;
5126 
5127     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5128     if (FieldClassDecl->isInvalidDecl())
5129       continue;
5130     if (FieldClassDecl->hasIrrelevantDestructor())
5131       continue;
5132     // The destructor for an implicit anonymous union member is never invoked.
5133     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5134       continue;
5135 
5136     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5137     assert(Dtor && "No dtor found for FieldClassDecl!");
5138     CheckDestructorAccess(Field->getLocation(), Dtor,
5139                           PDiag(diag::err_access_dtor_field)
5140                             << Field->getDeclName()
5141                             << FieldType);
5142 
5143     MarkFunctionReferenced(Location, Dtor);
5144     DiagnoseUseOfDecl(Dtor, Location);
5145   }
5146 
5147   // We only potentially invoke the destructors of potentially constructed
5148   // subobjects.
5149   bool VisitVirtualBases = !ClassDecl->isAbstract();
5150 
5151   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5152 
5153   // Bases.
5154   for (const auto &Base : ClassDecl->bases()) {
5155     // Bases are always records in a well-formed non-dependent class.
5156     const RecordType *RT = Base.getType()->getAs<RecordType>();
5157 
5158     // Remember direct virtual bases.
5159     if (Base.isVirtual()) {
5160       if (!VisitVirtualBases)
5161         continue;
5162       DirectVirtualBases.insert(RT);
5163     }
5164 
5165     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5166     // If our base class is invalid, we probably can't get its dtor anyway.
5167     if (BaseClassDecl->isInvalidDecl())
5168       continue;
5169     if (BaseClassDecl->hasIrrelevantDestructor())
5170       continue;
5171 
5172     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5173     assert(Dtor && "No dtor found for BaseClassDecl!");
5174 
5175     // FIXME: caret should be on the start of the class name
5176     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5177                           PDiag(diag::err_access_dtor_base)
5178                               << Base.getType() << Base.getSourceRange(),
5179                           Context.getTypeDeclType(ClassDecl));
5180 
5181     MarkFunctionReferenced(Location, Dtor);
5182     DiagnoseUseOfDecl(Dtor, Location);
5183   }
5184 
5185   if (!VisitVirtualBases)
5186     return;
5187 
5188   // Virtual bases.
5189   for (const auto &VBase : ClassDecl->vbases()) {
5190     // Bases are always records in a well-formed non-dependent class.
5191     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5192 
5193     // Ignore direct virtual bases.
5194     if (DirectVirtualBases.count(RT))
5195       continue;
5196 
5197     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5198     // If our base class is invalid, we probably can't get its dtor anyway.
5199     if (BaseClassDecl->isInvalidDecl())
5200       continue;
5201     if (BaseClassDecl->hasIrrelevantDestructor())
5202       continue;
5203 
5204     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5205     assert(Dtor && "No dtor found for BaseClassDecl!");
5206     if (CheckDestructorAccess(
5207             ClassDecl->getLocation(), Dtor,
5208             PDiag(diag::err_access_dtor_vbase)
5209                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5210             Context.getTypeDeclType(ClassDecl)) ==
5211         AR_accessible) {
5212       CheckDerivedToBaseConversion(
5213           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5214           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5215           SourceRange(), DeclarationName(), nullptr);
5216     }
5217 
5218     MarkFunctionReferenced(Location, Dtor);
5219     DiagnoseUseOfDecl(Dtor, Location);
5220   }
5221 }
5222 
5223 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5224   if (!CDtorDecl)
5225     return;
5226 
5227   if (CXXConstructorDecl *Constructor
5228       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5229     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5230     DiagnoseUninitializedFields(*this, Constructor);
5231   }
5232 }
5233 
5234 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5235   if (!getLangOpts().CPlusPlus)
5236     return false;
5237 
5238   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5239   if (!RD)
5240     return false;
5241 
5242   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5243   // class template specialization here, but doing so breaks a lot of code.
5244 
5245   // We can't answer whether something is abstract until it has a
5246   // definition. If it's currently being defined, we'll walk back
5247   // over all the declarations when we have a full definition.
5248   const CXXRecordDecl *Def = RD->getDefinition();
5249   if (!Def || Def->isBeingDefined())
5250     return false;
5251 
5252   return RD->isAbstract();
5253 }
5254 
5255 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5256                                   TypeDiagnoser &Diagnoser) {
5257   if (!isAbstractType(Loc, T))
5258     return false;
5259 
5260   T = Context.getBaseElementType(T);
5261   Diagnoser.diagnose(*this, Loc, T);
5262   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5263   return true;
5264 }
5265 
5266 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5267   // Check if we've already emitted the list of pure virtual functions
5268   // for this class.
5269   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5270     return;
5271 
5272   // If the diagnostic is suppressed, don't emit the notes. We're only
5273   // going to emit them once, so try to attach them to a diagnostic we're
5274   // actually going to show.
5275   if (Diags.isLastDiagnosticIgnored())
5276     return;
5277 
5278   CXXFinalOverriderMap FinalOverriders;
5279   RD->getFinalOverriders(FinalOverriders);
5280 
5281   // Keep a set of seen pure methods so we won't diagnose the same method
5282   // more than once.
5283   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5284 
5285   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5286                                    MEnd = FinalOverriders.end();
5287        M != MEnd;
5288        ++M) {
5289     for (OverridingMethods::iterator SO = M->second.begin(),
5290                                   SOEnd = M->second.end();
5291          SO != SOEnd; ++SO) {
5292       // C++ [class.abstract]p4:
5293       //   A class is abstract if it contains or inherits at least one
5294       //   pure virtual function for which the final overrider is pure
5295       //   virtual.
5296 
5297       //
5298       if (SO->second.size() != 1)
5299         continue;
5300 
5301       if (!SO->second.front().Method->isPure())
5302         continue;
5303 
5304       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5305         continue;
5306 
5307       Diag(SO->second.front().Method->getLocation(),
5308            diag::note_pure_virtual_function)
5309         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5310     }
5311   }
5312 
5313   if (!PureVirtualClassDiagSet)
5314     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5315   PureVirtualClassDiagSet->insert(RD);
5316 }
5317 
5318 namespace {
5319 struct AbstractUsageInfo {
5320   Sema &S;
5321   CXXRecordDecl *Record;
5322   CanQualType AbstractType;
5323   bool Invalid;
5324 
5325   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5326     : S(S), Record(Record),
5327       AbstractType(S.Context.getCanonicalType(
5328                    S.Context.getTypeDeclType(Record))),
5329       Invalid(false) {}
5330 
5331   void DiagnoseAbstractType() {
5332     if (Invalid) return;
5333     S.DiagnoseAbstractType(Record);
5334     Invalid = true;
5335   }
5336 
5337   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5338 };
5339 
5340 struct CheckAbstractUsage {
5341   AbstractUsageInfo &Info;
5342   const NamedDecl *Ctx;
5343 
5344   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5345     : Info(Info), Ctx(Ctx) {}
5346 
5347   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5348     switch (TL.getTypeLocClass()) {
5349 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5350 #define TYPELOC(CLASS, PARENT) \
5351     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5352 #include "clang/AST/TypeLocNodes.def"
5353     }
5354   }
5355 
5356   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5357     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5358     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5359       if (!TL.getParam(I))
5360         continue;
5361 
5362       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5363       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5364     }
5365   }
5366 
5367   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5368     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5369   }
5370 
5371   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5372     // Visit the type parameters from a permissive context.
5373     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5374       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5375       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5376         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5377           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5378       // TODO: other template argument types?
5379     }
5380   }
5381 
5382   // Visit pointee types from a permissive context.
5383 #define CheckPolymorphic(Type) \
5384   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5385     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5386   }
5387   CheckPolymorphic(PointerTypeLoc)
5388   CheckPolymorphic(ReferenceTypeLoc)
5389   CheckPolymorphic(MemberPointerTypeLoc)
5390   CheckPolymorphic(BlockPointerTypeLoc)
5391   CheckPolymorphic(AtomicTypeLoc)
5392 
5393   /// Handle all the types we haven't given a more specific
5394   /// implementation for above.
5395   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5396     // Every other kind of type that we haven't called out already
5397     // that has an inner type is either (1) sugar or (2) contains that
5398     // inner type in some way as a subobject.
5399     if (TypeLoc Next = TL.getNextTypeLoc())
5400       return Visit(Next, Sel);
5401 
5402     // If there's no inner type and we're in a permissive context,
5403     // don't diagnose.
5404     if (Sel == Sema::AbstractNone) return;
5405 
5406     // Check whether the type matches the abstract type.
5407     QualType T = TL.getType();
5408     if (T->isArrayType()) {
5409       Sel = Sema::AbstractArrayType;
5410       T = Info.S.Context.getBaseElementType(T);
5411     }
5412     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5413     if (CT != Info.AbstractType) return;
5414 
5415     // It matched; do some magic.
5416     if (Sel == Sema::AbstractArrayType) {
5417       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5418         << T << TL.getSourceRange();
5419     } else {
5420       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5421         << Sel << T << TL.getSourceRange();
5422     }
5423     Info.DiagnoseAbstractType();
5424   }
5425 };
5426 
5427 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5428                                   Sema::AbstractDiagSelID Sel) {
5429   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5430 }
5431 
5432 }
5433 
5434 /// Check for invalid uses of an abstract type in a method declaration.
5435 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5436                                     CXXMethodDecl *MD) {
5437   // No need to do the check on definitions, which require that
5438   // the return/param types be complete.
5439   if (MD->doesThisDeclarationHaveABody())
5440     return;
5441 
5442   // For safety's sake, just ignore it if we don't have type source
5443   // information.  This should never happen for non-implicit methods,
5444   // but...
5445   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5446     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5447 }
5448 
5449 /// Check for invalid uses of an abstract type within a class definition.
5450 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5451                                     CXXRecordDecl *RD) {
5452   for (auto *D : RD->decls()) {
5453     if (D->isImplicit()) continue;
5454 
5455     // Methods and method templates.
5456     if (isa<CXXMethodDecl>(D)) {
5457       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5458     } else if (isa<FunctionTemplateDecl>(D)) {
5459       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5460       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5461 
5462     // Fields and static variables.
5463     } else if (isa<FieldDecl>(D)) {
5464       FieldDecl *FD = cast<FieldDecl>(D);
5465       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5466         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5467     } else if (isa<VarDecl>(D)) {
5468       VarDecl *VD = cast<VarDecl>(D);
5469       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5470         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5471 
5472     // Nested classes and class templates.
5473     } else if (isa<CXXRecordDecl>(D)) {
5474       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5475     } else if (isa<ClassTemplateDecl>(D)) {
5476       CheckAbstractClassUsage(Info,
5477                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5478     }
5479   }
5480 }
5481 
5482 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5483   Attr *ClassAttr = getDLLAttr(Class);
5484   if (!ClassAttr)
5485     return;
5486 
5487   assert(ClassAttr->getKind() == attr::DLLExport);
5488 
5489   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5490 
5491   if (TSK == TSK_ExplicitInstantiationDeclaration)
5492     // Don't go any further if this is just an explicit instantiation
5493     // declaration.
5494     return;
5495 
5496   for (Decl *Member : Class->decls()) {
5497     // Defined static variables that are members of an exported base
5498     // class must be marked export too.
5499     auto *VD = dyn_cast<VarDecl>(Member);
5500     if (VD && Member->getAttr<DLLExportAttr>() &&
5501         VD->getStorageClass() == SC_Static &&
5502         TSK == TSK_ImplicitInstantiation)
5503       S.MarkVariableReferenced(VD->getLocation(), VD);
5504 
5505     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5506     if (!MD)
5507       continue;
5508 
5509     if (Member->getAttr<DLLExportAttr>()) {
5510       if (MD->isUserProvided()) {
5511         // Instantiate non-default class member functions ...
5512 
5513         // .. except for certain kinds of template specializations.
5514         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5515           continue;
5516 
5517         S.MarkFunctionReferenced(Class->getLocation(), MD);
5518 
5519         // The function will be passed to the consumer when its definition is
5520         // encountered.
5521       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5522                  MD->isCopyAssignmentOperator() ||
5523                  MD->isMoveAssignmentOperator()) {
5524         // Synthesize and instantiate non-trivial implicit methods, explicitly
5525         // defaulted methods, and the copy and move assignment operators. The
5526         // latter are exported even if they are trivial, because the address of
5527         // an operator can be taken and should compare equal across libraries.
5528         DiagnosticErrorTrap Trap(S.Diags);
5529         S.MarkFunctionReferenced(Class->getLocation(), MD);
5530         if (Trap.hasErrorOccurred()) {
5531           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5532               << Class << !S.getLangOpts().CPlusPlus11;
5533           break;
5534         }
5535 
5536         // There is no later point when we will see the definition of this
5537         // function, so pass it to the consumer now.
5538         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5539       }
5540     }
5541   }
5542 }
5543 
5544 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5545                                                         CXXRecordDecl *Class) {
5546   // Only the MS ABI has default constructor closures, so we don't need to do
5547   // this semantic checking anywhere else.
5548   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5549     return;
5550 
5551   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5552   for (Decl *Member : Class->decls()) {
5553     // Look for exported default constructors.
5554     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5555     if (!CD || !CD->isDefaultConstructor())
5556       continue;
5557     auto *Attr = CD->getAttr<DLLExportAttr>();
5558     if (!Attr)
5559       continue;
5560 
5561     // If the class is non-dependent, mark the default arguments as ODR-used so
5562     // that we can properly codegen the constructor closure.
5563     if (!Class->isDependentContext()) {
5564       for (ParmVarDecl *PD : CD->parameters()) {
5565         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5566         S.DiscardCleanupsInEvaluationContext();
5567       }
5568     }
5569 
5570     if (LastExportedDefaultCtor) {
5571       S.Diag(LastExportedDefaultCtor->getLocation(),
5572              diag::err_attribute_dll_ambiguous_default_ctor)
5573           << Class;
5574       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5575           << CD->getDeclName();
5576       return;
5577     }
5578     LastExportedDefaultCtor = CD;
5579   }
5580 }
5581 
5582 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5583   // Mark any compiler-generated routines with the implicit code_seg attribute.
5584   for (auto *Method : Class->methods()) {
5585     if (Method->isUserProvided())
5586       continue;
5587     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5588       Method->addAttr(A);
5589   }
5590 }
5591 
5592 /// Check class-level dllimport/dllexport attribute.
5593 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5594   Attr *ClassAttr = getDLLAttr(Class);
5595 
5596   // MSVC inherits DLL attributes to partial class template specializations.
5597   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5598     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5599       if (Attr *TemplateAttr =
5600               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5601         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5602         A->setInherited(true);
5603         ClassAttr = A;
5604       }
5605     }
5606   }
5607 
5608   if (!ClassAttr)
5609     return;
5610 
5611   if (!Class->isExternallyVisible()) {
5612     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5613         << Class << ClassAttr;
5614     return;
5615   }
5616 
5617   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5618       !ClassAttr->isInherited()) {
5619     // Diagnose dll attributes on members of class with dll attribute.
5620     for (Decl *Member : Class->decls()) {
5621       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5622         continue;
5623       InheritableAttr *MemberAttr = getDLLAttr(Member);
5624       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5625         continue;
5626 
5627       Diag(MemberAttr->getLocation(),
5628              diag::err_attribute_dll_member_of_dll_class)
5629           << MemberAttr << ClassAttr;
5630       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5631       Member->setInvalidDecl();
5632     }
5633   }
5634 
5635   if (Class->getDescribedClassTemplate())
5636     // Don't inherit dll attribute until the template is instantiated.
5637     return;
5638 
5639   // The class is either imported or exported.
5640   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5641 
5642   // Check if this was a dllimport attribute propagated from a derived class to
5643   // a base class template specialization. We don't apply these attributes to
5644   // static data members.
5645   const bool PropagatedImport =
5646       !ClassExported &&
5647       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5648 
5649   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5650 
5651   // Ignore explicit dllexport on explicit class template instantiation declarations.
5652   if (ClassExported && !ClassAttr->isInherited() &&
5653       TSK == TSK_ExplicitInstantiationDeclaration) {
5654     Class->dropAttr<DLLExportAttr>();
5655     return;
5656   }
5657 
5658   // Force declaration of implicit members so they can inherit the attribute.
5659   ForceDeclarationOfImplicitMembers(Class);
5660 
5661   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5662   // seem to be true in practice?
5663 
5664   for (Decl *Member : Class->decls()) {
5665     VarDecl *VD = dyn_cast<VarDecl>(Member);
5666     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5667 
5668     // Only methods and static fields inherit the attributes.
5669     if (!VD && !MD)
5670       continue;
5671 
5672     if (MD) {
5673       // Don't process deleted methods.
5674       if (MD->isDeleted())
5675         continue;
5676 
5677       if (MD->isInlined()) {
5678         // MinGW does not import or export inline methods.
5679         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5680             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5681           continue;
5682 
5683         // MSVC versions before 2015 don't export the move assignment operators
5684         // and move constructor, so don't attempt to import/export them if
5685         // we have a definition.
5686         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5687         if ((MD->isMoveAssignmentOperator() ||
5688              (Ctor && Ctor->isMoveConstructor())) &&
5689             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5690           continue;
5691 
5692         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5693         // operator is exported anyway.
5694         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5695             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5696           continue;
5697       }
5698     }
5699 
5700     // Don't apply dllimport attributes to static data members of class template
5701     // instantiations when the attribute is propagated from a derived class.
5702     if (VD && PropagatedImport)
5703       continue;
5704 
5705     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5706       continue;
5707 
5708     if (!getDLLAttr(Member)) {
5709       InheritableAttr *NewAttr = nullptr;
5710 
5711       // Do not export/import inline function when -fno-dllexport-inlines is
5712       // passed. But add attribute for later local static var check.
5713       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5714           TSK != TSK_ExplicitInstantiationDeclaration &&
5715           TSK != TSK_ExplicitInstantiationDefinition) {
5716         if (ClassExported) {
5717           NewAttr = ::new (getASTContext())
5718             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5719                                      getASTContext(),
5720                                      ClassAttr->getSpellingListIndex());
5721         } else {
5722           NewAttr = ::new (getASTContext())
5723             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5724                                      getASTContext(),
5725                                      ClassAttr->getSpellingListIndex());
5726         }
5727       } else {
5728         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5729       }
5730 
5731       NewAttr->setInherited(true);
5732       Member->addAttr(NewAttr);
5733 
5734       if (MD) {
5735         // Propagate DLLAttr to friend re-declarations of MD that have already
5736         // been constructed.
5737         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5738              FD = FD->getPreviousDecl()) {
5739           if (FD->getFriendObjectKind() == Decl::FOK_None)
5740             continue;
5741           assert(!getDLLAttr(FD) &&
5742                  "friend re-decl should not already have a DLLAttr");
5743           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5744           NewAttr->setInherited(true);
5745           FD->addAttr(NewAttr);
5746         }
5747       }
5748     }
5749   }
5750 
5751   if (ClassExported)
5752     DelayedDllExportClasses.push_back(Class);
5753 }
5754 
5755 /// Perform propagation of DLL attributes from a derived class to a
5756 /// templated base class for MS compatibility.
5757 void Sema::propagateDLLAttrToBaseClassTemplate(
5758     CXXRecordDecl *Class, Attr *ClassAttr,
5759     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5760   if (getDLLAttr(
5761           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5762     // If the base class template has a DLL attribute, don't try to change it.
5763     return;
5764   }
5765 
5766   auto TSK = BaseTemplateSpec->getSpecializationKind();
5767   if (!getDLLAttr(BaseTemplateSpec) &&
5768       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5769        TSK == TSK_ImplicitInstantiation)) {
5770     // The template hasn't been instantiated yet (or it has, but only as an
5771     // explicit instantiation declaration or implicit instantiation, which means
5772     // we haven't codegenned any members yet), so propagate the attribute.
5773     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5774     NewAttr->setInherited(true);
5775     BaseTemplateSpec->addAttr(NewAttr);
5776 
5777     // If this was an import, mark that we propagated it from a derived class to
5778     // a base class template specialization.
5779     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5780       ImportAttr->setPropagatedToBaseTemplate();
5781 
5782     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5783     // needs to be run again to work see the new attribute. Otherwise this will
5784     // get run whenever the template is instantiated.
5785     if (TSK != TSK_Undeclared)
5786       checkClassLevelDLLAttribute(BaseTemplateSpec);
5787 
5788     return;
5789   }
5790 
5791   if (getDLLAttr(BaseTemplateSpec)) {
5792     // The template has already been specialized or instantiated with an
5793     // attribute, explicitly or through propagation. We should not try to change
5794     // it.
5795     return;
5796   }
5797 
5798   // The template was previously instantiated or explicitly specialized without
5799   // a dll attribute, It's too late for us to add an attribute, so warn that
5800   // this is unsupported.
5801   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5802       << BaseTemplateSpec->isExplicitSpecialization();
5803   Diag(ClassAttr->getLocation(), diag::note_attribute);
5804   if (BaseTemplateSpec->isExplicitSpecialization()) {
5805     Diag(BaseTemplateSpec->getLocation(),
5806            diag::note_template_class_explicit_specialization_was_here)
5807         << BaseTemplateSpec;
5808   } else {
5809     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5810            diag::note_template_class_instantiation_was_here)
5811         << BaseTemplateSpec;
5812   }
5813 }
5814 
5815 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5816                                         SourceLocation DefaultLoc) {
5817   switch (S.getSpecialMember(MD)) {
5818   case Sema::CXXDefaultConstructor:
5819     S.DefineImplicitDefaultConstructor(DefaultLoc,
5820                                        cast<CXXConstructorDecl>(MD));
5821     break;
5822   case Sema::CXXCopyConstructor:
5823     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5824     break;
5825   case Sema::CXXCopyAssignment:
5826     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5827     break;
5828   case Sema::CXXDestructor:
5829     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5830     break;
5831   case Sema::CXXMoveConstructor:
5832     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5833     break;
5834   case Sema::CXXMoveAssignment:
5835     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5836     break;
5837   case Sema::CXXInvalid:
5838     llvm_unreachable("Invalid special member.");
5839   }
5840 }
5841 
5842 /// Determine whether a type is permitted to be passed or returned in
5843 /// registers, per C++ [class.temporary]p3.
5844 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5845                                TargetInfo::CallingConvKind CCK) {
5846   if (D->isDependentType() || D->isInvalidDecl())
5847     return false;
5848 
5849   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5850   // The PS4 platform ABI follows the behavior of Clang 3.2.
5851   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5852     return !D->hasNonTrivialDestructorForCall() &&
5853            !D->hasNonTrivialCopyConstructorForCall();
5854 
5855   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5856     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5857     bool DtorIsTrivialForCall = false;
5858 
5859     // If a class has at least one non-deleted, trivial copy constructor, it
5860     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5861     //
5862     // Note: This permits classes with non-trivial copy or move ctors to be
5863     // passed in registers, so long as they *also* have a trivial copy ctor,
5864     // which is non-conforming.
5865     if (D->needsImplicitCopyConstructor()) {
5866       if (!D->defaultedCopyConstructorIsDeleted()) {
5867         if (D->hasTrivialCopyConstructor())
5868           CopyCtorIsTrivial = true;
5869         if (D->hasTrivialCopyConstructorForCall())
5870           CopyCtorIsTrivialForCall = true;
5871       }
5872     } else {
5873       for (const CXXConstructorDecl *CD : D->ctors()) {
5874         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5875           if (CD->isTrivial())
5876             CopyCtorIsTrivial = true;
5877           if (CD->isTrivialForCall())
5878             CopyCtorIsTrivialForCall = true;
5879         }
5880       }
5881     }
5882 
5883     if (D->needsImplicitDestructor()) {
5884       if (!D->defaultedDestructorIsDeleted() &&
5885           D->hasTrivialDestructorForCall())
5886         DtorIsTrivialForCall = true;
5887     } else if (const auto *DD = D->getDestructor()) {
5888       if (!DD->isDeleted() && DD->isTrivialForCall())
5889         DtorIsTrivialForCall = true;
5890     }
5891 
5892     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5893     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5894       return true;
5895 
5896     // If a class has a destructor, we'd really like to pass it indirectly
5897     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5898     // impossible for small types, which it will pass in a single register or
5899     // stack slot. Most objects with dtors are large-ish, so handle that early.
5900     // We can't call out all large objects as being indirect because there are
5901     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5902     // how we pass large POD types.
5903 
5904     // Note: This permits small classes with nontrivial destructors to be
5905     // passed in registers, which is non-conforming.
5906     if (CopyCtorIsTrivial &&
5907         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5908       return true;
5909     return false;
5910   }
5911 
5912   // Per C++ [class.temporary]p3, the relevant condition is:
5913   //   each copy constructor, move constructor, and destructor of X is
5914   //   either trivial or deleted, and X has at least one non-deleted copy
5915   //   or move constructor
5916   bool HasNonDeletedCopyOrMove = false;
5917 
5918   if (D->needsImplicitCopyConstructor() &&
5919       !D->defaultedCopyConstructorIsDeleted()) {
5920     if (!D->hasTrivialCopyConstructorForCall())
5921       return false;
5922     HasNonDeletedCopyOrMove = true;
5923   }
5924 
5925   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5926       !D->defaultedMoveConstructorIsDeleted()) {
5927     if (!D->hasTrivialMoveConstructorForCall())
5928       return false;
5929     HasNonDeletedCopyOrMove = true;
5930   }
5931 
5932   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5933       !D->hasTrivialDestructorForCall())
5934     return false;
5935 
5936   for (const CXXMethodDecl *MD : D->methods()) {
5937     if (MD->isDeleted())
5938       continue;
5939 
5940     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5941     if (CD && CD->isCopyOrMoveConstructor())
5942       HasNonDeletedCopyOrMove = true;
5943     else if (!isa<CXXDestructorDecl>(MD))
5944       continue;
5945 
5946     if (!MD->isTrivialForCall())
5947       return false;
5948   }
5949 
5950   return HasNonDeletedCopyOrMove;
5951 }
5952 
5953 /// Perform semantic checks on a class definition that has been
5954 /// completing, introducing implicitly-declared members, checking for
5955 /// abstract types, etc.
5956 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5957   if (!Record)
5958     return;
5959 
5960   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5961     AbstractUsageInfo Info(*this, Record);
5962     CheckAbstractClassUsage(Info, Record);
5963   }
5964 
5965   // If this is not an aggregate type and has no user-declared constructor,
5966   // complain about any non-static data members of reference or const scalar
5967   // type, since they will never get initializers.
5968   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5969       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5970       !Record->isLambda()) {
5971     bool Complained = false;
5972     for (const auto *F : Record->fields()) {
5973       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5974         continue;
5975 
5976       if (F->getType()->isReferenceType() ||
5977           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5978         if (!Complained) {
5979           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5980             << Record->getTagKind() << Record;
5981           Complained = true;
5982         }
5983 
5984         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5985           << F->getType()->isReferenceType()
5986           << F->getDeclName();
5987       }
5988     }
5989   }
5990 
5991   if (Record->getIdentifier()) {
5992     // C++ [class.mem]p13:
5993     //   If T is the name of a class, then each of the following shall have a
5994     //   name different from T:
5995     //     - every member of every anonymous union that is a member of class T.
5996     //
5997     // C++ [class.mem]p14:
5998     //   In addition, if class T has a user-declared constructor (12.1), every
5999     //   non-static data member of class T shall have a name different from T.
6000     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6001     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6002          ++I) {
6003       NamedDecl *D = (*I)->getUnderlyingDecl();
6004       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6005            Record->hasUserDeclaredConstructor()) ||
6006           isa<IndirectFieldDecl>(D)) {
6007         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6008           << D->getDeclName();
6009         break;
6010       }
6011     }
6012   }
6013 
6014   // Warn if the class has virtual methods but non-virtual public destructor.
6015   if (Record->isPolymorphic() && !Record->isDependentType()) {
6016     CXXDestructorDecl *dtor = Record->getDestructor();
6017     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6018         !Record->hasAttr<FinalAttr>())
6019       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6020            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6021   }
6022 
6023   if (Record->isAbstract()) {
6024     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6025       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6026         << FA->isSpelledAsSealed();
6027       DiagnoseAbstractType(Record);
6028     }
6029   }
6030 
6031   // See if trivial_abi has to be dropped.
6032   if (Record->hasAttr<TrivialABIAttr>())
6033     checkIllFormedTrivialABIStruct(*Record);
6034 
6035   // Set HasTrivialSpecialMemberForCall if the record has attribute
6036   // "trivial_abi".
6037   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6038 
6039   if (HasTrivialABI)
6040     Record->setHasTrivialSpecialMemberForCall();
6041 
6042   bool HasMethodWithOverrideControl = false,
6043        HasOverridingMethodWithoutOverrideControl = false;
6044   if (!Record->isDependentType()) {
6045     for (auto *M : Record->methods()) {
6046       // See if a method overloads virtual methods in a base
6047       // class without overriding any.
6048       if (!M->isStatic())
6049         DiagnoseHiddenVirtualMethods(M);
6050       if (M->hasAttr<OverrideAttr>())
6051         HasMethodWithOverrideControl = true;
6052       else if (M->size_overridden_methods() > 0)
6053         HasOverridingMethodWithoutOverrideControl = true;
6054       // Check whether the explicitly-defaulted special members are valid.
6055       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6056         CheckExplicitlyDefaultedSpecialMember(M);
6057 
6058       // For an explicitly defaulted or deleted special member, we defer
6059       // determining triviality until the class is complete. That time is now!
6060       CXXSpecialMember CSM = getSpecialMember(M);
6061       if (!M->isImplicit() && !M->isUserProvided()) {
6062         if (CSM != CXXInvalid) {
6063           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6064           // Inform the class that we've finished declaring this member.
6065           Record->finishedDefaultedOrDeletedMember(M);
6066           M->setTrivialForCall(
6067               HasTrivialABI ||
6068               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6069           Record->setTrivialForCallFlags(M);
6070         }
6071       }
6072 
6073       // Set triviality for the purpose of calls if this is a user-provided
6074       // copy/move constructor or destructor.
6075       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6076            CSM == CXXDestructor) && M->isUserProvided()) {
6077         M->setTrivialForCall(HasTrivialABI);
6078         Record->setTrivialForCallFlags(M);
6079       }
6080 
6081       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6082           M->hasAttr<DLLExportAttr>()) {
6083         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6084             M->isTrivial() &&
6085             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6086              CSM == CXXDestructor))
6087           M->dropAttr<DLLExportAttr>();
6088 
6089         if (M->hasAttr<DLLExportAttr>()) {
6090           DefineImplicitSpecialMember(*this, M, M->getLocation());
6091           ActOnFinishInlineFunctionDef(M);
6092         }
6093       }
6094     }
6095   }
6096 
6097   if (HasMethodWithOverrideControl &&
6098       HasOverridingMethodWithoutOverrideControl) {
6099     // At least one method has the 'override' control declared.
6100     // Diagnose all other overridden methods which do not have 'override' specified on them.
6101     for (auto *M : Record->methods())
6102       DiagnoseAbsenceOfOverrideControl(M);
6103   }
6104 
6105   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6106   // whether this class uses any C++ features that are implemented
6107   // completely differently in MSVC, and if so, emit a diagnostic.
6108   // That diagnostic defaults to an error, but we allow projects to
6109   // map it down to a warning (or ignore it).  It's a fairly common
6110   // practice among users of the ms_struct pragma to mass-annotate
6111   // headers, sweeping up a bunch of types that the project doesn't
6112   // really rely on MSVC-compatible layout for.  We must therefore
6113   // support "ms_struct except for C++ stuff" as a secondary ABI.
6114   if (Record->isMsStruct(Context) &&
6115       (Record->isPolymorphic() || Record->getNumBases())) {
6116     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6117   }
6118 
6119   checkClassLevelDLLAttribute(Record);
6120   checkClassLevelCodeSegAttribute(Record);
6121 
6122   bool ClangABICompat4 =
6123       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6124   TargetInfo::CallingConvKind CCK =
6125       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6126   bool CanPass = canPassInRegisters(*this, Record, CCK);
6127 
6128   // Do not change ArgPassingRestrictions if it has already been set to
6129   // APK_CanNeverPassInRegs.
6130   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6131     Record->setArgPassingRestrictions(CanPass
6132                                           ? RecordDecl::APK_CanPassInRegs
6133                                           : RecordDecl::APK_CannotPassInRegs);
6134 
6135   // If canPassInRegisters returns true despite the record having a non-trivial
6136   // destructor, the record is destructed in the callee. This happens only when
6137   // the record or one of its subobjects has a field annotated with trivial_abi
6138   // or a field qualified with ObjC __strong/__weak.
6139   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6140     Record->setParamDestroyedInCallee(true);
6141   else if (Record->hasNonTrivialDestructor())
6142     Record->setParamDestroyedInCallee(CanPass);
6143 
6144   if (getLangOpts().ForceEmitVTables) {
6145     // If we want to emit all the vtables, we need to mark it as used.  This
6146     // is especially required for cases like vtable assumption loads.
6147     MarkVTableUsed(Record->getInnerLocStart(), Record);
6148   }
6149 }
6150 
6151 /// Look up the special member function that would be called by a special
6152 /// member function for a subobject of class type.
6153 ///
6154 /// \param Class The class type of the subobject.
6155 /// \param CSM The kind of special member function.
6156 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6157 /// \param ConstRHS True if this is a copy operation with a const object
6158 ///        on its RHS, that is, if the argument to the outer special member
6159 ///        function is 'const' and this is not a field marked 'mutable'.
6160 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6161     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6162     unsigned FieldQuals, bool ConstRHS) {
6163   unsigned LHSQuals = 0;
6164   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6165     LHSQuals = FieldQuals;
6166 
6167   unsigned RHSQuals = FieldQuals;
6168   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6169     RHSQuals = 0;
6170   else if (ConstRHS)
6171     RHSQuals |= Qualifiers::Const;
6172 
6173   return S.LookupSpecialMember(Class, CSM,
6174                                RHSQuals & Qualifiers::Const,
6175                                RHSQuals & Qualifiers::Volatile,
6176                                false,
6177                                LHSQuals & Qualifiers::Const,
6178                                LHSQuals & Qualifiers::Volatile);
6179 }
6180 
6181 class Sema::InheritedConstructorInfo {
6182   Sema &S;
6183   SourceLocation UseLoc;
6184 
6185   /// A mapping from the base classes through which the constructor was
6186   /// inherited to the using shadow declaration in that base class (or a null
6187   /// pointer if the constructor was declared in that base class).
6188   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6189       InheritedFromBases;
6190 
6191 public:
6192   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6193                            ConstructorUsingShadowDecl *Shadow)
6194       : S(S), UseLoc(UseLoc) {
6195     bool DiagnosedMultipleConstructedBases = false;
6196     CXXRecordDecl *ConstructedBase = nullptr;
6197     UsingDecl *ConstructedBaseUsing = nullptr;
6198 
6199     // Find the set of such base class subobjects and check that there's a
6200     // unique constructed subobject.
6201     for (auto *D : Shadow->redecls()) {
6202       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6203       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6204       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6205 
6206       InheritedFromBases.insert(
6207           std::make_pair(DNominatedBase->getCanonicalDecl(),
6208                          DShadow->getNominatedBaseClassShadowDecl()));
6209       if (DShadow->constructsVirtualBase())
6210         InheritedFromBases.insert(
6211             std::make_pair(DConstructedBase->getCanonicalDecl(),
6212                            DShadow->getConstructedBaseClassShadowDecl()));
6213       else
6214         assert(DNominatedBase == DConstructedBase);
6215 
6216       // [class.inhctor.init]p2:
6217       //   If the constructor was inherited from multiple base class subobjects
6218       //   of type B, the program is ill-formed.
6219       if (!ConstructedBase) {
6220         ConstructedBase = DConstructedBase;
6221         ConstructedBaseUsing = D->getUsingDecl();
6222       } else if (ConstructedBase != DConstructedBase &&
6223                  !Shadow->isInvalidDecl()) {
6224         if (!DiagnosedMultipleConstructedBases) {
6225           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6226               << Shadow->getTargetDecl();
6227           S.Diag(ConstructedBaseUsing->getLocation(),
6228                diag::note_ambiguous_inherited_constructor_using)
6229               << ConstructedBase;
6230           DiagnosedMultipleConstructedBases = true;
6231         }
6232         S.Diag(D->getUsingDecl()->getLocation(),
6233                diag::note_ambiguous_inherited_constructor_using)
6234             << DConstructedBase;
6235       }
6236     }
6237 
6238     if (DiagnosedMultipleConstructedBases)
6239       Shadow->setInvalidDecl();
6240   }
6241 
6242   /// Find the constructor to use for inherited construction of a base class,
6243   /// and whether that base class constructor inherits the constructor from a
6244   /// virtual base class (in which case it won't actually invoke it).
6245   std::pair<CXXConstructorDecl *, bool>
6246   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6247     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6248     if (It == InheritedFromBases.end())
6249       return std::make_pair(nullptr, false);
6250 
6251     // This is an intermediary class.
6252     if (It->second)
6253       return std::make_pair(
6254           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6255           It->second->constructsVirtualBase());
6256 
6257     // This is the base class from which the constructor was inherited.
6258     return std::make_pair(Ctor, false);
6259   }
6260 };
6261 
6262 /// Is the special member function which would be selected to perform the
6263 /// specified operation on the specified class type a constexpr constructor?
6264 static bool
6265 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6266                          Sema::CXXSpecialMember CSM, unsigned Quals,
6267                          bool ConstRHS,
6268                          CXXConstructorDecl *InheritedCtor = nullptr,
6269                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6270   // If we're inheriting a constructor, see if we need to call it for this base
6271   // class.
6272   if (InheritedCtor) {
6273     assert(CSM == Sema::CXXDefaultConstructor);
6274     auto BaseCtor =
6275         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6276     if (BaseCtor)
6277       return BaseCtor->isConstexpr();
6278   }
6279 
6280   if (CSM == Sema::CXXDefaultConstructor)
6281     return ClassDecl->hasConstexprDefaultConstructor();
6282 
6283   Sema::SpecialMemberOverloadResult SMOR =
6284       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6285   if (!SMOR.getMethod())
6286     // A constructor we wouldn't select can't be "involved in initializing"
6287     // anything.
6288     return true;
6289   return SMOR.getMethod()->isConstexpr();
6290 }
6291 
6292 /// Determine whether the specified special member function would be constexpr
6293 /// if it were implicitly defined.
6294 static bool defaultedSpecialMemberIsConstexpr(
6295     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6296     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6297     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6298   if (!S.getLangOpts().CPlusPlus11)
6299     return false;
6300 
6301   // C++11 [dcl.constexpr]p4:
6302   // In the definition of a constexpr constructor [...]
6303   bool Ctor = true;
6304   switch (CSM) {
6305   case Sema::CXXDefaultConstructor:
6306     if (Inherited)
6307       break;
6308     // Since default constructor lookup is essentially trivial (and cannot
6309     // involve, for instance, template instantiation), we compute whether a
6310     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6311     //
6312     // This is important for performance; we need to know whether the default
6313     // constructor is constexpr to determine whether the type is a literal type.
6314     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6315 
6316   case Sema::CXXCopyConstructor:
6317   case Sema::CXXMoveConstructor:
6318     // For copy or move constructors, we need to perform overload resolution.
6319     break;
6320 
6321   case Sema::CXXCopyAssignment:
6322   case Sema::CXXMoveAssignment:
6323     if (!S.getLangOpts().CPlusPlus14)
6324       return false;
6325     // In C++1y, we need to perform overload resolution.
6326     Ctor = false;
6327     break;
6328 
6329   case Sema::CXXDestructor:
6330   case Sema::CXXInvalid:
6331     return false;
6332   }
6333 
6334   //   -- if the class is a non-empty union, or for each non-empty anonymous
6335   //      union member of a non-union class, exactly one non-static data member
6336   //      shall be initialized; [DR1359]
6337   //
6338   // If we squint, this is guaranteed, since exactly one non-static data member
6339   // will be initialized (if the constructor isn't deleted), we just don't know
6340   // which one.
6341   if (Ctor && ClassDecl->isUnion())
6342     return CSM == Sema::CXXDefaultConstructor
6343                ? ClassDecl->hasInClassInitializer() ||
6344                      !ClassDecl->hasVariantMembers()
6345                : true;
6346 
6347   //   -- the class shall not have any virtual base classes;
6348   if (Ctor && ClassDecl->getNumVBases())
6349     return false;
6350 
6351   // C++1y [class.copy]p26:
6352   //   -- [the class] is a literal type, and
6353   if (!Ctor && !ClassDecl->isLiteral())
6354     return false;
6355 
6356   //   -- every constructor involved in initializing [...] base class
6357   //      sub-objects shall be a constexpr constructor;
6358   //   -- the assignment operator selected to copy/move each direct base
6359   //      class is a constexpr function, and
6360   for (const auto &B : ClassDecl->bases()) {
6361     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6362     if (!BaseType) continue;
6363 
6364     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6365     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6366                                   InheritedCtor, Inherited))
6367       return false;
6368   }
6369 
6370   //   -- every constructor involved in initializing non-static data members
6371   //      [...] shall be a constexpr constructor;
6372   //   -- every non-static data member and base class sub-object shall be
6373   //      initialized
6374   //   -- for each non-static data member of X that is of class type (or array
6375   //      thereof), the assignment operator selected to copy/move that member is
6376   //      a constexpr function
6377   for (const auto *F : ClassDecl->fields()) {
6378     if (F->isInvalidDecl())
6379       continue;
6380     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6381       continue;
6382     QualType BaseType = S.Context.getBaseElementType(F->getType());
6383     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6384       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6385       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6386                                     BaseType.getCVRQualifiers(),
6387                                     ConstArg && !F->isMutable()))
6388         return false;
6389     } else if (CSM == Sema::CXXDefaultConstructor) {
6390       return false;
6391     }
6392   }
6393 
6394   // All OK, it's constexpr!
6395   return true;
6396 }
6397 
6398 static Sema::ImplicitExceptionSpecification
6399 ComputeDefaultedSpecialMemberExceptionSpec(
6400     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6401     Sema::InheritedConstructorInfo *ICI);
6402 
6403 static Sema::ImplicitExceptionSpecification
6404 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6405   auto CSM = S.getSpecialMember(MD);
6406   if (CSM != Sema::CXXInvalid)
6407     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6408 
6409   auto *CD = cast<CXXConstructorDecl>(MD);
6410   assert(CD->getInheritedConstructor() &&
6411          "only special members have implicit exception specs");
6412   Sema::InheritedConstructorInfo ICI(
6413       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6414   return ComputeDefaultedSpecialMemberExceptionSpec(
6415       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6416 }
6417 
6418 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6419                                                             CXXMethodDecl *MD) {
6420   FunctionProtoType::ExtProtoInfo EPI;
6421 
6422   // Build an exception specification pointing back at this member.
6423   EPI.ExceptionSpec.Type = EST_Unevaluated;
6424   EPI.ExceptionSpec.SourceDecl = MD;
6425 
6426   // Set the calling convention to the default for C++ instance methods.
6427   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6428       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6429                                             /*IsCXXMethod=*/true));
6430   return EPI;
6431 }
6432 
6433 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6434   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6435   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6436     return;
6437 
6438   // Evaluate the exception specification.
6439   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6440   auto ESI = IES.getExceptionSpec();
6441 
6442   // Update the type of the special member to use it.
6443   UpdateExceptionSpec(MD, ESI);
6444 
6445   // A user-provided destructor can be defined outside the class. When that
6446   // happens, be sure to update the exception specification on both
6447   // declarations.
6448   const FunctionProtoType *CanonicalFPT =
6449     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6450   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6451     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6452 }
6453 
6454 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6455   CXXRecordDecl *RD = MD->getParent();
6456   CXXSpecialMember CSM = getSpecialMember(MD);
6457 
6458   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6459          "not an explicitly-defaulted special member");
6460 
6461   // Whether this was the first-declared instance of the constructor.
6462   // This affects whether we implicitly add an exception spec and constexpr.
6463   bool First = MD == MD->getCanonicalDecl();
6464 
6465   bool HadError = false;
6466 
6467   // C++11 [dcl.fct.def.default]p1:
6468   //   A function that is explicitly defaulted shall
6469   //     -- be a special member function (checked elsewhere),
6470   //     -- have the same type (except for ref-qualifiers, and except that a
6471   //        copy operation can take a non-const reference) as an implicit
6472   //        declaration, and
6473   //     -- not have default arguments.
6474   // C++2a changes the second bullet to instead delete the function if it's
6475   // defaulted on its first declaration, unless it's "an assignment operator,
6476   // and its return type differs or its parameter type is not a reference".
6477   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6478   bool ShouldDeleteForTypeMismatch = false;
6479   unsigned ExpectedParams = 1;
6480   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6481     ExpectedParams = 0;
6482   if (MD->getNumParams() != ExpectedParams) {
6483     // This checks for default arguments: a copy or move constructor with a
6484     // default argument is classified as a default constructor, and assignment
6485     // operations and destructors can't have default arguments.
6486     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6487       << CSM << MD->getSourceRange();
6488     HadError = true;
6489   } else if (MD->isVariadic()) {
6490     if (DeleteOnTypeMismatch)
6491       ShouldDeleteForTypeMismatch = true;
6492     else {
6493       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6494         << CSM << MD->getSourceRange();
6495       HadError = true;
6496     }
6497   }
6498 
6499   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6500 
6501   bool CanHaveConstParam = false;
6502   if (CSM == CXXCopyConstructor)
6503     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6504   else if (CSM == CXXCopyAssignment)
6505     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6506 
6507   QualType ReturnType = Context.VoidTy;
6508   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6509     // Check for return type matching.
6510     ReturnType = Type->getReturnType();
6511     QualType ExpectedReturnType =
6512         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6513     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6514       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6515         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6516       HadError = true;
6517     }
6518 
6519     // A defaulted special member cannot have cv-qualifiers.
6520     if (Type->getTypeQuals()) {
6521       if (DeleteOnTypeMismatch)
6522         ShouldDeleteForTypeMismatch = true;
6523       else {
6524         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6525           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6526         HadError = true;
6527       }
6528     }
6529   }
6530 
6531   // Check for parameter type matching.
6532   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6533   bool HasConstParam = false;
6534   if (ExpectedParams && ArgType->isReferenceType()) {
6535     // Argument must be reference to possibly-const T.
6536     QualType ReferentType = ArgType->getPointeeType();
6537     HasConstParam = ReferentType.isConstQualified();
6538 
6539     if (ReferentType.isVolatileQualified()) {
6540       if (DeleteOnTypeMismatch)
6541         ShouldDeleteForTypeMismatch = true;
6542       else {
6543         Diag(MD->getLocation(),
6544              diag::err_defaulted_special_member_volatile_param) << CSM;
6545         HadError = true;
6546       }
6547     }
6548 
6549     if (HasConstParam && !CanHaveConstParam) {
6550       if (DeleteOnTypeMismatch)
6551         ShouldDeleteForTypeMismatch = true;
6552       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6553         Diag(MD->getLocation(),
6554              diag::err_defaulted_special_member_copy_const_param)
6555           << (CSM == CXXCopyAssignment);
6556         // FIXME: Explain why this special member can't be const.
6557         HadError = true;
6558       } else {
6559         Diag(MD->getLocation(),
6560              diag::err_defaulted_special_member_move_const_param)
6561           << (CSM == CXXMoveAssignment);
6562         HadError = true;
6563       }
6564     }
6565   } else if (ExpectedParams) {
6566     // A copy assignment operator can take its argument by value, but a
6567     // defaulted one cannot.
6568     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6569     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6570     HadError = true;
6571   }
6572 
6573   // C++11 [dcl.fct.def.default]p2:
6574   //   An explicitly-defaulted function may be declared constexpr only if it
6575   //   would have been implicitly declared as constexpr,
6576   // Do not apply this rule to members of class templates, since core issue 1358
6577   // makes such functions always instantiate to constexpr functions. For
6578   // functions which cannot be constexpr (for non-constructors in C++11 and for
6579   // destructors in C++1y), this is checked elsewhere.
6580   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6581                                                      HasConstParam);
6582   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6583                                  : isa<CXXConstructorDecl>(MD)) &&
6584       MD->isConstexpr() && !Constexpr &&
6585       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6586     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6587     // FIXME: Explain why the special member can't be constexpr.
6588     HadError = true;
6589   }
6590 
6591   //   and may have an explicit exception-specification only if it is compatible
6592   //   with the exception-specification on the implicit declaration.
6593   if (Type->hasExceptionSpec()) {
6594     // Delay the check if this is the first declaration of the special member,
6595     // since we may not have parsed some necessary in-class initializers yet.
6596     if (First) {
6597       // If the exception specification needs to be instantiated, do so now,
6598       // before we clobber it with an EST_Unevaluated specification below.
6599       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6600         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6601         Type = MD->getType()->getAs<FunctionProtoType>();
6602       }
6603       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6604     } else
6605       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6606   }
6607 
6608   //   If a function is explicitly defaulted on its first declaration,
6609   if (First) {
6610     //  -- it is implicitly considered to be constexpr if the implicit
6611     //     definition would be,
6612     MD->setConstexpr(Constexpr);
6613 
6614     //  -- it is implicitly considered to have the same exception-specification
6615     //     as if it had been implicitly declared,
6616     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6617     EPI.ExceptionSpec.Type = EST_Unevaluated;
6618     EPI.ExceptionSpec.SourceDecl = MD;
6619     MD->setType(Context.getFunctionType(ReturnType,
6620                                         llvm::makeArrayRef(&ArgType,
6621                                                            ExpectedParams),
6622                                         EPI));
6623   }
6624 
6625   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6626     if (First) {
6627       SetDeclDeleted(MD, MD->getLocation());
6628       if (!inTemplateInstantiation() && !HadError) {
6629         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6630         if (ShouldDeleteForTypeMismatch) {
6631           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6632         } else {
6633           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6634         }
6635       }
6636       if (ShouldDeleteForTypeMismatch && !HadError) {
6637         Diag(MD->getLocation(),
6638              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6639       }
6640     } else {
6641       // C++11 [dcl.fct.def.default]p4:
6642       //   [For a] user-provided explicitly-defaulted function [...] if such a
6643       //   function is implicitly defined as deleted, the program is ill-formed.
6644       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6645       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6646       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6647       HadError = true;
6648     }
6649   }
6650 
6651   if (HadError)
6652     MD->setInvalidDecl();
6653 }
6654 
6655 /// Check whether the exception specification provided for an
6656 /// explicitly-defaulted special member matches the exception specification
6657 /// that would have been generated for an implicit special member, per
6658 /// C++11 [dcl.fct.def.default]p2.
6659 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6660     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6661   // If the exception specification was explicitly specified but hadn't been
6662   // parsed when the method was defaulted, grab it now.
6663   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6664     SpecifiedType =
6665         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6666 
6667   // Compute the implicit exception specification.
6668   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6669                                                        /*IsCXXMethod=*/true);
6670   FunctionProtoType::ExtProtoInfo EPI(CC);
6671   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6672   EPI.ExceptionSpec = IES.getExceptionSpec();
6673   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6674     Context.getFunctionType(Context.VoidTy, None, EPI));
6675 
6676   // Ensure that it matches.
6677   CheckEquivalentExceptionSpec(
6678     PDiag(diag::err_incorrect_defaulted_exception_spec)
6679       << getSpecialMember(MD), PDiag(),
6680     ImplicitType, SourceLocation(),
6681     SpecifiedType, MD->getLocation());
6682 }
6683 
6684 void Sema::CheckDelayedMemberExceptionSpecs() {
6685   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6686   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6687   decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6688 
6689   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6690   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6691   std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6692 
6693   // Perform any deferred checking of exception specifications for virtual
6694   // destructors.
6695   for (auto &Check : Overriding)
6696     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6697 
6698   // Perform any deferred checking of exception specifications for befriended
6699   // special members.
6700   for (auto &Check : Equivalent)
6701     CheckEquivalentExceptionSpec(Check.second, Check.first);
6702 
6703   // Check that any explicitly-defaulted methods have exception specifications
6704   // compatible with their implicit exception specifications.
6705   for (auto &Spec : Defaulted)
6706     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6707 }
6708 
6709 namespace {
6710 /// CRTP base class for visiting operations performed by a special member
6711 /// function (or inherited constructor).
6712 template<typename Derived>
6713 struct SpecialMemberVisitor {
6714   Sema &S;
6715   CXXMethodDecl *MD;
6716   Sema::CXXSpecialMember CSM;
6717   Sema::InheritedConstructorInfo *ICI;
6718 
6719   // Properties of the special member, computed for convenience.
6720   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6721 
6722   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6723                        Sema::InheritedConstructorInfo *ICI)
6724       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6725     switch (CSM) {
6726     case Sema::CXXDefaultConstructor:
6727     case Sema::CXXCopyConstructor:
6728     case Sema::CXXMoveConstructor:
6729       IsConstructor = true;
6730       break;
6731     case Sema::CXXCopyAssignment:
6732     case Sema::CXXMoveAssignment:
6733       IsAssignment = true;
6734       break;
6735     case Sema::CXXDestructor:
6736       break;
6737     case Sema::CXXInvalid:
6738       llvm_unreachable("invalid special member kind");
6739     }
6740 
6741     if (MD->getNumParams()) {
6742       if (const ReferenceType *RT =
6743               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6744         ConstArg = RT->getPointeeType().isConstQualified();
6745     }
6746   }
6747 
6748   Derived &getDerived() { return static_cast<Derived&>(*this); }
6749 
6750   /// Is this a "move" special member?
6751   bool isMove() const {
6752     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6753   }
6754 
6755   /// Look up the corresponding special member in the given class.
6756   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6757                                              unsigned Quals, bool IsMutable) {
6758     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6759                                        ConstArg && !IsMutable);
6760   }
6761 
6762   /// Look up the constructor for the specified base class to see if it's
6763   /// overridden due to this being an inherited constructor.
6764   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6765     if (!ICI)
6766       return {};
6767     assert(CSM == Sema::CXXDefaultConstructor);
6768     auto *BaseCtor =
6769       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6770     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6771       return MD;
6772     return {};
6773   }
6774 
6775   /// A base or member subobject.
6776   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6777 
6778   /// Get the location to use for a subobject in diagnostics.
6779   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6780     // FIXME: For an indirect virtual base, the direct base leading to
6781     // the indirect virtual base would be a more useful choice.
6782     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6783       return B->getBaseTypeLoc();
6784     else
6785       return Subobj.get<FieldDecl*>()->getLocation();
6786   }
6787 
6788   enum BasesToVisit {
6789     /// Visit all non-virtual (direct) bases.
6790     VisitNonVirtualBases,
6791     /// Visit all direct bases, virtual or not.
6792     VisitDirectBases,
6793     /// Visit all non-virtual bases, and all virtual bases if the class
6794     /// is not abstract.
6795     VisitPotentiallyConstructedBases,
6796     /// Visit all direct or virtual bases.
6797     VisitAllBases
6798   };
6799 
6800   // Visit the bases and members of the class.
6801   bool visit(BasesToVisit Bases) {
6802     CXXRecordDecl *RD = MD->getParent();
6803 
6804     if (Bases == VisitPotentiallyConstructedBases)
6805       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6806 
6807     for (auto &B : RD->bases())
6808       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6809           getDerived().visitBase(&B))
6810         return true;
6811 
6812     if (Bases == VisitAllBases)
6813       for (auto &B : RD->vbases())
6814         if (getDerived().visitBase(&B))
6815           return true;
6816 
6817     for (auto *F : RD->fields())
6818       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6819           getDerived().visitField(F))
6820         return true;
6821 
6822     return false;
6823   }
6824 };
6825 }
6826 
6827 namespace {
6828 struct SpecialMemberDeletionInfo
6829     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6830   bool Diagnose;
6831 
6832   SourceLocation Loc;
6833 
6834   bool AllFieldsAreConst;
6835 
6836   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6837                             Sema::CXXSpecialMember CSM,
6838                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6839       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6840         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6841 
6842   bool inUnion() const { return MD->getParent()->isUnion(); }
6843 
6844   Sema::CXXSpecialMember getEffectiveCSM() {
6845     return ICI ? Sema::CXXInvalid : CSM;
6846   }
6847 
6848   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6849   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6850 
6851   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6852   bool shouldDeleteForField(FieldDecl *FD);
6853   bool shouldDeleteForAllConstMembers();
6854 
6855   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6856                                      unsigned Quals);
6857   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6858                                     Sema::SpecialMemberOverloadResult SMOR,
6859                                     bool IsDtorCallInCtor);
6860 
6861   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6862 };
6863 }
6864 
6865 /// Is the given special member inaccessible when used on the given
6866 /// sub-object.
6867 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6868                                              CXXMethodDecl *target) {
6869   /// If we're operating on a base class, the object type is the
6870   /// type of this special member.
6871   QualType objectTy;
6872   AccessSpecifier access = target->getAccess();
6873   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6874     objectTy = S.Context.getTypeDeclType(MD->getParent());
6875     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6876 
6877   // If we're operating on a field, the object type is the type of the field.
6878   } else {
6879     objectTy = S.Context.getTypeDeclType(target->getParent());
6880   }
6881 
6882   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6883 }
6884 
6885 /// Check whether we should delete a special member due to the implicit
6886 /// definition containing a call to a special member of a subobject.
6887 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6888     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6889     bool IsDtorCallInCtor) {
6890   CXXMethodDecl *Decl = SMOR.getMethod();
6891   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6892 
6893   int DiagKind = -1;
6894 
6895   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6896     DiagKind = !Decl ? 0 : 1;
6897   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6898     DiagKind = 2;
6899   else if (!isAccessible(Subobj, Decl))
6900     DiagKind = 3;
6901   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6902            !Decl->isTrivial()) {
6903     // A member of a union must have a trivial corresponding special member.
6904     // As a weird special case, a destructor call from a union's constructor
6905     // must be accessible and non-deleted, but need not be trivial. Such a
6906     // destructor is never actually called, but is semantically checked as
6907     // if it were.
6908     DiagKind = 4;
6909   }
6910 
6911   if (DiagKind == -1)
6912     return false;
6913 
6914   if (Diagnose) {
6915     if (Field) {
6916       S.Diag(Field->getLocation(),
6917              diag::note_deleted_special_member_class_subobject)
6918         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6919         << Field << DiagKind << IsDtorCallInCtor;
6920     } else {
6921       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6922       S.Diag(Base->getBeginLoc(),
6923              diag::note_deleted_special_member_class_subobject)
6924           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6925           << Base->getType() << DiagKind << IsDtorCallInCtor;
6926     }
6927 
6928     if (DiagKind == 1)
6929       S.NoteDeletedFunction(Decl);
6930     // FIXME: Explain inaccessibility if DiagKind == 3.
6931   }
6932 
6933   return true;
6934 }
6935 
6936 /// Check whether we should delete a special member function due to having a
6937 /// direct or virtual base class or non-static data member of class type M.
6938 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6939     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6940   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6941   bool IsMutable = Field && Field->isMutable();
6942 
6943   // C++11 [class.ctor]p5:
6944   // -- any direct or virtual base class, or non-static data member with no
6945   //    brace-or-equal-initializer, has class type M (or array thereof) and
6946   //    either M has no default constructor or overload resolution as applied
6947   //    to M's default constructor results in an ambiguity or in a function
6948   //    that is deleted or inaccessible
6949   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6950   // -- a direct or virtual base class B that cannot be copied/moved because
6951   //    overload resolution, as applied to B's corresponding special member,
6952   //    results in an ambiguity or a function that is deleted or inaccessible
6953   //    from the defaulted special member
6954   // C++11 [class.dtor]p5:
6955   // -- any direct or virtual base class [...] has a type with a destructor
6956   //    that is deleted or inaccessible
6957   if (!(CSM == Sema::CXXDefaultConstructor &&
6958         Field && Field->hasInClassInitializer()) &&
6959       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6960                                    false))
6961     return true;
6962 
6963   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6964   // -- any direct or virtual base class or non-static data member has a
6965   //    type with a destructor that is deleted or inaccessible
6966   if (IsConstructor) {
6967     Sema::SpecialMemberOverloadResult SMOR =
6968         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6969                               false, false, false, false, false);
6970     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6971       return true;
6972   }
6973 
6974   return false;
6975 }
6976 
6977 /// Check whether we should delete a special member function due to the class
6978 /// having a particular direct or virtual base class.
6979 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6980   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6981   // If program is correct, BaseClass cannot be null, but if it is, the error
6982   // must be reported elsewhere.
6983   if (!BaseClass)
6984     return false;
6985   // If we have an inheriting constructor, check whether we're calling an
6986   // inherited constructor instead of a default constructor.
6987   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6988   if (auto *BaseCtor = SMOR.getMethod()) {
6989     // Note that we do not check access along this path; other than that,
6990     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6991     // FIXME: Check that the base has a usable destructor! Sink this into
6992     // shouldDeleteForClassSubobject.
6993     if (BaseCtor->isDeleted() && Diagnose) {
6994       S.Diag(Base->getBeginLoc(),
6995              diag::note_deleted_special_member_class_subobject)
6996           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6997           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
6998       S.NoteDeletedFunction(BaseCtor);
6999     }
7000     return BaseCtor->isDeleted();
7001   }
7002   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7003 }
7004 
7005 /// Check whether we should delete a special member function due to the class
7006 /// having a particular non-static data member.
7007 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7008   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7009   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7010 
7011   if (CSM == Sema::CXXDefaultConstructor) {
7012     // For a default constructor, all references must be initialized in-class
7013     // and, if a union, it must have a non-const member.
7014     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7015       if (Diagnose)
7016         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7017           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7018       return true;
7019     }
7020     // C++11 [class.ctor]p5: any non-variant non-static data member of
7021     // const-qualified type (or array thereof) with no
7022     // brace-or-equal-initializer does not have a user-provided default
7023     // constructor.
7024     if (!inUnion() && FieldType.isConstQualified() &&
7025         !FD->hasInClassInitializer() &&
7026         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7027       if (Diagnose)
7028         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7029           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7030       return true;
7031     }
7032 
7033     if (inUnion() && !FieldType.isConstQualified())
7034       AllFieldsAreConst = false;
7035   } else if (CSM == Sema::CXXCopyConstructor) {
7036     // For a copy constructor, data members must not be of rvalue reference
7037     // type.
7038     if (FieldType->isRValueReferenceType()) {
7039       if (Diagnose)
7040         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7041           << MD->getParent() << FD << FieldType;
7042       return true;
7043     }
7044   } else if (IsAssignment) {
7045     // For an assignment operator, data members must not be of reference type.
7046     if (FieldType->isReferenceType()) {
7047       if (Diagnose)
7048         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7049           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7050       return true;
7051     }
7052     if (!FieldRecord && FieldType.isConstQualified()) {
7053       // C++11 [class.copy]p23:
7054       // -- a non-static data member of const non-class type (or array thereof)
7055       if (Diagnose)
7056         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7057           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7058       return true;
7059     }
7060   }
7061 
7062   if (FieldRecord) {
7063     // Some additional restrictions exist on the variant members.
7064     if (!inUnion() && FieldRecord->isUnion() &&
7065         FieldRecord->isAnonymousStructOrUnion()) {
7066       bool AllVariantFieldsAreConst = true;
7067 
7068       // FIXME: Handle anonymous unions declared within anonymous unions.
7069       for (auto *UI : FieldRecord->fields()) {
7070         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7071 
7072         if (!UnionFieldType.isConstQualified())
7073           AllVariantFieldsAreConst = false;
7074 
7075         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7076         if (UnionFieldRecord &&
7077             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7078                                           UnionFieldType.getCVRQualifiers()))
7079           return true;
7080       }
7081 
7082       // At least one member in each anonymous union must be non-const
7083       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7084           !FieldRecord->field_empty()) {
7085         if (Diagnose)
7086           S.Diag(FieldRecord->getLocation(),
7087                  diag::note_deleted_default_ctor_all_const)
7088             << !!ICI << MD->getParent() << /*anonymous union*/1;
7089         return true;
7090       }
7091 
7092       // Don't check the implicit member of the anonymous union type.
7093       // This is technically non-conformant, but sanity demands it.
7094       return false;
7095     }
7096 
7097     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7098                                       FieldType.getCVRQualifiers()))
7099       return true;
7100   }
7101 
7102   return false;
7103 }
7104 
7105 /// C++11 [class.ctor] p5:
7106 ///   A defaulted default constructor for a class X is defined as deleted if
7107 /// X is a union and all of its variant members are of const-qualified type.
7108 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7109   // This is a silly definition, because it gives an empty union a deleted
7110   // default constructor. Don't do that.
7111   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7112     bool AnyFields = false;
7113     for (auto *F : MD->getParent()->fields())
7114       if ((AnyFields = !F->isUnnamedBitfield()))
7115         break;
7116     if (!AnyFields)
7117       return false;
7118     if (Diagnose)
7119       S.Diag(MD->getParent()->getLocation(),
7120              diag::note_deleted_default_ctor_all_const)
7121         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7122     return true;
7123   }
7124   return false;
7125 }
7126 
7127 /// Determine whether a defaulted special member function should be defined as
7128 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7129 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7130 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7131                                      InheritedConstructorInfo *ICI,
7132                                      bool Diagnose) {
7133   if (MD->isInvalidDecl())
7134     return false;
7135   CXXRecordDecl *RD = MD->getParent();
7136   assert(!RD->isDependentType() && "do deletion after instantiation");
7137   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7138     return false;
7139 
7140   // C++11 [expr.lambda.prim]p19:
7141   //   The closure type associated with a lambda-expression has a
7142   //   deleted (8.4.3) default constructor and a deleted copy
7143   //   assignment operator.
7144   // C++2a adds back these operators if the lambda has no capture-default.
7145   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7146       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7147     if (Diagnose)
7148       Diag(RD->getLocation(), diag::note_lambda_decl);
7149     return true;
7150   }
7151 
7152   // For an anonymous struct or union, the copy and assignment special members
7153   // will never be used, so skip the check. For an anonymous union declared at
7154   // namespace scope, the constructor and destructor are used.
7155   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7156       RD->isAnonymousStructOrUnion())
7157     return false;
7158 
7159   // C++11 [class.copy]p7, p18:
7160   //   If the class definition declares a move constructor or move assignment
7161   //   operator, an implicitly declared copy constructor or copy assignment
7162   //   operator is defined as deleted.
7163   if (MD->isImplicit() &&
7164       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7165     CXXMethodDecl *UserDeclaredMove = nullptr;
7166 
7167     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7168     // deletion of the corresponding copy operation, not both copy operations.
7169     // MSVC 2015 has adopted the standards conforming behavior.
7170     bool DeletesOnlyMatchingCopy =
7171         getLangOpts().MSVCCompat &&
7172         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7173 
7174     if (RD->hasUserDeclaredMoveConstructor() &&
7175         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7176       if (!Diagnose) return true;
7177 
7178       // Find any user-declared move constructor.
7179       for (auto *I : RD->ctors()) {
7180         if (I->isMoveConstructor()) {
7181           UserDeclaredMove = I;
7182           break;
7183         }
7184       }
7185       assert(UserDeclaredMove);
7186     } else if (RD->hasUserDeclaredMoveAssignment() &&
7187                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7188       if (!Diagnose) return true;
7189 
7190       // Find any user-declared move assignment operator.
7191       for (auto *I : RD->methods()) {
7192         if (I->isMoveAssignmentOperator()) {
7193           UserDeclaredMove = I;
7194           break;
7195         }
7196       }
7197       assert(UserDeclaredMove);
7198     }
7199 
7200     if (UserDeclaredMove) {
7201       Diag(UserDeclaredMove->getLocation(),
7202            diag::note_deleted_copy_user_declared_move)
7203         << (CSM == CXXCopyAssignment) << RD
7204         << UserDeclaredMove->isMoveAssignmentOperator();
7205       return true;
7206     }
7207   }
7208 
7209   // Do access control from the special member function
7210   ContextRAII MethodContext(*this, MD);
7211 
7212   // C++11 [class.dtor]p5:
7213   // -- for a virtual destructor, lookup of the non-array deallocation function
7214   //    results in an ambiguity or in a function that is deleted or inaccessible
7215   if (CSM == CXXDestructor && MD->isVirtual()) {
7216     FunctionDecl *OperatorDelete = nullptr;
7217     DeclarationName Name =
7218       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7219     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7220                                  OperatorDelete, /*Diagnose*/false)) {
7221       if (Diagnose)
7222         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7223       return true;
7224     }
7225   }
7226 
7227   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7228 
7229   // Per DR1611, do not consider virtual bases of constructors of abstract
7230   // classes, since we are not going to construct them.
7231   // Per DR1658, do not consider virtual bases of destructors of abstract
7232   // classes either.
7233   // Per DR2180, for assignment operators we only assign (and thus only
7234   // consider) direct bases.
7235   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7236                                  : SMI.VisitPotentiallyConstructedBases))
7237     return true;
7238 
7239   if (SMI.shouldDeleteForAllConstMembers())
7240     return true;
7241 
7242   if (getLangOpts().CUDA) {
7243     // We should delete the special member in CUDA mode if target inference
7244     // failed.
7245     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7246     // is treated as certain special member, which may not reflect what special
7247     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7248     // expects CSM to match MD, therefore recalculate CSM.
7249     assert(ICI || CSM == getSpecialMember(MD));
7250     auto RealCSM = CSM;
7251     if (ICI)
7252       RealCSM = getSpecialMember(MD);
7253 
7254     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7255                                                    SMI.ConstArg, Diagnose);
7256   }
7257 
7258   return false;
7259 }
7260 
7261 /// Perform lookup for a special member of the specified kind, and determine
7262 /// whether it is trivial. If the triviality can be determined without the
7263 /// lookup, skip it. This is intended for use when determining whether a
7264 /// special member of a containing object is trivial, and thus does not ever
7265 /// perform overload resolution for default constructors.
7266 ///
7267 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7268 /// member that was most likely to be intended to be trivial, if any.
7269 ///
7270 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7271 /// determine whether the special member is trivial.
7272 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7273                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7274                                      bool ConstRHS,
7275                                      Sema::TrivialABIHandling TAH,
7276                                      CXXMethodDecl **Selected) {
7277   if (Selected)
7278     *Selected = nullptr;
7279 
7280   switch (CSM) {
7281   case Sema::CXXInvalid:
7282     llvm_unreachable("not a special member");
7283 
7284   case Sema::CXXDefaultConstructor:
7285     // C++11 [class.ctor]p5:
7286     //   A default constructor is trivial if:
7287     //    - all the [direct subobjects] have trivial default constructors
7288     //
7289     // Note, no overload resolution is performed in this case.
7290     if (RD->hasTrivialDefaultConstructor())
7291       return true;
7292 
7293     if (Selected) {
7294       // If there's a default constructor which could have been trivial, dig it
7295       // out. Otherwise, if there's any user-provided default constructor, point
7296       // to that as an example of why there's not a trivial one.
7297       CXXConstructorDecl *DefCtor = nullptr;
7298       if (RD->needsImplicitDefaultConstructor())
7299         S.DeclareImplicitDefaultConstructor(RD);
7300       for (auto *CI : RD->ctors()) {
7301         if (!CI->isDefaultConstructor())
7302           continue;
7303         DefCtor = CI;
7304         if (!DefCtor->isUserProvided())
7305           break;
7306       }
7307 
7308       *Selected = DefCtor;
7309     }
7310 
7311     return false;
7312 
7313   case Sema::CXXDestructor:
7314     // C++11 [class.dtor]p5:
7315     //   A destructor is trivial if:
7316     //    - all the direct [subobjects] have trivial destructors
7317     if (RD->hasTrivialDestructor() ||
7318         (TAH == Sema::TAH_ConsiderTrivialABI &&
7319          RD->hasTrivialDestructorForCall()))
7320       return true;
7321 
7322     if (Selected) {
7323       if (RD->needsImplicitDestructor())
7324         S.DeclareImplicitDestructor(RD);
7325       *Selected = RD->getDestructor();
7326     }
7327 
7328     return false;
7329 
7330   case Sema::CXXCopyConstructor:
7331     // C++11 [class.copy]p12:
7332     //   A copy constructor is trivial if:
7333     //    - the constructor selected to copy each direct [subobject] is trivial
7334     if (RD->hasTrivialCopyConstructor() ||
7335         (TAH == Sema::TAH_ConsiderTrivialABI &&
7336          RD->hasTrivialCopyConstructorForCall())) {
7337       if (Quals == Qualifiers::Const)
7338         // We must either select the trivial copy constructor or reach an
7339         // ambiguity; no need to actually perform overload resolution.
7340         return true;
7341     } else if (!Selected) {
7342       return false;
7343     }
7344     // In C++98, we are not supposed to perform overload resolution here, but we
7345     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7346     // cases like B as having a non-trivial copy constructor:
7347     //   struct A { template<typename T> A(T&); };
7348     //   struct B { mutable A a; };
7349     goto NeedOverloadResolution;
7350 
7351   case Sema::CXXCopyAssignment:
7352     // C++11 [class.copy]p25:
7353     //   A copy assignment operator is trivial if:
7354     //    - the assignment operator selected to copy each direct [subobject] is
7355     //      trivial
7356     if (RD->hasTrivialCopyAssignment()) {
7357       if (Quals == Qualifiers::Const)
7358         return true;
7359     } else if (!Selected) {
7360       return false;
7361     }
7362     // In C++98, we are not supposed to perform overload resolution here, but we
7363     // treat that as a language defect.
7364     goto NeedOverloadResolution;
7365 
7366   case Sema::CXXMoveConstructor:
7367   case Sema::CXXMoveAssignment:
7368   NeedOverloadResolution:
7369     Sema::SpecialMemberOverloadResult SMOR =
7370         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7371 
7372     // The standard doesn't describe how to behave if the lookup is ambiguous.
7373     // We treat it as not making the member non-trivial, just like the standard
7374     // mandates for the default constructor. This should rarely matter, because
7375     // the member will also be deleted.
7376     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7377       return true;
7378 
7379     if (!SMOR.getMethod()) {
7380       assert(SMOR.getKind() ==
7381              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7382       return false;
7383     }
7384 
7385     // We deliberately don't check if we found a deleted special member. We're
7386     // not supposed to!
7387     if (Selected)
7388       *Selected = SMOR.getMethod();
7389 
7390     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7391         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7392       return SMOR.getMethod()->isTrivialForCall();
7393     return SMOR.getMethod()->isTrivial();
7394   }
7395 
7396   llvm_unreachable("unknown special method kind");
7397 }
7398 
7399 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7400   for (auto *CI : RD->ctors())
7401     if (!CI->isImplicit())
7402       return CI;
7403 
7404   // Look for constructor templates.
7405   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7406   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7407     if (CXXConstructorDecl *CD =
7408           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7409       return CD;
7410   }
7411 
7412   return nullptr;
7413 }
7414 
7415 /// The kind of subobject we are checking for triviality. The values of this
7416 /// enumeration are used in diagnostics.
7417 enum TrivialSubobjectKind {
7418   /// The subobject is a base class.
7419   TSK_BaseClass,
7420   /// The subobject is a non-static data member.
7421   TSK_Field,
7422   /// The object is actually the complete object.
7423   TSK_CompleteObject
7424 };
7425 
7426 /// Check whether the special member selected for a given type would be trivial.
7427 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7428                                       QualType SubType, bool ConstRHS,
7429                                       Sema::CXXSpecialMember CSM,
7430                                       TrivialSubobjectKind Kind,
7431                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7432   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7433   if (!SubRD)
7434     return true;
7435 
7436   CXXMethodDecl *Selected;
7437   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7438                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7439     return true;
7440 
7441   if (Diagnose) {
7442     if (ConstRHS)
7443       SubType.addConst();
7444 
7445     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7446       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7447         << Kind << SubType.getUnqualifiedType();
7448       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7449         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7450     } else if (!Selected)
7451       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7452         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7453     else if (Selected->isUserProvided()) {
7454       if (Kind == TSK_CompleteObject)
7455         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7456           << Kind << SubType.getUnqualifiedType() << CSM;
7457       else {
7458         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7459           << Kind << SubType.getUnqualifiedType() << CSM;
7460         S.Diag(Selected->getLocation(), diag::note_declared_at);
7461       }
7462     } else {
7463       if (Kind != TSK_CompleteObject)
7464         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7465           << Kind << SubType.getUnqualifiedType() << CSM;
7466 
7467       // Explain why the defaulted or deleted special member isn't trivial.
7468       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7469                                Diagnose);
7470     }
7471   }
7472 
7473   return false;
7474 }
7475 
7476 /// Check whether the members of a class type allow a special member to be
7477 /// trivial.
7478 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7479                                      Sema::CXXSpecialMember CSM,
7480                                      bool ConstArg,
7481                                      Sema::TrivialABIHandling TAH,
7482                                      bool Diagnose) {
7483   for (const auto *FI : RD->fields()) {
7484     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7485       continue;
7486 
7487     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7488 
7489     // Pretend anonymous struct or union members are members of this class.
7490     if (FI->isAnonymousStructOrUnion()) {
7491       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7492                                     CSM, ConstArg, TAH, Diagnose))
7493         return false;
7494       continue;
7495     }
7496 
7497     // C++11 [class.ctor]p5:
7498     //   A default constructor is trivial if [...]
7499     //    -- no non-static data member of its class has a
7500     //       brace-or-equal-initializer
7501     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7502       if (Diagnose)
7503         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7504       return false;
7505     }
7506 
7507     // Objective C ARC 4.3.5:
7508     //   [...] nontrivally ownership-qualified types are [...] not trivially
7509     //   default constructible, copy constructible, move constructible, copy
7510     //   assignable, move assignable, or destructible [...]
7511     if (FieldType.hasNonTrivialObjCLifetime()) {
7512       if (Diagnose)
7513         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7514           << RD << FieldType.getObjCLifetime();
7515       return false;
7516     }
7517 
7518     bool ConstRHS = ConstArg && !FI->isMutable();
7519     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7520                                    CSM, TSK_Field, TAH, Diagnose))
7521       return false;
7522   }
7523 
7524   return true;
7525 }
7526 
7527 /// Diagnose why the specified class does not have a trivial special member of
7528 /// the given kind.
7529 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7530   QualType Ty = Context.getRecordType(RD);
7531 
7532   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7533   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7534                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7535                             /*Diagnose*/true);
7536 }
7537 
7538 /// Determine whether a defaulted or deleted special member function is trivial,
7539 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7540 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7541 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7542                                   TrivialABIHandling TAH, bool Diagnose) {
7543   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7544 
7545   CXXRecordDecl *RD = MD->getParent();
7546 
7547   bool ConstArg = false;
7548 
7549   // C++11 [class.copy]p12, p25: [DR1593]
7550   //   A [special member] is trivial if [...] its parameter-type-list is
7551   //   equivalent to the parameter-type-list of an implicit declaration [...]
7552   switch (CSM) {
7553   case CXXDefaultConstructor:
7554   case CXXDestructor:
7555     // Trivial default constructors and destructors cannot have parameters.
7556     break;
7557 
7558   case CXXCopyConstructor:
7559   case CXXCopyAssignment: {
7560     // Trivial copy operations always have const, non-volatile parameter types.
7561     ConstArg = true;
7562     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7563     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7564     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7565       if (Diagnose)
7566         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7567           << Param0->getSourceRange() << Param0->getType()
7568           << Context.getLValueReferenceType(
7569                Context.getRecordType(RD).withConst());
7570       return false;
7571     }
7572     break;
7573   }
7574 
7575   case CXXMoveConstructor:
7576   case CXXMoveAssignment: {
7577     // Trivial move operations always have non-cv-qualified parameters.
7578     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7579     const RValueReferenceType *RT =
7580       Param0->getType()->getAs<RValueReferenceType>();
7581     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7582       if (Diagnose)
7583         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7584           << Param0->getSourceRange() << Param0->getType()
7585           << Context.getRValueReferenceType(Context.getRecordType(RD));
7586       return false;
7587     }
7588     break;
7589   }
7590 
7591   case CXXInvalid:
7592     llvm_unreachable("not a special member");
7593   }
7594 
7595   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7596     if (Diagnose)
7597       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7598            diag::note_nontrivial_default_arg)
7599         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7600     return false;
7601   }
7602   if (MD->isVariadic()) {
7603     if (Diagnose)
7604       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7605     return false;
7606   }
7607 
7608   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7609   //   A copy/move [constructor or assignment operator] is trivial if
7610   //    -- the [member] selected to copy/move each direct base class subobject
7611   //       is trivial
7612   //
7613   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7614   //   A [default constructor or destructor] is trivial if
7615   //    -- all the direct base classes have trivial [default constructors or
7616   //       destructors]
7617   for (const auto &BI : RD->bases())
7618     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7619                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7620       return false;
7621 
7622   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7623   //   A copy/move [constructor or assignment operator] for a class X is
7624   //   trivial if
7625   //    -- for each non-static data member of X that is of class type (or array
7626   //       thereof), the constructor selected to copy/move that member is
7627   //       trivial
7628   //
7629   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7630   //   A [default constructor or destructor] is trivial if
7631   //    -- for all of the non-static data members of its class that are of class
7632   //       type (or array thereof), each such class has a trivial [default
7633   //       constructor or destructor]
7634   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7635     return false;
7636 
7637   // C++11 [class.dtor]p5:
7638   //   A destructor is trivial if [...]
7639   //    -- the destructor is not virtual
7640   if (CSM == CXXDestructor && MD->isVirtual()) {
7641     if (Diagnose)
7642       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7643     return false;
7644   }
7645 
7646   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7647   //   A [special member] for class X is trivial if [...]
7648   //    -- class X has no virtual functions and no virtual base classes
7649   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7650     if (!Diagnose)
7651       return false;
7652 
7653     if (RD->getNumVBases()) {
7654       // Check for virtual bases. We already know that the corresponding
7655       // member in all bases is trivial, so vbases must all be direct.
7656       CXXBaseSpecifier &BS = *RD->vbases_begin();
7657       assert(BS.isVirtual());
7658       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7659       return false;
7660     }
7661 
7662     // Must have a virtual method.
7663     for (const auto *MI : RD->methods()) {
7664       if (MI->isVirtual()) {
7665         SourceLocation MLoc = MI->getBeginLoc();
7666         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7667         return false;
7668       }
7669     }
7670 
7671     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7672   }
7673 
7674   // Looks like it's trivial!
7675   return true;
7676 }
7677 
7678 namespace {
7679 struct FindHiddenVirtualMethod {
7680   Sema *S;
7681   CXXMethodDecl *Method;
7682   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7683   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7684 
7685 private:
7686   /// Check whether any most overriden method from MD in Methods
7687   static bool CheckMostOverridenMethods(
7688       const CXXMethodDecl *MD,
7689       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7690     if (MD->size_overridden_methods() == 0)
7691       return Methods.count(MD->getCanonicalDecl());
7692     for (const CXXMethodDecl *O : MD->overridden_methods())
7693       if (CheckMostOverridenMethods(O, Methods))
7694         return true;
7695     return false;
7696   }
7697 
7698 public:
7699   /// Member lookup function that determines whether a given C++
7700   /// method overloads virtual methods in a base class without overriding any,
7701   /// to be used with CXXRecordDecl::lookupInBases().
7702   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7703     RecordDecl *BaseRecord =
7704         Specifier->getType()->getAs<RecordType>()->getDecl();
7705 
7706     DeclarationName Name = Method->getDeclName();
7707     assert(Name.getNameKind() == DeclarationName::Identifier);
7708 
7709     bool foundSameNameMethod = false;
7710     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7711     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7712          Path.Decls = Path.Decls.slice(1)) {
7713       NamedDecl *D = Path.Decls.front();
7714       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7715         MD = MD->getCanonicalDecl();
7716         foundSameNameMethod = true;
7717         // Interested only in hidden virtual methods.
7718         if (!MD->isVirtual())
7719           continue;
7720         // If the method we are checking overrides a method from its base
7721         // don't warn about the other overloaded methods. Clang deviates from
7722         // GCC by only diagnosing overloads of inherited virtual functions that
7723         // do not override any other virtual functions in the base. GCC's
7724         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7725         // function from a base class. These cases may be better served by a
7726         // warning (not specific to virtual functions) on call sites when the
7727         // call would select a different function from the base class, were it
7728         // visible.
7729         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7730         if (!S->IsOverload(Method, MD, false))
7731           return true;
7732         // Collect the overload only if its hidden.
7733         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7734           overloadedMethods.push_back(MD);
7735       }
7736     }
7737 
7738     if (foundSameNameMethod)
7739       OverloadedMethods.append(overloadedMethods.begin(),
7740                                overloadedMethods.end());
7741     return foundSameNameMethod;
7742   }
7743 };
7744 } // end anonymous namespace
7745 
7746 /// Add the most overriden methods from MD to Methods
7747 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7748                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7749   if (MD->size_overridden_methods() == 0)
7750     Methods.insert(MD->getCanonicalDecl());
7751   else
7752     for (const CXXMethodDecl *O : MD->overridden_methods())
7753       AddMostOverridenMethods(O, Methods);
7754 }
7755 
7756 /// Check if a method overloads virtual methods in a base class without
7757 /// overriding any.
7758 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7759                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7760   if (!MD->getDeclName().isIdentifier())
7761     return;
7762 
7763   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7764                      /*bool RecordPaths=*/false,
7765                      /*bool DetectVirtual=*/false);
7766   FindHiddenVirtualMethod FHVM;
7767   FHVM.Method = MD;
7768   FHVM.S = this;
7769 
7770   // Keep the base methods that were overriden or introduced in the subclass
7771   // by 'using' in a set. A base method not in this set is hidden.
7772   CXXRecordDecl *DC = MD->getParent();
7773   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7774   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7775     NamedDecl *ND = *I;
7776     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7777       ND = shad->getTargetDecl();
7778     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7779       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7780   }
7781 
7782   if (DC->lookupInBases(FHVM, Paths))
7783     OverloadedMethods = FHVM.OverloadedMethods;
7784 }
7785 
7786 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7787                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7788   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7789     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7790     PartialDiagnostic PD = PDiag(
7791          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7792     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7793     Diag(overloadedMD->getLocation(), PD);
7794   }
7795 }
7796 
7797 /// Diagnose methods which overload virtual methods in a base class
7798 /// without overriding any.
7799 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7800   if (MD->isInvalidDecl())
7801     return;
7802 
7803   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7804     return;
7805 
7806   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7807   FindHiddenVirtualMethods(MD, OverloadedMethods);
7808   if (!OverloadedMethods.empty()) {
7809     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7810       << MD << (OverloadedMethods.size() > 1);
7811 
7812     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7813   }
7814 }
7815 
7816 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7817   auto PrintDiagAndRemoveAttr = [&]() {
7818     // No diagnostics if this is a template instantiation.
7819     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7820       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7821            diag::ext_cannot_use_trivial_abi) << &RD;
7822     RD.dropAttr<TrivialABIAttr>();
7823   };
7824 
7825   // Ill-formed if the struct has virtual functions.
7826   if (RD.isPolymorphic()) {
7827     PrintDiagAndRemoveAttr();
7828     return;
7829   }
7830 
7831   for (const auto &B : RD.bases()) {
7832     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7833     // virtual base.
7834     if ((!B.getType()->isDependentType() &&
7835          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7836         B.isVirtual()) {
7837       PrintDiagAndRemoveAttr();
7838       return;
7839     }
7840   }
7841 
7842   for (const auto *FD : RD.fields()) {
7843     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7844     // non-trivial for the purpose of calls.
7845     QualType FT = FD->getType();
7846     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7847       PrintDiagAndRemoveAttr();
7848       return;
7849     }
7850 
7851     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7852       if (!RT->isDependentType() &&
7853           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7854         PrintDiagAndRemoveAttr();
7855         return;
7856       }
7857   }
7858 }
7859 
7860 void Sema::ActOnFinishCXXMemberSpecification(
7861     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7862     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7863   if (!TagDecl)
7864     return;
7865 
7866   AdjustDeclIfTemplate(TagDecl);
7867 
7868   for (const ParsedAttr &AL : AttrList) {
7869     if (AL.getKind() != ParsedAttr::AT_Visibility)
7870       continue;
7871     AL.setInvalid();
7872     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7873         << AL.getName();
7874   }
7875 
7876   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7877               // strict aliasing violation!
7878               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7879               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7880 
7881   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7882 }
7883 
7884 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7885 /// special functions, such as the default constructor, copy
7886 /// constructor, or destructor, to the given C++ class (C++
7887 /// [special]p1).  This routine can only be executed just before the
7888 /// definition of the class is complete.
7889 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7890   if (ClassDecl->needsImplicitDefaultConstructor()) {
7891     ++ASTContext::NumImplicitDefaultConstructors;
7892 
7893     if (ClassDecl->hasInheritedConstructor())
7894       DeclareImplicitDefaultConstructor(ClassDecl);
7895   }
7896 
7897   if (ClassDecl->needsImplicitCopyConstructor()) {
7898     ++ASTContext::NumImplicitCopyConstructors;
7899 
7900     // If the properties or semantics of the copy constructor couldn't be
7901     // determined while the class was being declared, force a declaration
7902     // of it now.
7903     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7904         ClassDecl->hasInheritedConstructor())
7905       DeclareImplicitCopyConstructor(ClassDecl);
7906     // For the MS ABI we need to know whether the copy ctor is deleted. A
7907     // prerequisite for deleting the implicit copy ctor is that the class has a
7908     // move ctor or move assignment that is either user-declared or whose
7909     // semantics are inherited from a subobject. FIXME: We should provide a more
7910     // direct way for CodeGen to ask whether the constructor was deleted.
7911     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7912              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7913               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7914               ClassDecl->hasUserDeclaredMoveAssignment() ||
7915               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7916       DeclareImplicitCopyConstructor(ClassDecl);
7917   }
7918 
7919   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7920     ++ASTContext::NumImplicitMoveConstructors;
7921 
7922     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7923         ClassDecl->hasInheritedConstructor())
7924       DeclareImplicitMoveConstructor(ClassDecl);
7925   }
7926 
7927   if (ClassDecl->needsImplicitCopyAssignment()) {
7928     ++ASTContext::NumImplicitCopyAssignmentOperators;
7929 
7930     // If we have a dynamic class, then the copy assignment operator may be
7931     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7932     // it shows up in the right place in the vtable and that we diagnose
7933     // problems with the implicit exception specification.
7934     if (ClassDecl->isDynamicClass() ||
7935         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7936         ClassDecl->hasInheritedAssignment())
7937       DeclareImplicitCopyAssignment(ClassDecl);
7938   }
7939 
7940   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7941     ++ASTContext::NumImplicitMoveAssignmentOperators;
7942 
7943     // Likewise for the move assignment operator.
7944     if (ClassDecl->isDynamicClass() ||
7945         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7946         ClassDecl->hasInheritedAssignment())
7947       DeclareImplicitMoveAssignment(ClassDecl);
7948   }
7949 
7950   if (ClassDecl->needsImplicitDestructor()) {
7951     ++ASTContext::NumImplicitDestructors;
7952 
7953     // If we have a dynamic class, then the destructor may be virtual, so we
7954     // have to declare the destructor immediately. This ensures that, e.g., it
7955     // shows up in the right place in the vtable and that we diagnose problems
7956     // with the implicit exception specification.
7957     if (ClassDecl->isDynamicClass() ||
7958         ClassDecl->needsOverloadResolutionForDestructor())
7959       DeclareImplicitDestructor(ClassDecl);
7960   }
7961 }
7962 
7963 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7964   if (!D)
7965     return 0;
7966 
7967   // The order of template parameters is not important here. All names
7968   // get added to the same scope.
7969   SmallVector<TemplateParameterList *, 4> ParameterLists;
7970 
7971   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7972     D = TD->getTemplatedDecl();
7973 
7974   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7975     ParameterLists.push_back(PSD->getTemplateParameters());
7976 
7977   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7978     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7979       ParameterLists.push_back(DD->getTemplateParameterList(i));
7980 
7981     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7982       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7983         ParameterLists.push_back(FTD->getTemplateParameters());
7984     }
7985   }
7986 
7987   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7988     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7989       ParameterLists.push_back(TD->getTemplateParameterList(i));
7990 
7991     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7992       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7993         ParameterLists.push_back(CTD->getTemplateParameters());
7994     }
7995   }
7996 
7997   unsigned Count = 0;
7998   for (TemplateParameterList *Params : ParameterLists) {
7999     if (Params->size() > 0)
8000       // Ignore explicit specializations; they don't contribute to the template
8001       // depth.
8002       ++Count;
8003     for (NamedDecl *Param : *Params) {
8004       if (Param->getDeclName()) {
8005         S->AddDecl(Param);
8006         IdResolver.AddDecl(Param);
8007       }
8008     }
8009   }
8010 
8011   return Count;
8012 }
8013 
8014 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8015   if (!RecordD) return;
8016   AdjustDeclIfTemplate(RecordD);
8017   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8018   PushDeclContext(S, Record);
8019 }
8020 
8021 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8022   if (!RecordD) return;
8023   PopDeclContext();
8024 }
8025 
8026 /// This is used to implement the constant expression evaluation part of the
8027 /// attribute enable_if extension. There is nothing in standard C++ which would
8028 /// require reentering parameters.
8029 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8030   if (!Param)
8031     return;
8032 
8033   S->AddDecl(Param);
8034   if (Param->getDeclName())
8035     IdResolver.AddDecl(Param);
8036 }
8037 
8038 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8039 /// parsing a top-level (non-nested) C++ class, and we are now
8040 /// parsing those parts of the given Method declaration that could
8041 /// not be parsed earlier (C++ [class.mem]p2), such as default
8042 /// arguments. This action should enter the scope of the given
8043 /// Method declaration as if we had just parsed the qualified method
8044 /// name. However, it should not bring the parameters into scope;
8045 /// that will be performed by ActOnDelayedCXXMethodParameter.
8046 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8047 }
8048 
8049 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8050 /// C++ method declaration. We're (re-)introducing the given
8051 /// function parameter into scope for use in parsing later parts of
8052 /// the method declaration. For example, we could see an
8053 /// ActOnParamDefaultArgument event for this parameter.
8054 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8055   if (!ParamD)
8056     return;
8057 
8058   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8059 
8060   // If this parameter has an unparsed default argument, clear it out
8061   // to make way for the parsed default argument.
8062   if (Param->hasUnparsedDefaultArg())
8063     Param->setDefaultArg(nullptr);
8064 
8065   S->AddDecl(Param);
8066   if (Param->getDeclName())
8067     IdResolver.AddDecl(Param);
8068 }
8069 
8070 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8071 /// processing the delayed method declaration for Method. The method
8072 /// declaration is now considered finished. There may be a separate
8073 /// ActOnStartOfFunctionDef action later (not necessarily
8074 /// immediately!) for this method, if it was also defined inside the
8075 /// class body.
8076 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8077   if (!MethodD)
8078     return;
8079 
8080   AdjustDeclIfTemplate(MethodD);
8081 
8082   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8083 
8084   // Now that we have our default arguments, check the constructor
8085   // again. It could produce additional diagnostics or affect whether
8086   // the class has implicitly-declared destructors, among other
8087   // things.
8088   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8089     CheckConstructor(Constructor);
8090 
8091   // Check the default arguments, which we may have added.
8092   if (!Method->isInvalidDecl())
8093     CheckCXXDefaultArguments(Method);
8094 }
8095 
8096 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8097 /// the well-formedness of the constructor declarator @p D with type @p
8098 /// R. If there are any errors in the declarator, this routine will
8099 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8100 /// will be updated to reflect a well-formed type for the constructor and
8101 /// returned.
8102 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8103                                           StorageClass &SC) {
8104   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8105 
8106   // C++ [class.ctor]p3:
8107   //   A constructor shall not be virtual (10.3) or static (9.4). A
8108   //   constructor can be invoked for a const, volatile or const
8109   //   volatile object. A constructor shall not be declared const,
8110   //   volatile, or const volatile (9.3.2).
8111   if (isVirtual) {
8112     if (!D.isInvalidType())
8113       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8114         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8115         << SourceRange(D.getIdentifierLoc());
8116     D.setInvalidType();
8117   }
8118   if (SC == SC_Static) {
8119     if (!D.isInvalidType())
8120       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8121         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8122         << SourceRange(D.getIdentifierLoc());
8123     D.setInvalidType();
8124     SC = SC_None;
8125   }
8126 
8127   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8128     diagnoseIgnoredQualifiers(
8129         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8130         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8131         D.getDeclSpec().getRestrictSpecLoc(),
8132         D.getDeclSpec().getAtomicSpecLoc());
8133     D.setInvalidType();
8134   }
8135 
8136   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8137   if (FTI.TypeQuals != 0) {
8138     if (FTI.TypeQuals & Qualifiers::Const)
8139       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8140         << "const" << SourceRange(D.getIdentifierLoc());
8141     if (FTI.TypeQuals & Qualifiers::Volatile)
8142       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8143         << "volatile" << SourceRange(D.getIdentifierLoc());
8144     if (FTI.TypeQuals & Qualifiers::Restrict)
8145       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8146         << "restrict" << SourceRange(D.getIdentifierLoc());
8147     D.setInvalidType();
8148   }
8149 
8150   // C++0x [class.ctor]p4:
8151   //   A constructor shall not be declared with a ref-qualifier.
8152   if (FTI.hasRefQualifier()) {
8153     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8154       << FTI.RefQualifierIsLValueRef
8155       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8156     D.setInvalidType();
8157   }
8158 
8159   // Rebuild the function type "R" without any type qualifiers (in
8160   // case any of the errors above fired) and with "void" as the
8161   // return type, since constructors don't have return types.
8162   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8163   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8164     return R;
8165 
8166   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8167   EPI.TypeQuals = 0;
8168   EPI.RefQualifier = RQ_None;
8169 
8170   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8171 }
8172 
8173 /// CheckConstructor - Checks a fully-formed constructor for
8174 /// well-formedness, issuing any diagnostics required. Returns true if
8175 /// the constructor declarator is invalid.
8176 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8177   CXXRecordDecl *ClassDecl
8178     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8179   if (!ClassDecl)
8180     return Constructor->setInvalidDecl();
8181 
8182   // C++ [class.copy]p3:
8183   //   A declaration of a constructor for a class X is ill-formed if
8184   //   its first parameter is of type (optionally cv-qualified) X and
8185   //   either there are no other parameters or else all other
8186   //   parameters have default arguments.
8187   if (!Constructor->isInvalidDecl() &&
8188       ((Constructor->getNumParams() == 1) ||
8189        (Constructor->getNumParams() > 1 &&
8190         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8191       Constructor->getTemplateSpecializationKind()
8192                                               != TSK_ImplicitInstantiation) {
8193     QualType ParamType = Constructor->getParamDecl(0)->getType();
8194     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8195     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8196       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8197       const char *ConstRef
8198         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8199                                                         : " const &";
8200       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8201         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8202 
8203       // FIXME: Rather that making the constructor invalid, we should endeavor
8204       // to fix the type.
8205       Constructor->setInvalidDecl();
8206     }
8207   }
8208 }
8209 
8210 /// CheckDestructor - Checks a fully-formed destructor definition for
8211 /// well-formedness, issuing any diagnostics required.  Returns true
8212 /// on error.
8213 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8214   CXXRecordDecl *RD = Destructor->getParent();
8215 
8216   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8217     SourceLocation Loc;
8218 
8219     if (!Destructor->isImplicit())
8220       Loc = Destructor->getLocation();
8221     else
8222       Loc = RD->getLocation();
8223 
8224     // If we have a virtual destructor, look up the deallocation function
8225     if (FunctionDecl *OperatorDelete =
8226             FindDeallocationFunctionForDestructor(Loc, RD)) {
8227       Expr *ThisArg = nullptr;
8228 
8229       // If the notional 'delete this' expression requires a non-trivial
8230       // conversion from 'this' to the type of a destroying operator delete's
8231       // first parameter, perform that conversion now.
8232       if (OperatorDelete->isDestroyingOperatorDelete()) {
8233         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8234         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8235           // C++ [class.dtor]p13:
8236           //   ... as if for the expression 'delete this' appearing in a
8237           //   non-virtual destructor of the destructor's class.
8238           ContextRAII SwitchContext(*this, Destructor);
8239           ExprResult This =
8240               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8241           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8242           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8243           if (This.isInvalid()) {
8244             // FIXME: Register this as a context note so that it comes out
8245             // in the right order.
8246             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8247             return true;
8248           }
8249           ThisArg = This.get();
8250         }
8251       }
8252 
8253       MarkFunctionReferenced(Loc, OperatorDelete);
8254       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8255     }
8256   }
8257 
8258   return false;
8259 }
8260 
8261 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8262 /// the well-formednes of the destructor declarator @p D with type @p
8263 /// R. If there are any errors in the declarator, this routine will
8264 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8265 /// will be updated to reflect a well-formed type for the destructor and
8266 /// returned.
8267 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8268                                          StorageClass& SC) {
8269   // C++ [class.dtor]p1:
8270   //   [...] A typedef-name that names a class is a class-name
8271   //   (7.1.3); however, a typedef-name that names a class shall not
8272   //   be used as the identifier in the declarator for a destructor
8273   //   declaration.
8274   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8275   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8276     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8277       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8278   else if (const TemplateSpecializationType *TST =
8279              DeclaratorType->getAs<TemplateSpecializationType>())
8280     if (TST->isTypeAlias())
8281       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8282         << DeclaratorType << 1;
8283 
8284   // C++ [class.dtor]p2:
8285   //   A destructor is used to destroy objects of its class type. A
8286   //   destructor takes no parameters, and no return type can be
8287   //   specified for it (not even void). The address of a destructor
8288   //   shall not be taken. A destructor shall not be static. A
8289   //   destructor can be invoked for a const, volatile or const
8290   //   volatile object. A destructor shall not be declared const,
8291   //   volatile or const volatile (9.3.2).
8292   if (SC == SC_Static) {
8293     if (!D.isInvalidType())
8294       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8295         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8296         << SourceRange(D.getIdentifierLoc())
8297         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8298 
8299     SC = SC_None;
8300   }
8301   if (!D.isInvalidType()) {
8302     // Destructors don't have return types, but the parser will
8303     // happily parse something like:
8304     //
8305     //   class X {
8306     //     float ~X();
8307     //   };
8308     //
8309     // The return type will be eliminated later.
8310     if (D.getDeclSpec().hasTypeSpecifier())
8311       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8312         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8313         << SourceRange(D.getIdentifierLoc());
8314     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8315       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8316                                 SourceLocation(),
8317                                 D.getDeclSpec().getConstSpecLoc(),
8318                                 D.getDeclSpec().getVolatileSpecLoc(),
8319                                 D.getDeclSpec().getRestrictSpecLoc(),
8320                                 D.getDeclSpec().getAtomicSpecLoc());
8321       D.setInvalidType();
8322     }
8323   }
8324 
8325   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8326   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8327     if (FTI.TypeQuals & Qualifiers::Const)
8328       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8329         << "const" << SourceRange(D.getIdentifierLoc());
8330     if (FTI.TypeQuals & Qualifiers::Volatile)
8331       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8332         << "volatile" << SourceRange(D.getIdentifierLoc());
8333     if (FTI.TypeQuals & Qualifiers::Restrict)
8334       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8335         << "restrict" << SourceRange(D.getIdentifierLoc());
8336     D.setInvalidType();
8337   }
8338 
8339   // C++0x [class.dtor]p2:
8340   //   A destructor shall not be declared with a ref-qualifier.
8341   if (FTI.hasRefQualifier()) {
8342     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8343       << FTI.RefQualifierIsLValueRef
8344       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8345     D.setInvalidType();
8346   }
8347 
8348   // Make sure we don't have any parameters.
8349   if (FTIHasNonVoidParameters(FTI)) {
8350     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8351 
8352     // Delete the parameters.
8353     FTI.freeParams();
8354     D.setInvalidType();
8355   }
8356 
8357   // Make sure the destructor isn't variadic.
8358   if (FTI.isVariadic) {
8359     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8360     D.setInvalidType();
8361   }
8362 
8363   // Rebuild the function type "R" without any type qualifiers or
8364   // parameters (in case any of the errors above fired) and with
8365   // "void" as the return type, since destructors don't have return
8366   // types.
8367   if (!D.isInvalidType())
8368     return R;
8369 
8370   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8371   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8372   EPI.Variadic = false;
8373   EPI.TypeQuals = 0;
8374   EPI.RefQualifier = RQ_None;
8375   return Context.getFunctionType(Context.VoidTy, None, EPI);
8376 }
8377 
8378 static void extendLeft(SourceRange &R, SourceRange Before) {
8379   if (Before.isInvalid())
8380     return;
8381   R.setBegin(Before.getBegin());
8382   if (R.getEnd().isInvalid())
8383     R.setEnd(Before.getEnd());
8384 }
8385 
8386 static void extendRight(SourceRange &R, SourceRange After) {
8387   if (After.isInvalid())
8388     return;
8389   if (R.getBegin().isInvalid())
8390     R.setBegin(After.getBegin());
8391   R.setEnd(After.getEnd());
8392 }
8393 
8394 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8395 /// well-formednes of the conversion function declarator @p D with
8396 /// type @p R. If there are any errors in the declarator, this routine
8397 /// will emit diagnostics and return true. Otherwise, it will return
8398 /// false. Either way, the type @p R will be updated to reflect a
8399 /// well-formed type for the conversion operator.
8400 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8401                                      StorageClass& SC) {
8402   // C++ [class.conv.fct]p1:
8403   //   Neither parameter types nor return type can be specified. The
8404   //   type of a conversion function (8.3.5) is "function taking no
8405   //   parameter returning conversion-type-id."
8406   if (SC == SC_Static) {
8407     if (!D.isInvalidType())
8408       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8409         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8410         << D.getName().getSourceRange();
8411     D.setInvalidType();
8412     SC = SC_None;
8413   }
8414 
8415   TypeSourceInfo *ConvTSI = nullptr;
8416   QualType ConvType =
8417       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8418 
8419   const DeclSpec &DS = D.getDeclSpec();
8420   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8421     // Conversion functions don't have return types, but the parser will
8422     // happily parse something like:
8423     //
8424     //   class X {
8425     //     float operator bool();
8426     //   };
8427     //
8428     // The return type will be changed later anyway.
8429     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8430       << SourceRange(DS.getTypeSpecTypeLoc())
8431       << SourceRange(D.getIdentifierLoc());
8432     D.setInvalidType();
8433   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8434     // It's also plausible that the user writes type qualifiers in the wrong
8435     // place, such as:
8436     //   struct S { const operator int(); };
8437     // FIXME: we could provide a fixit to move the qualifiers onto the
8438     // conversion type.
8439     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8440         << SourceRange(D.getIdentifierLoc()) << 0;
8441     D.setInvalidType();
8442   }
8443 
8444   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8445 
8446   // Make sure we don't have any parameters.
8447   if (Proto->getNumParams() > 0) {
8448     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8449 
8450     // Delete the parameters.
8451     D.getFunctionTypeInfo().freeParams();
8452     D.setInvalidType();
8453   } else if (Proto->isVariadic()) {
8454     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8455     D.setInvalidType();
8456   }
8457 
8458   // Diagnose "&operator bool()" and other such nonsense.  This
8459   // is actually a gcc extension which we don't support.
8460   if (Proto->getReturnType() != ConvType) {
8461     bool NeedsTypedef = false;
8462     SourceRange Before, After;
8463 
8464     // Walk the chunks and extract information on them for our diagnostic.
8465     bool PastFunctionChunk = false;
8466     for (auto &Chunk : D.type_objects()) {
8467       switch (Chunk.Kind) {
8468       case DeclaratorChunk::Function:
8469         if (!PastFunctionChunk) {
8470           if (Chunk.Fun.HasTrailingReturnType) {
8471             TypeSourceInfo *TRT = nullptr;
8472             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8473             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8474           }
8475           PastFunctionChunk = true;
8476           break;
8477         }
8478         LLVM_FALLTHROUGH;
8479       case DeclaratorChunk::Array:
8480         NeedsTypedef = true;
8481         extendRight(After, Chunk.getSourceRange());
8482         break;
8483 
8484       case DeclaratorChunk::Pointer:
8485       case DeclaratorChunk::BlockPointer:
8486       case DeclaratorChunk::Reference:
8487       case DeclaratorChunk::MemberPointer:
8488       case DeclaratorChunk::Pipe:
8489         extendLeft(Before, Chunk.getSourceRange());
8490         break;
8491 
8492       case DeclaratorChunk::Paren:
8493         extendLeft(Before, Chunk.Loc);
8494         extendRight(After, Chunk.EndLoc);
8495         break;
8496       }
8497     }
8498 
8499     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8500                          After.isValid()  ? After.getBegin() :
8501                                             D.getIdentifierLoc();
8502     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8503     DB << Before << After;
8504 
8505     if (!NeedsTypedef) {
8506       DB << /*don't need a typedef*/0;
8507 
8508       // If we can provide a correct fix-it hint, do so.
8509       if (After.isInvalid() && ConvTSI) {
8510         SourceLocation InsertLoc =
8511             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8512         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8513            << FixItHint::CreateInsertionFromRange(
8514                   InsertLoc, CharSourceRange::getTokenRange(Before))
8515            << FixItHint::CreateRemoval(Before);
8516       }
8517     } else if (!Proto->getReturnType()->isDependentType()) {
8518       DB << /*typedef*/1 << Proto->getReturnType();
8519     } else if (getLangOpts().CPlusPlus11) {
8520       DB << /*alias template*/2 << Proto->getReturnType();
8521     } else {
8522       DB << /*might not be fixable*/3;
8523     }
8524 
8525     // Recover by incorporating the other type chunks into the result type.
8526     // Note, this does *not* change the name of the function. This is compatible
8527     // with the GCC extension:
8528     //   struct S { &operator int(); } s;
8529     //   int &r = s.operator int(); // ok in GCC
8530     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8531     ConvType = Proto->getReturnType();
8532   }
8533 
8534   // C++ [class.conv.fct]p4:
8535   //   The conversion-type-id shall not represent a function type nor
8536   //   an array type.
8537   if (ConvType->isArrayType()) {
8538     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8539     ConvType = Context.getPointerType(ConvType);
8540     D.setInvalidType();
8541   } else if (ConvType->isFunctionType()) {
8542     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8543     ConvType = Context.getPointerType(ConvType);
8544     D.setInvalidType();
8545   }
8546 
8547   // Rebuild the function type "R" without any parameters (in case any
8548   // of the errors above fired) and with the conversion type as the
8549   // return type.
8550   if (D.isInvalidType())
8551     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8552 
8553   // C++0x explicit conversion operators.
8554   if (DS.isExplicitSpecified())
8555     Diag(DS.getExplicitSpecLoc(),
8556          getLangOpts().CPlusPlus11
8557              ? diag::warn_cxx98_compat_explicit_conversion_functions
8558              : diag::ext_explicit_conversion_functions)
8559         << SourceRange(DS.getExplicitSpecLoc());
8560 }
8561 
8562 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8563 /// the declaration of the given C++ conversion function. This routine
8564 /// is responsible for recording the conversion function in the C++
8565 /// class, if possible.
8566 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8567   assert(Conversion && "Expected to receive a conversion function declaration");
8568 
8569   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8570 
8571   // Make sure we aren't redeclaring the conversion function.
8572   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8573 
8574   // C++ [class.conv.fct]p1:
8575   //   [...] A conversion function is never used to convert a
8576   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8577   //   same object type (or a reference to it), to a (possibly
8578   //   cv-qualified) base class of that type (or a reference to it),
8579   //   or to (possibly cv-qualified) void.
8580   // FIXME: Suppress this warning if the conversion function ends up being a
8581   // virtual function that overrides a virtual function in a base class.
8582   QualType ClassType
8583     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8584   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8585     ConvType = ConvTypeRef->getPointeeType();
8586   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8587       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8588     /* Suppress diagnostics for instantiations. */;
8589   else if (ConvType->isRecordType()) {
8590     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8591     if (ConvType == ClassType)
8592       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8593         << ClassType;
8594     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8595       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8596         <<  ClassType << ConvType;
8597   } else if (ConvType->isVoidType()) {
8598     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8599       << ClassType << ConvType;
8600   }
8601 
8602   if (FunctionTemplateDecl *ConversionTemplate
8603                                 = Conversion->getDescribedFunctionTemplate())
8604     return ConversionTemplate;
8605 
8606   return Conversion;
8607 }
8608 
8609 namespace {
8610 /// Utility class to accumulate and print a diagnostic listing the invalid
8611 /// specifier(s) on a declaration.
8612 struct BadSpecifierDiagnoser {
8613   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8614       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8615   ~BadSpecifierDiagnoser() {
8616     Diagnostic << Specifiers;
8617   }
8618 
8619   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8620     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8621   }
8622   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8623     return check(SpecLoc,
8624                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8625   }
8626   void check(SourceLocation SpecLoc, const char *Spec) {
8627     if (SpecLoc.isInvalid()) return;
8628     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8629     if (!Specifiers.empty()) Specifiers += " ";
8630     Specifiers += Spec;
8631   }
8632 
8633   Sema &S;
8634   Sema::SemaDiagnosticBuilder Diagnostic;
8635   std::string Specifiers;
8636 };
8637 }
8638 
8639 /// Check the validity of a declarator that we parsed for a deduction-guide.
8640 /// These aren't actually declarators in the grammar, so we need to check that
8641 /// the user didn't specify any pieces that are not part of the deduction-guide
8642 /// grammar.
8643 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8644                                          StorageClass &SC) {
8645   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8646   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8647   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8648 
8649   // C++ [temp.deduct.guide]p3:
8650   //   A deduction-gide shall be declared in the same scope as the
8651   //   corresponding class template.
8652   if (!CurContext->getRedeclContext()->Equals(
8653           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8654     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8655       << GuidedTemplateDecl;
8656     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8657   }
8658 
8659   auto &DS = D.getMutableDeclSpec();
8660   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8661   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8662       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8663       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8664     BadSpecifierDiagnoser Diagnoser(
8665         *this, D.getIdentifierLoc(),
8666         diag::err_deduction_guide_invalid_specifier);
8667 
8668     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8669     DS.ClearStorageClassSpecs();
8670     SC = SC_None;
8671 
8672     // 'explicit' is permitted.
8673     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8674     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8675     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8676     DS.ClearConstexprSpec();
8677 
8678     Diagnoser.check(DS.getConstSpecLoc(), "const");
8679     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8680     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8681     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8682     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8683     DS.ClearTypeQualifiers();
8684 
8685     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8686     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8687     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8688     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8689     DS.ClearTypeSpecType();
8690   }
8691 
8692   if (D.isInvalidType())
8693     return;
8694 
8695   // Check the declarator is simple enough.
8696   bool FoundFunction = false;
8697   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8698     if (Chunk.Kind == DeclaratorChunk::Paren)
8699       continue;
8700     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8701       Diag(D.getDeclSpec().getBeginLoc(),
8702            diag::err_deduction_guide_with_complex_decl)
8703           << D.getSourceRange();
8704       break;
8705     }
8706     if (!Chunk.Fun.hasTrailingReturnType()) {
8707       Diag(D.getName().getBeginLoc(),
8708            diag::err_deduction_guide_no_trailing_return_type);
8709       break;
8710     }
8711 
8712     // Check that the return type is written as a specialization of
8713     // the template specified as the deduction-guide's name.
8714     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8715     TypeSourceInfo *TSI = nullptr;
8716     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8717     assert(TSI && "deduction guide has valid type but invalid return type?");
8718     bool AcceptableReturnType = false;
8719     bool MightInstantiateToSpecialization = false;
8720     if (auto RetTST =
8721             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8722       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8723       bool TemplateMatches =
8724           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8725       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8726         AcceptableReturnType = true;
8727       else {
8728         // This could still instantiate to the right type, unless we know it
8729         // names the wrong class template.
8730         auto *TD = SpecifiedName.getAsTemplateDecl();
8731         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8732                                              !TemplateMatches);
8733       }
8734     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8735       MightInstantiateToSpecialization = true;
8736     }
8737 
8738     if (!AcceptableReturnType) {
8739       Diag(TSI->getTypeLoc().getBeginLoc(),
8740            diag::err_deduction_guide_bad_trailing_return_type)
8741           << GuidedTemplate << TSI->getType()
8742           << MightInstantiateToSpecialization
8743           << TSI->getTypeLoc().getSourceRange();
8744     }
8745 
8746     // Keep going to check that we don't have any inner declarator pieces (we
8747     // could still have a function returning a pointer to a function).
8748     FoundFunction = true;
8749   }
8750 
8751   if (D.isFunctionDefinition())
8752     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8753 }
8754 
8755 //===----------------------------------------------------------------------===//
8756 // Namespace Handling
8757 //===----------------------------------------------------------------------===//
8758 
8759 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8760 /// reopened.
8761 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8762                                             SourceLocation Loc,
8763                                             IdentifierInfo *II, bool *IsInline,
8764                                             NamespaceDecl *PrevNS) {
8765   assert(*IsInline != PrevNS->isInline());
8766 
8767   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8768   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8769   // inline namespaces, with the intention of bringing names into namespace std.
8770   //
8771   // We support this just well enough to get that case working; this is not
8772   // sufficient to support reopening namespaces as inline in general.
8773   if (*IsInline && II && II->getName().startswith("__atomic") &&
8774       S.getSourceManager().isInSystemHeader(Loc)) {
8775     // Mark all prior declarations of the namespace as inline.
8776     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8777          NS = NS->getPreviousDecl())
8778       NS->setInline(*IsInline);
8779     // Patch up the lookup table for the containing namespace. This isn't really
8780     // correct, but it's good enough for this particular case.
8781     for (auto *I : PrevNS->decls())
8782       if (auto *ND = dyn_cast<NamedDecl>(I))
8783         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8784     return;
8785   }
8786 
8787   if (PrevNS->isInline())
8788     // The user probably just forgot the 'inline', so suggest that it
8789     // be added back.
8790     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8791       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8792   else
8793     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8794 
8795   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8796   *IsInline = PrevNS->isInline();
8797 }
8798 
8799 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8800 /// definition.
8801 Decl *Sema::ActOnStartNamespaceDef(
8802     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8803     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8804     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8805   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8806   // For anonymous namespace, take the location of the left brace.
8807   SourceLocation Loc = II ? IdentLoc : LBrace;
8808   bool IsInline = InlineLoc.isValid();
8809   bool IsInvalid = false;
8810   bool IsStd = false;
8811   bool AddToKnown = false;
8812   Scope *DeclRegionScope = NamespcScope->getParent();
8813 
8814   NamespaceDecl *PrevNS = nullptr;
8815   if (II) {
8816     // C++ [namespace.def]p2:
8817     //   The identifier in an original-namespace-definition shall not
8818     //   have been previously defined in the declarative region in
8819     //   which the original-namespace-definition appears. The
8820     //   identifier in an original-namespace-definition is the name of
8821     //   the namespace. Subsequently in that declarative region, it is
8822     //   treated as an original-namespace-name.
8823     //
8824     // Since namespace names are unique in their scope, and we don't
8825     // look through using directives, just look for any ordinary names
8826     // as if by qualified name lookup.
8827     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8828                    ForExternalRedeclaration);
8829     LookupQualifiedName(R, CurContext->getRedeclContext());
8830     NamedDecl *PrevDecl =
8831         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8832     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8833 
8834     if (PrevNS) {
8835       // This is an extended namespace definition.
8836       if (IsInline != PrevNS->isInline())
8837         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8838                                         &IsInline, PrevNS);
8839     } else if (PrevDecl) {
8840       // This is an invalid name redefinition.
8841       Diag(Loc, diag::err_redefinition_different_kind)
8842         << II;
8843       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8844       IsInvalid = true;
8845       // Continue on to push Namespc as current DeclContext and return it.
8846     } else if (II->isStr("std") &&
8847                CurContext->getRedeclContext()->isTranslationUnit()) {
8848       // This is the first "real" definition of the namespace "std", so update
8849       // our cache of the "std" namespace to point at this definition.
8850       PrevNS = getStdNamespace();
8851       IsStd = true;
8852       AddToKnown = !IsInline;
8853     } else {
8854       // We've seen this namespace for the first time.
8855       AddToKnown = !IsInline;
8856     }
8857   } else {
8858     // Anonymous namespaces.
8859 
8860     // Determine whether the parent already has an anonymous namespace.
8861     DeclContext *Parent = CurContext->getRedeclContext();
8862     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8863       PrevNS = TU->getAnonymousNamespace();
8864     } else {
8865       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8866       PrevNS = ND->getAnonymousNamespace();
8867     }
8868 
8869     if (PrevNS && IsInline != PrevNS->isInline())
8870       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8871                                       &IsInline, PrevNS);
8872   }
8873 
8874   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8875                                                  StartLoc, Loc, II, PrevNS);
8876   if (IsInvalid)
8877     Namespc->setInvalidDecl();
8878 
8879   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8880   AddPragmaAttributes(DeclRegionScope, Namespc);
8881 
8882   // FIXME: Should we be merging attributes?
8883   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8884     PushNamespaceVisibilityAttr(Attr, Loc);
8885 
8886   if (IsStd)
8887     StdNamespace = Namespc;
8888   if (AddToKnown)
8889     KnownNamespaces[Namespc] = false;
8890 
8891   if (II) {
8892     PushOnScopeChains(Namespc, DeclRegionScope);
8893   } else {
8894     // Link the anonymous namespace into its parent.
8895     DeclContext *Parent = CurContext->getRedeclContext();
8896     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8897       TU->setAnonymousNamespace(Namespc);
8898     } else {
8899       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8900     }
8901 
8902     CurContext->addDecl(Namespc);
8903 
8904     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8905     //   behaves as if it were replaced by
8906     //     namespace unique { /* empty body */ }
8907     //     using namespace unique;
8908     //     namespace unique { namespace-body }
8909     //   where all occurrences of 'unique' in a translation unit are
8910     //   replaced by the same identifier and this identifier differs
8911     //   from all other identifiers in the entire program.
8912 
8913     // We just create the namespace with an empty name and then add an
8914     // implicit using declaration, just like the standard suggests.
8915     //
8916     // CodeGen enforces the "universally unique" aspect by giving all
8917     // declarations semantically contained within an anonymous
8918     // namespace internal linkage.
8919 
8920     if (!PrevNS) {
8921       UD = UsingDirectiveDecl::Create(Context, Parent,
8922                                       /* 'using' */ LBrace,
8923                                       /* 'namespace' */ SourceLocation(),
8924                                       /* qualifier */ NestedNameSpecifierLoc(),
8925                                       /* identifier */ SourceLocation(),
8926                                       Namespc,
8927                                       /* Ancestor */ Parent);
8928       UD->setImplicit();
8929       Parent->addDecl(UD);
8930     }
8931   }
8932 
8933   ActOnDocumentableDecl(Namespc);
8934 
8935   // Although we could have an invalid decl (i.e. the namespace name is a
8936   // redefinition), push it as current DeclContext and try to continue parsing.
8937   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8938   // for the namespace has the declarations that showed up in that particular
8939   // namespace definition.
8940   PushDeclContext(NamespcScope, Namespc);
8941   return Namespc;
8942 }
8943 
8944 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8945 /// is a namespace alias, returns the namespace it points to.
8946 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8947   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8948     return AD->getNamespace();
8949   return dyn_cast_or_null<NamespaceDecl>(D);
8950 }
8951 
8952 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8953 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8954 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8955   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8956   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8957   Namespc->setRBraceLoc(RBrace);
8958   PopDeclContext();
8959   if (Namespc->hasAttr<VisibilityAttr>())
8960     PopPragmaVisibility(true, RBrace);
8961 }
8962 
8963 CXXRecordDecl *Sema::getStdBadAlloc() const {
8964   return cast_or_null<CXXRecordDecl>(
8965                                   StdBadAlloc.get(Context.getExternalSource()));
8966 }
8967 
8968 EnumDecl *Sema::getStdAlignValT() const {
8969   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8970 }
8971 
8972 NamespaceDecl *Sema::getStdNamespace() const {
8973   return cast_or_null<NamespaceDecl>(
8974                                  StdNamespace.get(Context.getExternalSource()));
8975 }
8976 
8977 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8978   if (!StdExperimentalNamespaceCache) {
8979     if (auto Std = getStdNamespace()) {
8980       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8981                           SourceLocation(), LookupNamespaceName);
8982       if (!LookupQualifiedName(Result, Std) ||
8983           !(StdExperimentalNamespaceCache =
8984                 Result.getAsSingle<NamespaceDecl>()))
8985         Result.suppressDiagnostics();
8986     }
8987   }
8988   return StdExperimentalNamespaceCache;
8989 }
8990 
8991 namespace {
8992 
8993 enum UnsupportedSTLSelect {
8994   USS_InvalidMember,
8995   USS_MissingMember,
8996   USS_NonTrivial,
8997   USS_Other
8998 };
8999 
9000 struct InvalidSTLDiagnoser {
9001   Sema &S;
9002   SourceLocation Loc;
9003   QualType TyForDiags;
9004 
9005   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9006                       const VarDecl *VD = nullptr) {
9007     {
9008       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9009                << TyForDiags << ((int)Sel);
9010       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9011         assert(!Name.empty());
9012         D << Name;
9013       }
9014     }
9015     if (Sel == USS_InvalidMember) {
9016       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9017           << VD << VD->getSourceRange();
9018     }
9019     return QualType();
9020   }
9021 };
9022 } // namespace
9023 
9024 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9025                                            SourceLocation Loc) {
9026   assert(getLangOpts().CPlusPlus &&
9027          "Looking for comparison category type outside of C++.");
9028 
9029   // Check if we've already successfully checked the comparison category type
9030   // before. If so, skip checking it again.
9031   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9032   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9033     return Info->getType();
9034 
9035   // If lookup failed
9036   if (!Info) {
9037     std::string NameForDiags = "std::";
9038     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9039     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9040         << NameForDiags;
9041     return QualType();
9042   }
9043 
9044   assert(Info->Kind == Kind);
9045   assert(Info->Record);
9046 
9047   // Update the Record decl in case we encountered a forward declaration on our
9048   // first pass. FIXME: This is a bit of a hack.
9049   if (Info->Record->hasDefinition())
9050     Info->Record = Info->Record->getDefinition();
9051 
9052   // Use an elaborated type for diagnostics which has a name containing the
9053   // prepended 'std' namespace but not any inline namespace names.
9054   QualType TyForDiags = [&]() {
9055     auto *NNS =
9056         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9057     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9058   }();
9059 
9060   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9061     return QualType();
9062 
9063   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9064 
9065   if (!Info->Record->isTriviallyCopyable())
9066     return UnsupportedSTLError(USS_NonTrivial);
9067 
9068   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9069     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9070     // Tolerate empty base classes.
9071     if (Base->isEmpty())
9072       continue;
9073     // Reject STL implementations which have at least one non-empty base.
9074     return UnsupportedSTLError();
9075   }
9076 
9077   // Check that the STL has implemented the types using a single integer field.
9078   // This expectation allows better codegen for builtin operators. We require:
9079   //   (1) The class has exactly one field.
9080   //   (2) The field is an integral or enumeration type.
9081   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9082   if (std::distance(FIt, FEnd) != 1 ||
9083       !FIt->getType()->isIntegralOrEnumerationType()) {
9084     return UnsupportedSTLError();
9085   }
9086 
9087   // Build each of the require values and store them in Info.
9088   for (ComparisonCategoryResult CCR :
9089        ComparisonCategories::getPossibleResultsForType(Kind)) {
9090     StringRef MemName = ComparisonCategories::getResultString(CCR);
9091     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9092 
9093     if (!ValInfo)
9094       return UnsupportedSTLError(USS_MissingMember, MemName);
9095 
9096     VarDecl *VD = ValInfo->VD;
9097     assert(VD && "should not be null!");
9098 
9099     // Attempt to diagnose reasons why the STL definition of this type
9100     // might be foobar, including it failing to be a constant expression.
9101     // TODO Handle more ways the lookup or result can be invalid.
9102     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9103         !VD->checkInitIsICE())
9104       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9105 
9106     // Attempt to evaluate the var decl as a constant expression and extract
9107     // the value of its first field as a ICE. If this fails, the STL
9108     // implementation is not supported.
9109     if (!ValInfo->hasValidIntValue())
9110       return UnsupportedSTLError();
9111 
9112     MarkVariableReferenced(Loc, VD);
9113   }
9114 
9115   // We've successfully built the required types and expressions. Update
9116   // the cache and return the newly cached value.
9117   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9118   return Info->getType();
9119 }
9120 
9121 /// Retrieve the special "std" namespace, which may require us to
9122 /// implicitly define the namespace.
9123 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9124   if (!StdNamespace) {
9125     // The "std" namespace has not yet been defined, so build one implicitly.
9126     StdNamespace = NamespaceDecl::Create(Context,
9127                                          Context.getTranslationUnitDecl(),
9128                                          /*Inline=*/false,
9129                                          SourceLocation(), SourceLocation(),
9130                                          &PP.getIdentifierTable().get("std"),
9131                                          /*PrevDecl=*/nullptr);
9132     getStdNamespace()->setImplicit(true);
9133   }
9134 
9135   return getStdNamespace();
9136 }
9137 
9138 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9139   assert(getLangOpts().CPlusPlus &&
9140          "Looking for std::initializer_list outside of C++.");
9141 
9142   // We're looking for implicit instantiations of
9143   // template <typename E> class std::initializer_list.
9144 
9145   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9146     return false;
9147 
9148   ClassTemplateDecl *Template = nullptr;
9149   const TemplateArgument *Arguments = nullptr;
9150 
9151   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9152 
9153     ClassTemplateSpecializationDecl *Specialization =
9154         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9155     if (!Specialization)
9156       return false;
9157 
9158     Template = Specialization->getSpecializedTemplate();
9159     Arguments = Specialization->getTemplateArgs().data();
9160   } else if (const TemplateSpecializationType *TST =
9161                  Ty->getAs<TemplateSpecializationType>()) {
9162     Template = dyn_cast_or_null<ClassTemplateDecl>(
9163         TST->getTemplateName().getAsTemplateDecl());
9164     Arguments = TST->getArgs();
9165   }
9166   if (!Template)
9167     return false;
9168 
9169   if (!StdInitializerList) {
9170     // Haven't recognized std::initializer_list yet, maybe this is it.
9171     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9172     if (TemplateClass->getIdentifier() !=
9173             &PP.getIdentifierTable().get("initializer_list") ||
9174         !getStdNamespace()->InEnclosingNamespaceSetOf(
9175             TemplateClass->getDeclContext()))
9176       return false;
9177     // This is a template called std::initializer_list, but is it the right
9178     // template?
9179     TemplateParameterList *Params = Template->getTemplateParameters();
9180     if (Params->getMinRequiredArguments() != 1)
9181       return false;
9182     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9183       return false;
9184 
9185     // It's the right template.
9186     StdInitializerList = Template;
9187   }
9188 
9189   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9190     return false;
9191 
9192   // This is an instance of std::initializer_list. Find the argument type.
9193   if (Element)
9194     *Element = Arguments[0].getAsType();
9195   return true;
9196 }
9197 
9198 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9199   NamespaceDecl *Std = S.getStdNamespace();
9200   if (!Std) {
9201     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9202     return nullptr;
9203   }
9204 
9205   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9206                       Loc, Sema::LookupOrdinaryName);
9207   if (!S.LookupQualifiedName(Result, Std)) {
9208     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9209     return nullptr;
9210   }
9211   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9212   if (!Template) {
9213     Result.suppressDiagnostics();
9214     // We found something weird. Complain about the first thing we found.
9215     NamedDecl *Found = *Result.begin();
9216     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9217     return nullptr;
9218   }
9219 
9220   // We found some template called std::initializer_list. Now verify that it's
9221   // correct.
9222   TemplateParameterList *Params = Template->getTemplateParameters();
9223   if (Params->getMinRequiredArguments() != 1 ||
9224       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9225     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9226     return nullptr;
9227   }
9228 
9229   return Template;
9230 }
9231 
9232 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9233   if (!StdInitializerList) {
9234     StdInitializerList = LookupStdInitializerList(*this, Loc);
9235     if (!StdInitializerList)
9236       return QualType();
9237   }
9238 
9239   TemplateArgumentListInfo Args(Loc, Loc);
9240   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9241                                        Context.getTrivialTypeSourceInfo(Element,
9242                                                                         Loc)));
9243   return Context.getCanonicalType(
9244       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9245 }
9246 
9247 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9248   // C++ [dcl.init.list]p2:
9249   //   A constructor is an initializer-list constructor if its first parameter
9250   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9251   //   std::initializer_list<E> for some type E, and either there are no other
9252   //   parameters or else all other parameters have default arguments.
9253   if (Ctor->getNumParams() < 1 ||
9254       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9255     return false;
9256 
9257   QualType ArgType = Ctor->getParamDecl(0)->getType();
9258   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9259     ArgType = RT->getPointeeType().getUnqualifiedType();
9260 
9261   return isStdInitializerList(ArgType, nullptr);
9262 }
9263 
9264 /// Determine whether a using statement is in a context where it will be
9265 /// apply in all contexts.
9266 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9267   switch (CurContext->getDeclKind()) {
9268     case Decl::TranslationUnit:
9269       return true;
9270     case Decl::LinkageSpec:
9271       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9272     default:
9273       return false;
9274   }
9275 }
9276 
9277 namespace {
9278 
9279 // Callback to only accept typo corrections that are namespaces.
9280 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9281 public:
9282   bool ValidateCandidate(const TypoCorrection &candidate) override {
9283     if (NamedDecl *ND = candidate.getCorrectionDecl())
9284       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9285     return false;
9286   }
9287 };
9288 
9289 }
9290 
9291 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9292                                        CXXScopeSpec &SS,
9293                                        SourceLocation IdentLoc,
9294                                        IdentifierInfo *Ident) {
9295   R.clear();
9296   if (TypoCorrection Corrected =
9297           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9298                         llvm::make_unique<NamespaceValidatorCCC>(),
9299                         Sema::CTK_ErrorRecovery)) {
9300     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9301       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9302       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9303                               Ident->getName().equals(CorrectedStr);
9304       S.diagnoseTypo(Corrected,
9305                      S.PDiag(diag::err_using_directive_member_suggest)
9306                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9307                      S.PDiag(diag::note_namespace_defined_here));
9308     } else {
9309       S.diagnoseTypo(Corrected,
9310                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9311                      S.PDiag(diag::note_namespace_defined_here));
9312     }
9313     R.addDecl(Corrected.getFoundDecl());
9314     return true;
9315   }
9316   return false;
9317 }
9318 
9319 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9320                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9321                                 SourceLocation IdentLoc,
9322                                 IdentifierInfo *NamespcName,
9323                                 const ParsedAttributesView &AttrList) {
9324   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9325   assert(NamespcName && "Invalid NamespcName.");
9326   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9327 
9328   // This can only happen along a recovery path.
9329   while (S->isTemplateParamScope())
9330     S = S->getParent();
9331   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9332 
9333   UsingDirectiveDecl *UDir = nullptr;
9334   NestedNameSpecifier *Qualifier = nullptr;
9335   if (SS.isSet())
9336     Qualifier = SS.getScopeRep();
9337 
9338   // Lookup namespace name.
9339   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9340   LookupParsedName(R, S, &SS);
9341   if (R.isAmbiguous())
9342     return nullptr;
9343 
9344   if (R.empty()) {
9345     R.clear();
9346     // Allow "using namespace std;" or "using namespace ::std;" even if
9347     // "std" hasn't been defined yet, for GCC compatibility.
9348     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9349         NamespcName->isStr("std")) {
9350       Diag(IdentLoc, diag::ext_using_undefined_std);
9351       R.addDecl(getOrCreateStdNamespace());
9352       R.resolveKind();
9353     }
9354     // Otherwise, attempt typo correction.
9355     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9356   }
9357 
9358   if (!R.empty()) {
9359     NamedDecl *Named = R.getRepresentativeDecl();
9360     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9361     assert(NS && "expected namespace decl");
9362 
9363     // The use of a nested name specifier may trigger deprecation warnings.
9364     DiagnoseUseOfDecl(Named, IdentLoc);
9365 
9366     // C++ [namespace.udir]p1:
9367     //   A using-directive specifies that the names in the nominated
9368     //   namespace can be used in the scope in which the
9369     //   using-directive appears after the using-directive. During
9370     //   unqualified name lookup (3.4.1), the names appear as if they
9371     //   were declared in the nearest enclosing namespace which
9372     //   contains both the using-directive and the nominated
9373     //   namespace. [Note: in this context, "contains" means "contains
9374     //   directly or indirectly". ]
9375 
9376     // Find enclosing context containing both using-directive and
9377     // nominated namespace.
9378     DeclContext *CommonAncestor = NS;
9379     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9380       CommonAncestor = CommonAncestor->getParent();
9381 
9382     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9383                                       SS.getWithLocInContext(Context),
9384                                       IdentLoc, Named, CommonAncestor);
9385 
9386     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9387         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9388       Diag(IdentLoc, diag::warn_using_directive_in_header);
9389     }
9390 
9391     PushUsingDirective(S, UDir);
9392   } else {
9393     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9394   }
9395 
9396   if (UDir)
9397     ProcessDeclAttributeList(S, UDir, AttrList);
9398 
9399   return UDir;
9400 }
9401 
9402 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9403   // If the scope has an associated entity and the using directive is at
9404   // namespace or translation unit scope, add the UsingDirectiveDecl into
9405   // its lookup structure so qualified name lookup can find it.
9406   DeclContext *Ctx = S->getEntity();
9407   if (Ctx && !Ctx->isFunctionOrMethod())
9408     Ctx->addDecl(UDir);
9409   else
9410     // Otherwise, it is at block scope. The using-directives will affect lookup
9411     // only to the end of the scope.
9412     S->PushUsingDirective(UDir);
9413 }
9414 
9415 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9416                                   SourceLocation UsingLoc,
9417                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9418                                   UnqualifiedId &Name,
9419                                   SourceLocation EllipsisLoc,
9420                                   const ParsedAttributesView &AttrList) {
9421   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9422 
9423   if (SS.isEmpty()) {
9424     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9425     return nullptr;
9426   }
9427 
9428   switch (Name.getKind()) {
9429   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9430   case UnqualifiedIdKind::IK_Identifier:
9431   case UnqualifiedIdKind::IK_OperatorFunctionId:
9432   case UnqualifiedIdKind::IK_LiteralOperatorId:
9433   case UnqualifiedIdKind::IK_ConversionFunctionId:
9434     break;
9435 
9436   case UnqualifiedIdKind::IK_ConstructorName:
9437   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9438     // C++11 inheriting constructors.
9439     Diag(Name.getBeginLoc(),
9440          getLangOpts().CPlusPlus11
9441              ? diag::warn_cxx98_compat_using_decl_constructor
9442              : diag::err_using_decl_constructor)
9443         << SS.getRange();
9444 
9445     if (getLangOpts().CPlusPlus11) break;
9446 
9447     return nullptr;
9448 
9449   case UnqualifiedIdKind::IK_DestructorName:
9450     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9451     return nullptr;
9452 
9453   case UnqualifiedIdKind::IK_TemplateId:
9454     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9455         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9456     return nullptr;
9457 
9458   case UnqualifiedIdKind::IK_DeductionGuideName:
9459     llvm_unreachable("cannot parse qualified deduction guide name");
9460   }
9461 
9462   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9463   DeclarationName TargetName = TargetNameInfo.getName();
9464   if (!TargetName)
9465     return nullptr;
9466 
9467   // Warn about access declarations.
9468   if (UsingLoc.isInvalid()) {
9469     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9470                                  ? diag::err_access_decl
9471                                  : diag::warn_access_decl_deprecated)
9472         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9473   }
9474 
9475   if (EllipsisLoc.isInvalid()) {
9476     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9477         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9478       return nullptr;
9479   } else {
9480     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9481         !TargetNameInfo.containsUnexpandedParameterPack()) {
9482       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9483         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9484       EllipsisLoc = SourceLocation();
9485     }
9486   }
9487 
9488   NamedDecl *UD =
9489       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9490                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9491                             /*IsInstantiation*/false);
9492   if (UD)
9493     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9494 
9495   return UD;
9496 }
9497 
9498 /// Determine whether a using declaration considers the given
9499 /// declarations as "equivalent", e.g., if they are redeclarations of
9500 /// the same entity or are both typedefs of the same type.
9501 static bool
9502 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9503   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9504     return true;
9505 
9506   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9507     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9508       return Context.hasSameType(TD1->getUnderlyingType(),
9509                                  TD2->getUnderlyingType());
9510 
9511   return false;
9512 }
9513 
9514 
9515 /// Determines whether to create a using shadow decl for a particular
9516 /// decl, given the set of decls existing prior to this using lookup.
9517 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9518                                 const LookupResult &Previous,
9519                                 UsingShadowDecl *&PrevShadow) {
9520   // Diagnose finding a decl which is not from a base class of the
9521   // current class.  We do this now because there are cases where this
9522   // function will silently decide not to build a shadow decl, which
9523   // will pre-empt further diagnostics.
9524   //
9525   // We don't need to do this in C++11 because we do the check once on
9526   // the qualifier.
9527   //
9528   // FIXME: diagnose the following if we care enough:
9529   //   struct A { int foo; };
9530   //   struct B : A { using A::foo; };
9531   //   template <class T> struct C : A {};
9532   //   template <class T> struct D : C<T> { using B::foo; } // <---
9533   // This is invalid (during instantiation) in C++03 because B::foo
9534   // resolves to the using decl in B, which is not a base class of D<T>.
9535   // We can't diagnose it immediately because C<T> is an unknown
9536   // specialization.  The UsingShadowDecl in D<T> then points directly
9537   // to A::foo, which will look well-formed when we instantiate.
9538   // The right solution is to not collapse the shadow-decl chain.
9539   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9540     DeclContext *OrigDC = Orig->getDeclContext();
9541 
9542     // Handle enums and anonymous structs.
9543     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9544     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9545     while (OrigRec->isAnonymousStructOrUnion())
9546       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9547 
9548     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9549       if (OrigDC == CurContext) {
9550         Diag(Using->getLocation(),
9551              diag::err_using_decl_nested_name_specifier_is_current_class)
9552           << Using->getQualifierLoc().getSourceRange();
9553         Diag(Orig->getLocation(), diag::note_using_decl_target);
9554         Using->setInvalidDecl();
9555         return true;
9556       }
9557 
9558       Diag(Using->getQualifierLoc().getBeginLoc(),
9559            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9560         << Using->getQualifier()
9561         << cast<CXXRecordDecl>(CurContext)
9562         << Using->getQualifierLoc().getSourceRange();
9563       Diag(Orig->getLocation(), diag::note_using_decl_target);
9564       Using->setInvalidDecl();
9565       return true;
9566     }
9567   }
9568 
9569   if (Previous.empty()) return false;
9570 
9571   NamedDecl *Target = Orig;
9572   if (isa<UsingShadowDecl>(Target))
9573     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9574 
9575   // If the target happens to be one of the previous declarations, we
9576   // don't have a conflict.
9577   //
9578   // FIXME: but we might be increasing its access, in which case we
9579   // should redeclare it.
9580   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9581   bool FoundEquivalentDecl = false;
9582   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9583          I != E; ++I) {
9584     NamedDecl *D = (*I)->getUnderlyingDecl();
9585     // We can have UsingDecls in our Previous results because we use the same
9586     // LookupResult for checking whether the UsingDecl itself is a valid
9587     // redeclaration.
9588     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9589       continue;
9590 
9591     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9592       // C++ [class.mem]p19:
9593       //   If T is the name of a class, then [every named member other than
9594       //   a non-static data member] shall have a name different from T
9595       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9596           !isa<IndirectFieldDecl>(Target) &&
9597           !isa<UnresolvedUsingValueDecl>(Target) &&
9598           DiagnoseClassNameShadow(
9599               CurContext,
9600               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9601         return true;
9602     }
9603 
9604     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9605       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9606         PrevShadow = Shadow;
9607       FoundEquivalentDecl = true;
9608     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9609       // We don't conflict with an existing using shadow decl of an equivalent
9610       // declaration, but we're not a redeclaration of it.
9611       FoundEquivalentDecl = true;
9612     }
9613 
9614     if (isVisible(D))
9615       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9616   }
9617 
9618   if (FoundEquivalentDecl)
9619     return false;
9620 
9621   if (FunctionDecl *FD = Target->getAsFunction()) {
9622     NamedDecl *OldDecl = nullptr;
9623     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9624                           /*IsForUsingDecl*/ true)) {
9625     case Ovl_Overload:
9626       return false;
9627 
9628     case Ovl_NonFunction:
9629       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9630       break;
9631 
9632     // We found a decl with the exact signature.
9633     case Ovl_Match:
9634       // If we're in a record, we want to hide the target, so we
9635       // return true (without a diagnostic) to tell the caller not to
9636       // build a shadow decl.
9637       if (CurContext->isRecord())
9638         return true;
9639 
9640       // If we're not in a record, this is an error.
9641       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9642       break;
9643     }
9644 
9645     Diag(Target->getLocation(), diag::note_using_decl_target);
9646     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9647     Using->setInvalidDecl();
9648     return true;
9649   }
9650 
9651   // Target is not a function.
9652 
9653   if (isa<TagDecl>(Target)) {
9654     // No conflict between a tag and a non-tag.
9655     if (!Tag) return false;
9656 
9657     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9658     Diag(Target->getLocation(), diag::note_using_decl_target);
9659     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9660     Using->setInvalidDecl();
9661     return true;
9662   }
9663 
9664   // No conflict between a tag and a non-tag.
9665   if (!NonTag) return false;
9666 
9667   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9668   Diag(Target->getLocation(), diag::note_using_decl_target);
9669   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9670   Using->setInvalidDecl();
9671   return true;
9672 }
9673 
9674 /// Determine whether a direct base class is a virtual base class.
9675 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9676   if (!Derived->getNumVBases())
9677     return false;
9678   for (auto &B : Derived->bases())
9679     if (B.getType()->getAsCXXRecordDecl() == Base)
9680       return B.isVirtual();
9681   llvm_unreachable("not a direct base class");
9682 }
9683 
9684 /// Builds a shadow declaration corresponding to a 'using' declaration.
9685 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9686                                             UsingDecl *UD,
9687                                             NamedDecl *Orig,
9688                                             UsingShadowDecl *PrevDecl) {
9689   // If we resolved to another shadow declaration, just coalesce them.
9690   NamedDecl *Target = Orig;
9691   if (isa<UsingShadowDecl>(Target)) {
9692     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9693     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9694   }
9695 
9696   NamedDecl *NonTemplateTarget = Target;
9697   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9698     NonTemplateTarget = TargetTD->getTemplatedDecl();
9699 
9700   UsingShadowDecl *Shadow;
9701   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9702     bool IsVirtualBase =
9703         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9704                             UD->getQualifier()->getAsRecordDecl());
9705     Shadow = ConstructorUsingShadowDecl::Create(
9706         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9707   } else {
9708     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9709                                      Target);
9710   }
9711   UD->addShadowDecl(Shadow);
9712 
9713   Shadow->setAccess(UD->getAccess());
9714   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9715     Shadow->setInvalidDecl();
9716 
9717   Shadow->setPreviousDecl(PrevDecl);
9718 
9719   if (S)
9720     PushOnScopeChains(Shadow, S);
9721   else
9722     CurContext->addDecl(Shadow);
9723 
9724 
9725   return Shadow;
9726 }
9727 
9728 /// Hides a using shadow declaration.  This is required by the current
9729 /// using-decl implementation when a resolvable using declaration in a
9730 /// class is followed by a declaration which would hide or override
9731 /// one or more of the using decl's targets; for example:
9732 ///
9733 ///   struct Base { void foo(int); };
9734 ///   struct Derived : Base {
9735 ///     using Base::foo;
9736 ///     void foo(int);
9737 ///   };
9738 ///
9739 /// The governing language is C++03 [namespace.udecl]p12:
9740 ///
9741 ///   When a using-declaration brings names from a base class into a
9742 ///   derived class scope, member functions in the derived class
9743 ///   override and/or hide member functions with the same name and
9744 ///   parameter types in a base class (rather than conflicting).
9745 ///
9746 /// There are two ways to implement this:
9747 ///   (1) optimistically create shadow decls when they're not hidden
9748 ///       by existing declarations, or
9749 ///   (2) don't create any shadow decls (or at least don't make them
9750 ///       visible) until we've fully parsed/instantiated the class.
9751 /// The problem with (1) is that we might have to retroactively remove
9752 /// a shadow decl, which requires several O(n) operations because the
9753 /// decl structures are (very reasonably) not designed for removal.
9754 /// (2) avoids this but is very fiddly and phase-dependent.
9755 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9756   if (Shadow->getDeclName().getNameKind() ==
9757         DeclarationName::CXXConversionFunctionName)
9758     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9759 
9760   // Remove it from the DeclContext...
9761   Shadow->getDeclContext()->removeDecl(Shadow);
9762 
9763   // ...and the scope, if applicable...
9764   if (S) {
9765     S->RemoveDecl(Shadow);
9766     IdResolver.RemoveDecl(Shadow);
9767   }
9768 
9769   // ...and the using decl.
9770   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9771 
9772   // TODO: complain somehow if Shadow was used.  It shouldn't
9773   // be possible for this to happen, because...?
9774 }
9775 
9776 /// Find the base specifier for a base class with the given type.
9777 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9778                                                 QualType DesiredBase,
9779                                                 bool &AnyDependentBases) {
9780   // Check whether the named type is a direct base class.
9781   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9782   for (auto &Base : Derived->bases()) {
9783     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9784     if (CanonicalDesiredBase == BaseType)
9785       return &Base;
9786     if (BaseType->isDependentType())
9787       AnyDependentBases = true;
9788   }
9789   return nullptr;
9790 }
9791 
9792 namespace {
9793 class UsingValidatorCCC : public CorrectionCandidateCallback {
9794 public:
9795   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9796                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9797       : HasTypenameKeyword(HasTypenameKeyword),
9798         IsInstantiation(IsInstantiation), OldNNS(NNS),
9799         RequireMemberOf(RequireMemberOf) {}
9800 
9801   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9802     NamedDecl *ND = Candidate.getCorrectionDecl();
9803 
9804     // Keywords are not valid here.
9805     if (!ND || isa<NamespaceDecl>(ND))
9806       return false;
9807 
9808     // Completely unqualified names are invalid for a 'using' declaration.
9809     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9810       return false;
9811 
9812     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9813     // reject.
9814 
9815     if (RequireMemberOf) {
9816       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9817       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9818         // No-one ever wants a using-declaration to name an injected-class-name
9819         // of a base class, unless they're declaring an inheriting constructor.
9820         ASTContext &Ctx = ND->getASTContext();
9821         if (!Ctx.getLangOpts().CPlusPlus11)
9822           return false;
9823         QualType FoundType = Ctx.getRecordType(FoundRecord);
9824 
9825         // Check that the injected-class-name is named as a member of its own
9826         // type; we don't want to suggest 'using Derived::Base;', since that
9827         // means something else.
9828         NestedNameSpecifier *Specifier =
9829             Candidate.WillReplaceSpecifier()
9830                 ? Candidate.getCorrectionSpecifier()
9831                 : OldNNS;
9832         if (!Specifier->getAsType() ||
9833             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9834           return false;
9835 
9836         // Check that this inheriting constructor declaration actually names a
9837         // direct base class of the current class.
9838         bool AnyDependentBases = false;
9839         if (!findDirectBaseWithType(RequireMemberOf,
9840                                     Ctx.getRecordType(FoundRecord),
9841                                     AnyDependentBases) &&
9842             !AnyDependentBases)
9843           return false;
9844       } else {
9845         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9846         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9847           return false;
9848 
9849         // FIXME: Check that the base class member is accessible?
9850       }
9851     } else {
9852       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9853       if (FoundRecord && FoundRecord->isInjectedClassName())
9854         return false;
9855     }
9856 
9857     if (isa<TypeDecl>(ND))
9858       return HasTypenameKeyword || !IsInstantiation;
9859 
9860     return !HasTypenameKeyword;
9861   }
9862 
9863 private:
9864   bool HasTypenameKeyword;
9865   bool IsInstantiation;
9866   NestedNameSpecifier *OldNNS;
9867   CXXRecordDecl *RequireMemberOf;
9868 };
9869 } // end anonymous namespace
9870 
9871 /// Builds a using declaration.
9872 ///
9873 /// \param IsInstantiation - Whether this call arises from an
9874 ///   instantiation of an unresolved using declaration.  We treat
9875 ///   the lookup differently for these declarations.
9876 NamedDecl *Sema::BuildUsingDeclaration(
9877     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9878     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9879     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9880     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9881   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9882   SourceLocation IdentLoc = NameInfo.getLoc();
9883   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9884 
9885   // FIXME: We ignore attributes for now.
9886 
9887   // For an inheriting constructor declaration, the name of the using
9888   // declaration is the name of a constructor in this class, not in the
9889   // base class.
9890   DeclarationNameInfo UsingName = NameInfo;
9891   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9892     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9893       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9894           Context.getCanonicalType(Context.getRecordType(RD))));
9895 
9896   // Do the redeclaration lookup in the current scope.
9897   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9898                         ForVisibleRedeclaration);
9899   Previous.setHideTags(false);
9900   if (S) {
9901     LookupName(Previous, S);
9902 
9903     // It is really dumb that we have to do this.
9904     LookupResult::Filter F = Previous.makeFilter();
9905     while (F.hasNext()) {
9906       NamedDecl *D = F.next();
9907       if (!isDeclInScope(D, CurContext, S))
9908         F.erase();
9909       // If we found a local extern declaration that's not ordinarily visible,
9910       // and this declaration is being added to a non-block scope, ignore it.
9911       // We're only checking for scope conflicts here, not also for violations
9912       // of the linkage rules.
9913       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9914                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9915         F.erase();
9916     }
9917     F.done();
9918   } else {
9919     assert(IsInstantiation && "no scope in non-instantiation");
9920     if (CurContext->isRecord())
9921       LookupQualifiedName(Previous, CurContext);
9922     else {
9923       // No redeclaration check is needed here; in non-member contexts we
9924       // diagnosed all possible conflicts with other using-declarations when
9925       // building the template:
9926       //
9927       // For a dependent non-type using declaration, the only valid case is
9928       // if we instantiate to a single enumerator. We check for conflicts
9929       // between shadow declarations we introduce, and we check in the template
9930       // definition for conflicts between a non-type using declaration and any
9931       // other declaration, which together covers all cases.
9932       //
9933       // A dependent typename using declaration will never successfully
9934       // instantiate, since it will always name a class member, so we reject
9935       // that in the template definition.
9936     }
9937   }
9938 
9939   // Check for invalid redeclarations.
9940   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9941                                   SS, IdentLoc, Previous))
9942     return nullptr;
9943 
9944   // Check for bad qualifiers.
9945   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9946                               IdentLoc))
9947     return nullptr;
9948 
9949   DeclContext *LookupContext = computeDeclContext(SS);
9950   NamedDecl *D;
9951   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9952   if (!LookupContext || EllipsisLoc.isValid()) {
9953     if (HasTypenameKeyword) {
9954       // FIXME: not all declaration name kinds are legal here
9955       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9956                                               UsingLoc, TypenameLoc,
9957                                               QualifierLoc,
9958                                               IdentLoc, NameInfo.getName(),
9959                                               EllipsisLoc);
9960     } else {
9961       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9962                                            QualifierLoc, NameInfo, EllipsisLoc);
9963     }
9964     D->setAccess(AS);
9965     CurContext->addDecl(D);
9966     return D;
9967   }
9968 
9969   auto Build = [&](bool Invalid) {
9970     UsingDecl *UD =
9971         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9972                           UsingName, HasTypenameKeyword);
9973     UD->setAccess(AS);
9974     CurContext->addDecl(UD);
9975     UD->setInvalidDecl(Invalid);
9976     return UD;
9977   };
9978   auto BuildInvalid = [&]{ return Build(true); };
9979   auto BuildValid = [&]{ return Build(false); };
9980 
9981   if (RequireCompleteDeclContext(SS, LookupContext))
9982     return BuildInvalid();
9983 
9984   // Look up the target name.
9985   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9986 
9987   // Unlike most lookups, we don't always want to hide tag
9988   // declarations: tag names are visible through the using declaration
9989   // even if hidden by ordinary names, *except* in a dependent context
9990   // where it's important for the sanity of two-phase lookup.
9991   if (!IsInstantiation)
9992     R.setHideTags(false);
9993 
9994   // For the purposes of this lookup, we have a base object type
9995   // equal to that of the current context.
9996   if (CurContext->isRecord()) {
9997     R.setBaseObjectType(
9998                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9999   }
10000 
10001   LookupQualifiedName(R, LookupContext);
10002 
10003   // Try to correct typos if possible. If constructor name lookup finds no
10004   // results, that means the named class has no explicit constructors, and we
10005   // suppressed declaring implicit ones (probably because it's dependent or
10006   // invalid).
10007   if (R.empty() &&
10008       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10009     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10010     // it will believe that glibc provides a ::gets in cases where it does not,
10011     // and will try to pull it into namespace std with a using-declaration.
10012     // Just ignore the using-declaration in that case.
10013     auto *II = NameInfo.getName().getAsIdentifierInfo();
10014     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10015         CurContext->isStdNamespace() &&
10016         isa<TranslationUnitDecl>(LookupContext) &&
10017         getSourceManager().isInSystemHeader(UsingLoc))
10018       return nullptr;
10019     if (TypoCorrection Corrected = CorrectTypo(
10020             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
10021             llvm::make_unique<UsingValidatorCCC>(
10022                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10023                 dyn_cast<CXXRecordDecl>(CurContext)),
10024             CTK_ErrorRecovery)) {
10025       // We reject candidates where DroppedSpecifier == true, hence the
10026       // literal '0' below.
10027       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10028                                 << NameInfo.getName() << LookupContext << 0
10029                                 << SS.getRange());
10030 
10031       // If we picked a correction with no attached Decl we can't do anything
10032       // useful with it, bail out.
10033       NamedDecl *ND = Corrected.getCorrectionDecl();
10034       if (!ND)
10035         return BuildInvalid();
10036 
10037       // If we corrected to an inheriting constructor, handle it as one.
10038       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10039       if (RD && RD->isInjectedClassName()) {
10040         // The parent of the injected class name is the class itself.
10041         RD = cast<CXXRecordDecl>(RD->getParent());
10042 
10043         // Fix up the information we'll use to build the using declaration.
10044         if (Corrected.WillReplaceSpecifier()) {
10045           NestedNameSpecifierLocBuilder Builder;
10046           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10047                               QualifierLoc.getSourceRange());
10048           QualifierLoc = Builder.getWithLocInContext(Context);
10049         }
10050 
10051         // In this case, the name we introduce is the name of a derived class
10052         // constructor.
10053         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10054         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10055             Context.getCanonicalType(Context.getRecordType(CurClass))));
10056         UsingName.setNamedTypeInfo(nullptr);
10057         for (auto *Ctor : LookupConstructors(RD))
10058           R.addDecl(Ctor);
10059         R.resolveKind();
10060       } else {
10061         // FIXME: Pick up all the declarations if we found an overloaded
10062         // function.
10063         UsingName.setName(ND->getDeclName());
10064         R.addDecl(ND);
10065       }
10066     } else {
10067       Diag(IdentLoc, diag::err_no_member)
10068         << NameInfo.getName() << LookupContext << SS.getRange();
10069       return BuildInvalid();
10070     }
10071   }
10072 
10073   if (R.isAmbiguous())
10074     return BuildInvalid();
10075 
10076   if (HasTypenameKeyword) {
10077     // If we asked for a typename and got a non-type decl, error out.
10078     if (!R.getAsSingle<TypeDecl>()) {
10079       Diag(IdentLoc, diag::err_using_typename_non_type);
10080       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10081         Diag((*I)->getUnderlyingDecl()->getLocation(),
10082              diag::note_using_decl_target);
10083       return BuildInvalid();
10084     }
10085   } else {
10086     // If we asked for a non-typename and we got a type, error out,
10087     // but only if this is an instantiation of an unresolved using
10088     // decl.  Otherwise just silently find the type name.
10089     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10090       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10091       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10092       return BuildInvalid();
10093     }
10094   }
10095 
10096   // C++14 [namespace.udecl]p6:
10097   // A using-declaration shall not name a namespace.
10098   if (R.getAsSingle<NamespaceDecl>()) {
10099     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10100       << SS.getRange();
10101     return BuildInvalid();
10102   }
10103 
10104   // C++14 [namespace.udecl]p7:
10105   // A using-declaration shall not name a scoped enumerator.
10106   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10107     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10108       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10109         << SS.getRange();
10110       return BuildInvalid();
10111     }
10112   }
10113 
10114   UsingDecl *UD = BuildValid();
10115 
10116   // Some additional rules apply to inheriting constructors.
10117   if (UsingName.getName().getNameKind() ==
10118         DeclarationName::CXXConstructorName) {
10119     // Suppress access diagnostics; the access check is instead performed at the
10120     // point of use for an inheriting constructor.
10121     R.suppressDiagnostics();
10122     if (CheckInheritingConstructorUsingDecl(UD))
10123       return UD;
10124   }
10125 
10126   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10127     UsingShadowDecl *PrevDecl = nullptr;
10128     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10129       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10130   }
10131 
10132   return UD;
10133 }
10134 
10135 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10136                                     ArrayRef<NamedDecl *> Expansions) {
10137   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10138          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10139          isa<UsingPackDecl>(InstantiatedFrom));
10140 
10141   auto *UPD =
10142       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10143   UPD->setAccess(InstantiatedFrom->getAccess());
10144   CurContext->addDecl(UPD);
10145   return UPD;
10146 }
10147 
10148 /// Additional checks for a using declaration referring to a constructor name.
10149 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10150   assert(!UD->hasTypename() && "expecting a constructor name");
10151 
10152   const Type *SourceType = UD->getQualifier()->getAsType();
10153   assert(SourceType &&
10154          "Using decl naming constructor doesn't have type in scope spec.");
10155   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10156 
10157   // Check whether the named type is a direct base class.
10158   bool AnyDependentBases = false;
10159   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10160                                       AnyDependentBases);
10161   if (!Base && !AnyDependentBases) {
10162     Diag(UD->getUsingLoc(),
10163          diag::err_using_decl_constructor_not_in_direct_base)
10164       << UD->getNameInfo().getSourceRange()
10165       << QualType(SourceType, 0) << TargetClass;
10166     UD->setInvalidDecl();
10167     return true;
10168   }
10169 
10170   if (Base)
10171     Base->setInheritConstructors();
10172 
10173   return false;
10174 }
10175 
10176 /// Checks that the given using declaration is not an invalid
10177 /// redeclaration.  Note that this is checking only for the using decl
10178 /// itself, not for any ill-formedness among the UsingShadowDecls.
10179 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10180                                        bool HasTypenameKeyword,
10181                                        const CXXScopeSpec &SS,
10182                                        SourceLocation NameLoc,
10183                                        const LookupResult &Prev) {
10184   NestedNameSpecifier *Qual = SS.getScopeRep();
10185 
10186   // C++03 [namespace.udecl]p8:
10187   // C++0x [namespace.udecl]p10:
10188   //   A using-declaration is a declaration and can therefore be used
10189   //   repeatedly where (and only where) multiple declarations are
10190   //   allowed.
10191   //
10192   // That's in non-member contexts.
10193   if (!CurContext->getRedeclContext()->isRecord()) {
10194     // A dependent qualifier outside a class can only ever resolve to an
10195     // enumeration type. Therefore it conflicts with any other non-type
10196     // declaration in the same scope.
10197     // FIXME: How should we check for dependent type-type conflicts at block
10198     // scope?
10199     if (Qual->isDependent() && !HasTypenameKeyword) {
10200       for (auto *D : Prev) {
10201         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10202           bool OldCouldBeEnumerator =
10203               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10204           Diag(NameLoc,
10205                OldCouldBeEnumerator ? diag::err_redefinition
10206                                     : diag::err_redefinition_different_kind)
10207               << Prev.getLookupName();
10208           Diag(D->getLocation(), diag::note_previous_definition);
10209           return true;
10210         }
10211       }
10212     }
10213     return false;
10214   }
10215 
10216   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10217     NamedDecl *D = *I;
10218 
10219     bool DTypename;
10220     NestedNameSpecifier *DQual;
10221     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10222       DTypename = UD->hasTypename();
10223       DQual = UD->getQualifier();
10224     } else if (UnresolvedUsingValueDecl *UD
10225                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10226       DTypename = false;
10227       DQual = UD->getQualifier();
10228     } else if (UnresolvedUsingTypenameDecl *UD
10229                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10230       DTypename = true;
10231       DQual = UD->getQualifier();
10232     } else continue;
10233 
10234     // using decls differ if one says 'typename' and the other doesn't.
10235     // FIXME: non-dependent using decls?
10236     if (HasTypenameKeyword != DTypename) continue;
10237 
10238     // using decls differ if they name different scopes (but note that
10239     // template instantiation can cause this check to trigger when it
10240     // didn't before instantiation).
10241     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10242         Context.getCanonicalNestedNameSpecifier(DQual))
10243       continue;
10244 
10245     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10246     Diag(D->getLocation(), diag::note_using_decl) << 1;
10247     return true;
10248   }
10249 
10250   return false;
10251 }
10252 
10253 
10254 /// Checks that the given nested-name qualifier used in a using decl
10255 /// in the current context is appropriately related to the current
10256 /// scope.  If an error is found, diagnoses it and returns true.
10257 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10258                                    bool HasTypename,
10259                                    const CXXScopeSpec &SS,
10260                                    const DeclarationNameInfo &NameInfo,
10261                                    SourceLocation NameLoc) {
10262   DeclContext *NamedContext = computeDeclContext(SS);
10263 
10264   if (!CurContext->isRecord()) {
10265     // C++03 [namespace.udecl]p3:
10266     // C++0x [namespace.udecl]p8:
10267     //   A using-declaration for a class member shall be a member-declaration.
10268 
10269     // If we weren't able to compute a valid scope, it might validly be a
10270     // dependent class scope or a dependent enumeration unscoped scope. If
10271     // we have a 'typename' keyword, the scope must resolve to a class type.
10272     if ((HasTypename && !NamedContext) ||
10273         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10274       auto *RD = NamedContext
10275                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10276                      : nullptr;
10277       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10278         RD = nullptr;
10279 
10280       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10281         << SS.getRange();
10282 
10283       // If we have a complete, non-dependent source type, try to suggest a
10284       // way to get the same effect.
10285       if (!RD)
10286         return true;
10287 
10288       // Find what this using-declaration was referring to.
10289       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10290       R.setHideTags(false);
10291       R.suppressDiagnostics();
10292       LookupQualifiedName(R, RD);
10293 
10294       if (R.getAsSingle<TypeDecl>()) {
10295         if (getLangOpts().CPlusPlus11) {
10296           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10297           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10298             << 0 // alias declaration
10299             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10300                                           NameInfo.getName().getAsString() +
10301                                               " = ");
10302         } else {
10303           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10304           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10305           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10306             << 1 // typedef declaration
10307             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10308             << FixItHint::CreateInsertion(
10309                    InsertLoc, " " + NameInfo.getName().getAsString());
10310         }
10311       } else if (R.getAsSingle<VarDecl>()) {
10312         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10313         // repeating the type of the static data member here.
10314         FixItHint FixIt;
10315         if (getLangOpts().CPlusPlus11) {
10316           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10317           FixIt = FixItHint::CreateReplacement(
10318               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10319         }
10320 
10321         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10322           << 2 // reference declaration
10323           << FixIt;
10324       } else if (R.getAsSingle<EnumConstantDecl>()) {
10325         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10326         // repeating the type of the enumeration here, and we can't do so if
10327         // the type is anonymous.
10328         FixItHint FixIt;
10329         if (getLangOpts().CPlusPlus11) {
10330           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10331           FixIt = FixItHint::CreateReplacement(
10332               UsingLoc,
10333               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10334         }
10335 
10336         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10337           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10338           << FixIt;
10339       }
10340       return true;
10341     }
10342 
10343     // Otherwise, this might be valid.
10344     return false;
10345   }
10346 
10347   // The current scope is a record.
10348 
10349   // If the named context is dependent, we can't decide much.
10350   if (!NamedContext) {
10351     // FIXME: in C++0x, we can diagnose if we can prove that the
10352     // nested-name-specifier does not refer to a base class, which is
10353     // still possible in some cases.
10354 
10355     // Otherwise we have to conservatively report that things might be
10356     // okay.
10357     return false;
10358   }
10359 
10360   if (!NamedContext->isRecord()) {
10361     // Ideally this would point at the last name in the specifier,
10362     // but we don't have that level of source info.
10363     Diag(SS.getRange().getBegin(),
10364          diag::err_using_decl_nested_name_specifier_is_not_class)
10365       << SS.getScopeRep() << SS.getRange();
10366     return true;
10367   }
10368 
10369   if (!NamedContext->isDependentContext() &&
10370       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10371     return true;
10372 
10373   if (getLangOpts().CPlusPlus11) {
10374     // C++11 [namespace.udecl]p3:
10375     //   In a using-declaration used as a member-declaration, the
10376     //   nested-name-specifier shall name a base class of the class
10377     //   being defined.
10378 
10379     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10380                                  cast<CXXRecordDecl>(NamedContext))) {
10381       if (CurContext == NamedContext) {
10382         Diag(NameLoc,
10383              diag::err_using_decl_nested_name_specifier_is_current_class)
10384           << SS.getRange();
10385         return true;
10386       }
10387 
10388       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10389         Diag(SS.getRange().getBegin(),
10390              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10391           << SS.getScopeRep()
10392           << cast<CXXRecordDecl>(CurContext)
10393           << SS.getRange();
10394       }
10395       return true;
10396     }
10397 
10398     return false;
10399   }
10400 
10401   // C++03 [namespace.udecl]p4:
10402   //   A using-declaration used as a member-declaration shall refer
10403   //   to a member of a base class of the class being defined [etc.].
10404 
10405   // Salient point: SS doesn't have to name a base class as long as
10406   // lookup only finds members from base classes.  Therefore we can
10407   // diagnose here only if we can prove that that can't happen,
10408   // i.e. if the class hierarchies provably don't intersect.
10409 
10410   // TODO: it would be nice if "definitely valid" results were cached
10411   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10412   // need to be repeated.
10413 
10414   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10415   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10416     Bases.insert(Base);
10417     return true;
10418   };
10419 
10420   // Collect all bases. Return false if we find a dependent base.
10421   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10422     return false;
10423 
10424   // Returns true if the base is dependent or is one of the accumulated base
10425   // classes.
10426   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10427     return !Bases.count(Base);
10428   };
10429 
10430   // Return false if the class has a dependent base or if it or one
10431   // of its bases is present in the base set of the current context.
10432   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10433       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10434     return false;
10435 
10436   Diag(SS.getRange().getBegin(),
10437        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10438     << SS.getScopeRep()
10439     << cast<CXXRecordDecl>(CurContext)
10440     << SS.getRange();
10441 
10442   return true;
10443 }
10444 
10445 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10446                                   MultiTemplateParamsArg TemplateParamLists,
10447                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10448                                   const ParsedAttributesView &AttrList,
10449                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10450   // Skip up to the relevant declaration scope.
10451   while (S->isTemplateParamScope())
10452     S = S->getParent();
10453   assert((S->getFlags() & Scope::DeclScope) &&
10454          "got alias-declaration outside of declaration scope");
10455 
10456   if (Type.isInvalid())
10457     return nullptr;
10458 
10459   bool Invalid = false;
10460   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10461   TypeSourceInfo *TInfo = nullptr;
10462   GetTypeFromParser(Type.get(), &TInfo);
10463 
10464   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10465     return nullptr;
10466 
10467   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10468                                       UPPC_DeclarationType)) {
10469     Invalid = true;
10470     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10471                                              TInfo->getTypeLoc().getBeginLoc());
10472   }
10473 
10474   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10475                         TemplateParamLists.size()
10476                             ? forRedeclarationInCurContext()
10477                             : ForVisibleRedeclaration);
10478   LookupName(Previous, S);
10479 
10480   // Warn about shadowing the name of a template parameter.
10481   if (Previous.isSingleResult() &&
10482       Previous.getFoundDecl()->isTemplateParameter()) {
10483     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10484     Previous.clear();
10485   }
10486 
10487   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10488          "name in alias declaration must be an identifier");
10489   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10490                                                Name.StartLocation,
10491                                                Name.Identifier, TInfo);
10492 
10493   NewTD->setAccess(AS);
10494 
10495   if (Invalid)
10496     NewTD->setInvalidDecl();
10497 
10498   ProcessDeclAttributeList(S, NewTD, AttrList);
10499   AddPragmaAttributes(S, NewTD);
10500 
10501   CheckTypedefForVariablyModifiedType(S, NewTD);
10502   Invalid |= NewTD->isInvalidDecl();
10503 
10504   bool Redeclaration = false;
10505 
10506   NamedDecl *NewND;
10507   if (TemplateParamLists.size()) {
10508     TypeAliasTemplateDecl *OldDecl = nullptr;
10509     TemplateParameterList *OldTemplateParams = nullptr;
10510 
10511     if (TemplateParamLists.size() != 1) {
10512       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10513         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10514          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10515     }
10516     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10517 
10518     // Check that we can declare a template here.
10519     if (CheckTemplateDeclScope(S, TemplateParams))
10520       return nullptr;
10521 
10522     // Only consider previous declarations in the same scope.
10523     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10524                          /*ExplicitInstantiationOrSpecialization*/false);
10525     if (!Previous.empty()) {
10526       Redeclaration = true;
10527 
10528       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10529       if (!OldDecl && !Invalid) {
10530         Diag(UsingLoc, diag::err_redefinition_different_kind)
10531           << Name.Identifier;
10532 
10533         NamedDecl *OldD = Previous.getRepresentativeDecl();
10534         if (OldD->getLocation().isValid())
10535           Diag(OldD->getLocation(), diag::note_previous_definition);
10536 
10537         Invalid = true;
10538       }
10539 
10540       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10541         if (TemplateParameterListsAreEqual(TemplateParams,
10542                                            OldDecl->getTemplateParameters(),
10543                                            /*Complain=*/true,
10544                                            TPL_TemplateMatch))
10545           OldTemplateParams =
10546               OldDecl->getMostRecentDecl()->getTemplateParameters();
10547         else
10548           Invalid = true;
10549 
10550         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10551         if (!Invalid &&
10552             !Context.hasSameType(OldTD->getUnderlyingType(),
10553                                  NewTD->getUnderlyingType())) {
10554           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10555           // but we can't reasonably accept it.
10556           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10557             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10558           if (OldTD->getLocation().isValid())
10559             Diag(OldTD->getLocation(), diag::note_previous_definition);
10560           Invalid = true;
10561         }
10562       }
10563     }
10564 
10565     // Merge any previous default template arguments into our parameters,
10566     // and check the parameter list.
10567     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10568                                    TPC_TypeAliasTemplate))
10569       return nullptr;
10570 
10571     TypeAliasTemplateDecl *NewDecl =
10572       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10573                                     Name.Identifier, TemplateParams,
10574                                     NewTD);
10575     NewTD->setDescribedAliasTemplate(NewDecl);
10576 
10577     NewDecl->setAccess(AS);
10578 
10579     if (Invalid)
10580       NewDecl->setInvalidDecl();
10581     else if (OldDecl) {
10582       NewDecl->setPreviousDecl(OldDecl);
10583       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10584     }
10585 
10586     NewND = NewDecl;
10587   } else {
10588     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10589       setTagNameForLinkagePurposes(TD, NewTD);
10590       handleTagNumbering(TD, S);
10591     }
10592     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10593     NewND = NewTD;
10594   }
10595 
10596   PushOnScopeChains(NewND, S);
10597   ActOnDocumentableDecl(NewND);
10598   return NewND;
10599 }
10600 
10601 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10602                                    SourceLocation AliasLoc,
10603                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10604                                    SourceLocation IdentLoc,
10605                                    IdentifierInfo *Ident) {
10606 
10607   // Lookup the namespace name.
10608   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10609   LookupParsedName(R, S, &SS);
10610 
10611   if (R.isAmbiguous())
10612     return nullptr;
10613 
10614   if (R.empty()) {
10615     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10616       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10617       return nullptr;
10618     }
10619   }
10620   assert(!R.isAmbiguous() && !R.empty());
10621   NamedDecl *ND = R.getRepresentativeDecl();
10622 
10623   // Check if we have a previous declaration with the same name.
10624   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10625                      ForVisibleRedeclaration);
10626   LookupName(PrevR, S);
10627 
10628   // Check we're not shadowing a template parameter.
10629   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10630     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10631     PrevR.clear();
10632   }
10633 
10634   // Filter out any other lookup result from an enclosing scope.
10635   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10636                        /*AllowInlineNamespace*/false);
10637 
10638   // Find the previous declaration and check that we can redeclare it.
10639   NamespaceAliasDecl *Prev = nullptr;
10640   if (PrevR.isSingleResult()) {
10641     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10642     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10643       // We already have an alias with the same name that points to the same
10644       // namespace; check that it matches.
10645       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10646         Prev = AD;
10647       } else if (isVisible(PrevDecl)) {
10648         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10649           << Alias;
10650         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10651           << AD->getNamespace();
10652         return nullptr;
10653       }
10654     } else if (isVisible(PrevDecl)) {
10655       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10656                             ? diag::err_redefinition
10657                             : diag::err_redefinition_different_kind;
10658       Diag(AliasLoc, DiagID) << Alias;
10659       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10660       return nullptr;
10661     }
10662   }
10663 
10664   // The use of a nested name specifier may trigger deprecation warnings.
10665   DiagnoseUseOfDecl(ND, IdentLoc);
10666 
10667   NamespaceAliasDecl *AliasDecl =
10668     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10669                                Alias, SS.getWithLocInContext(Context),
10670                                IdentLoc, ND);
10671   if (Prev)
10672     AliasDecl->setPreviousDecl(Prev);
10673 
10674   PushOnScopeChains(AliasDecl, S);
10675   return AliasDecl;
10676 }
10677 
10678 namespace {
10679 struct SpecialMemberExceptionSpecInfo
10680     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10681   SourceLocation Loc;
10682   Sema::ImplicitExceptionSpecification ExceptSpec;
10683 
10684   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10685                                  Sema::CXXSpecialMember CSM,
10686                                  Sema::InheritedConstructorInfo *ICI,
10687                                  SourceLocation Loc)
10688       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10689 
10690   bool visitBase(CXXBaseSpecifier *Base);
10691   bool visitField(FieldDecl *FD);
10692 
10693   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10694                            unsigned Quals);
10695 
10696   void visitSubobjectCall(Subobject Subobj,
10697                           Sema::SpecialMemberOverloadResult SMOR);
10698 };
10699 }
10700 
10701 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10702   auto *RT = Base->getType()->getAs<RecordType>();
10703   if (!RT)
10704     return false;
10705 
10706   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10707   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10708   if (auto *BaseCtor = SMOR.getMethod()) {
10709     visitSubobjectCall(Base, BaseCtor);
10710     return false;
10711   }
10712 
10713   visitClassSubobject(BaseClass, Base, 0);
10714   return false;
10715 }
10716 
10717 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10718   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10719     Expr *E = FD->getInClassInitializer();
10720     if (!E)
10721       // FIXME: It's a little wasteful to build and throw away a
10722       // CXXDefaultInitExpr here.
10723       // FIXME: We should have a single context note pointing at Loc, and
10724       // this location should be MD->getLocation() instead, since that's
10725       // the location where we actually use the default init expression.
10726       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10727     if (E)
10728       ExceptSpec.CalledExpr(E);
10729   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10730                             ->getAs<RecordType>()) {
10731     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10732                         FD->getType().getCVRQualifiers());
10733   }
10734   return false;
10735 }
10736 
10737 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10738                                                          Subobject Subobj,
10739                                                          unsigned Quals) {
10740   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10741   bool IsMutable = Field && Field->isMutable();
10742   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10743 }
10744 
10745 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10746     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10747   // Note, if lookup fails, it doesn't matter what exception specification we
10748   // choose because the special member will be deleted.
10749   if (CXXMethodDecl *MD = SMOR.getMethod())
10750     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10751 }
10752 
10753 namespace {
10754 /// RAII object to register a special member as being currently declared.
10755 struct ComputingExceptionSpec {
10756   Sema &S;
10757 
10758   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10759       : S(S) {
10760     Sema::CodeSynthesisContext Ctx;
10761     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10762     Ctx.PointOfInstantiation = Loc;
10763     Ctx.Entity = MD;
10764     S.pushCodeSynthesisContext(Ctx);
10765   }
10766   ~ComputingExceptionSpec() {
10767     S.popCodeSynthesisContext();
10768   }
10769 };
10770 }
10771 
10772 static Sema::ImplicitExceptionSpecification
10773 ComputeDefaultedSpecialMemberExceptionSpec(
10774     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10775     Sema::InheritedConstructorInfo *ICI) {
10776   ComputingExceptionSpec CES(S, MD, Loc);
10777 
10778   CXXRecordDecl *ClassDecl = MD->getParent();
10779 
10780   // C++ [except.spec]p14:
10781   //   An implicitly declared special member function (Clause 12) shall have an
10782   //   exception-specification. [...]
10783   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10784   if (ClassDecl->isInvalidDecl())
10785     return Info.ExceptSpec;
10786 
10787   // FIXME: If this diagnostic fires, we're probably missing a check for
10788   // attempting to resolve an exception specification before it's known
10789   // at a higher level.
10790   if (S.RequireCompleteType(MD->getLocation(),
10791                             S.Context.getRecordType(ClassDecl),
10792                             diag::err_exception_spec_incomplete_type))
10793     return Info.ExceptSpec;
10794 
10795   // C++1z [except.spec]p7:
10796   //   [Look for exceptions thrown by] a constructor selected [...] to
10797   //   initialize a potentially constructed subobject,
10798   // C++1z [except.spec]p8:
10799   //   The exception specification for an implicitly-declared destructor, or a
10800   //   destructor without a noexcept-specifier, is potentially-throwing if and
10801   //   only if any of the destructors for any of its potentially constructed
10802   //   subojects is potentially throwing.
10803   // FIXME: We respect the first rule but ignore the "potentially constructed"
10804   // in the second rule to resolve a core issue (no number yet) that would have
10805   // us reject:
10806   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10807   //   struct B : A {};
10808   //   struct C : B { void f(); };
10809   // ... due to giving B::~B() a non-throwing exception specification.
10810   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10811                                 : Info.VisitAllBases);
10812 
10813   return Info.ExceptSpec;
10814 }
10815 
10816 namespace {
10817 /// RAII object to register a special member as being currently declared.
10818 struct DeclaringSpecialMember {
10819   Sema &S;
10820   Sema::SpecialMemberDecl D;
10821   Sema::ContextRAII SavedContext;
10822   bool WasAlreadyBeingDeclared;
10823 
10824   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10825       : S(S), D(RD, CSM), SavedContext(S, RD) {
10826     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10827     if (WasAlreadyBeingDeclared)
10828       // This almost never happens, but if it does, ensure that our cache
10829       // doesn't contain a stale result.
10830       S.SpecialMemberCache.clear();
10831     else {
10832       // Register a note to be produced if we encounter an error while
10833       // declaring the special member.
10834       Sema::CodeSynthesisContext Ctx;
10835       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10836       // FIXME: We don't have a location to use here. Using the class's
10837       // location maintains the fiction that we declare all special members
10838       // with the class, but (1) it's not clear that lying about that helps our
10839       // users understand what's going on, and (2) there may be outer contexts
10840       // on the stack (some of which are relevant) and printing them exposes
10841       // our lies.
10842       Ctx.PointOfInstantiation = RD->getLocation();
10843       Ctx.Entity = RD;
10844       Ctx.SpecialMember = CSM;
10845       S.pushCodeSynthesisContext(Ctx);
10846     }
10847   }
10848   ~DeclaringSpecialMember() {
10849     if (!WasAlreadyBeingDeclared) {
10850       S.SpecialMembersBeingDeclared.erase(D);
10851       S.popCodeSynthesisContext();
10852     }
10853   }
10854 
10855   /// Are we already trying to declare this special member?
10856   bool isAlreadyBeingDeclared() const {
10857     return WasAlreadyBeingDeclared;
10858   }
10859 };
10860 }
10861 
10862 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10863   // Look up any existing declarations, but don't trigger declaration of all
10864   // implicit special members with this name.
10865   DeclarationName Name = FD->getDeclName();
10866   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10867                  ForExternalRedeclaration);
10868   for (auto *D : FD->getParent()->lookup(Name))
10869     if (auto *Acceptable = R.getAcceptableDecl(D))
10870       R.addDecl(Acceptable);
10871   R.resolveKind();
10872   R.suppressDiagnostics();
10873 
10874   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10875 }
10876 
10877 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10878                                                      CXXRecordDecl *ClassDecl) {
10879   // C++ [class.ctor]p5:
10880   //   A default constructor for a class X is a constructor of class X
10881   //   that can be called without an argument. If there is no
10882   //   user-declared constructor for class X, a default constructor is
10883   //   implicitly declared. An implicitly-declared default constructor
10884   //   is an inline public member of its class.
10885   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10886          "Should not build implicit default constructor!");
10887 
10888   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10889   if (DSM.isAlreadyBeingDeclared())
10890     return nullptr;
10891 
10892   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10893                                                      CXXDefaultConstructor,
10894                                                      false);
10895 
10896   // Create the actual constructor declaration.
10897   CanQualType ClassType
10898     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10899   SourceLocation ClassLoc = ClassDecl->getLocation();
10900   DeclarationName Name
10901     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10902   DeclarationNameInfo NameInfo(Name, ClassLoc);
10903   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10904       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10905       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10906       /*isImplicitlyDeclared=*/true, Constexpr);
10907   DefaultCon->setAccess(AS_public);
10908   DefaultCon->setDefaulted();
10909 
10910   if (getLangOpts().CUDA) {
10911     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10912                                             DefaultCon,
10913                                             /* ConstRHS */ false,
10914                                             /* Diagnose */ false);
10915   }
10916 
10917   // Build an exception specification pointing back at this constructor.
10918   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10919   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10920 
10921   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10922   // constructors is easy to compute.
10923   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10924 
10925   // Note that we have declared this constructor.
10926   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10927 
10928   Scope *S = getScopeForContext(ClassDecl);
10929   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10930 
10931   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10932     SetDeclDeleted(DefaultCon, ClassLoc);
10933 
10934   if (S)
10935     PushOnScopeChains(DefaultCon, S, false);
10936   ClassDecl->addDecl(DefaultCon);
10937 
10938   return DefaultCon;
10939 }
10940 
10941 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10942                                             CXXConstructorDecl *Constructor) {
10943   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10944           !Constructor->doesThisDeclarationHaveABody() &&
10945           !Constructor->isDeleted()) &&
10946     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10947   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10948     return;
10949 
10950   CXXRecordDecl *ClassDecl = Constructor->getParent();
10951   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10952 
10953   SynthesizedFunctionScope Scope(*this, Constructor);
10954 
10955   // The exception specification is needed because we are defining the
10956   // function.
10957   ResolveExceptionSpec(CurrentLocation,
10958                        Constructor->getType()->castAs<FunctionProtoType>());
10959   MarkVTableUsed(CurrentLocation, ClassDecl);
10960 
10961   // Add a context note for diagnostics produced after this point.
10962   Scope.addContextNote(CurrentLocation);
10963 
10964   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10965     Constructor->setInvalidDecl();
10966     return;
10967   }
10968 
10969   SourceLocation Loc = Constructor->getEndLoc().isValid()
10970                            ? Constructor->getEndLoc()
10971                            : Constructor->getLocation();
10972   Constructor->setBody(new (Context) CompoundStmt(Loc));
10973   Constructor->markUsed(Context);
10974 
10975   if (ASTMutationListener *L = getASTMutationListener()) {
10976     L->CompletedImplicitDefinition(Constructor);
10977   }
10978 
10979   DiagnoseUninitializedFields(*this, Constructor);
10980 }
10981 
10982 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10983   // Perform any delayed checks on exception specifications.
10984   CheckDelayedMemberExceptionSpecs();
10985 }
10986 
10987 /// Find or create the fake constructor we synthesize to model constructing an
10988 /// object of a derived class via a constructor of a base class.
10989 CXXConstructorDecl *
10990 Sema::findInheritingConstructor(SourceLocation Loc,
10991                                 CXXConstructorDecl *BaseCtor,
10992                                 ConstructorUsingShadowDecl *Shadow) {
10993   CXXRecordDecl *Derived = Shadow->getParent();
10994   SourceLocation UsingLoc = Shadow->getLocation();
10995 
10996   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10997   // For now we use the name of the base class constructor as a member of the
10998   // derived class to indicate a (fake) inherited constructor name.
10999   DeclarationName Name = BaseCtor->getDeclName();
11000 
11001   // Check to see if we already have a fake constructor for this inherited
11002   // constructor call.
11003   for (NamedDecl *Ctor : Derived->lookup(Name))
11004     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11005                                ->getInheritedConstructor()
11006                                .getConstructor(),
11007                            BaseCtor))
11008       return cast<CXXConstructorDecl>(Ctor);
11009 
11010   DeclarationNameInfo NameInfo(Name, UsingLoc);
11011   TypeSourceInfo *TInfo =
11012       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11013   FunctionProtoTypeLoc ProtoLoc =
11014       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11015 
11016   // Check the inherited constructor is valid and find the list of base classes
11017   // from which it was inherited.
11018   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11019 
11020   bool Constexpr =
11021       BaseCtor->isConstexpr() &&
11022       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11023                                         false, BaseCtor, &ICI);
11024 
11025   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11026       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11027       BaseCtor->isExplicit(), /*Inline=*/true,
11028       /*ImplicitlyDeclared=*/true, Constexpr,
11029       InheritedConstructor(Shadow, BaseCtor));
11030   if (Shadow->isInvalidDecl())
11031     DerivedCtor->setInvalidDecl();
11032 
11033   // Build an unevaluated exception specification for this fake constructor.
11034   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11035   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11036   EPI.ExceptionSpec.Type = EST_Unevaluated;
11037   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11038   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11039                                                FPT->getParamTypes(), EPI));
11040 
11041   // Build the parameter declarations.
11042   SmallVector<ParmVarDecl *, 16> ParamDecls;
11043   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11044     TypeSourceInfo *TInfo =
11045         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11046     ParmVarDecl *PD = ParmVarDecl::Create(
11047         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11048         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11049     PD->setScopeInfo(0, I);
11050     PD->setImplicit();
11051     // Ensure attributes are propagated onto parameters (this matters for
11052     // format, pass_object_size, ...).
11053     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11054     ParamDecls.push_back(PD);
11055     ProtoLoc.setParam(I, PD);
11056   }
11057 
11058   // Set up the new constructor.
11059   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11060   DerivedCtor->setAccess(BaseCtor->getAccess());
11061   DerivedCtor->setParams(ParamDecls);
11062   Derived->addDecl(DerivedCtor);
11063 
11064   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11065     SetDeclDeleted(DerivedCtor, UsingLoc);
11066 
11067   return DerivedCtor;
11068 }
11069 
11070 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11071   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11072                                Ctor->getInheritedConstructor().getShadowDecl());
11073   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11074                             /*Diagnose*/true);
11075 }
11076 
11077 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11078                                        CXXConstructorDecl *Constructor) {
11079   CXXRecordDecl *ClassDecl = Constructor->getParent();
11080   assert(Constructor->getInheritedConstructor() &&
11081          !Constructor->doesThisDeclarationHaveABody() &&
11082          !Constructor->isDeleted());
11083   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11084     return;
11085 
11086   // Initializations are performed "as if by a defaulted default constructor",
11087   // so enter the appropriate scope.
11088   SynthesizedFunctionScope Scope(*this, Constructor);
11089 
11090   // The exception specification is needed because we are defining the
11091   // function.
11092   ResolveExceptionSpec(CurrentLocation,
11093                        Constructor->getType()->castAs<FunctionProtoType>());
11094   MarkVTableUsed(CurrentLocation, ClassDecl);
11095 
11096   // Add a context note for diagnostics produced after this point.
11097   Scope.addContextNote(CurrentLocation);
11098 
11099   ConstructorUsingShadowDecl *Shadow =
11100       Constructor->getInheritedConstructor().getShadowDecl();
11101   CXXConstructorDecl *InheritedCtor =
11102       Constructor->getInheritedConstructor().getConstructor();
11103 
11104   // [class.inhctor.init]p1:
11105   //   initialization proceeds as if a defaulted default constructor is used to
11106   //   initialize the D object and each base class subobject from which the
11107   //   constructor was inherited
11108 
11109   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11110   CXXRecordDecl *RD = Shadow->getParent();
11111   SourceLocation InitLoc = Shadow->getLocation();
11112 
11113   // Build explicit initializers for all base classes from which the
11114   // constructor was inherited.
11115   SmallVector<CXXCtorInitializer*, 8> Inits;
11116   for (bool VBase : {false, true}) {
11117     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11118       if (B.isVirtual() != VBase)
11119         continue;
11120 
11121       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11122       if (!BaseRD)
11123         continue;
11124 
11125       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11126       if (!BaseCtor.first)
11127         continue;
11128 
11129       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11130       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11131           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11132 
11133       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11134       Inits.push_back(new (Context) CXXCtorInitializer(
11135           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11136           SourceLocation()));
11137     }
11138   }
11139 
11140   // We now proceed as if for a defaulted default constructor, with the relevant
11141   // initializers replaced.
11142 
11143   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11144     Constructor->setInvalidDecl();
11145     return;
11146   }
11147 
11148   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11149   Constructor->markUsed(Context);
11150 
11151   if (ASTMutationListener *L = getASTMutationListener()) {
11152     L->CompletedImplicitDefinition(Constructor);
11153   }
11154 
11155   DiagnoseUninitializedFields(*this, Constructor);
11156 }
11157 
11158 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11159   // C++ [class.dtor]p2:
11160   //   If a class has no user-declared destructor, a destructor is
11161   //   declared implicitly. An implicitly-declared destructor is an
11162   //   inline public member of its class.
11163   assert(ClassDecl->needsImplicitDestructor());
11164 
11165   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11166   if (DSM.isAlreadyBeingDeclared())
11167     return nullptr;
11168 
11169   // Create the actual destructor declaration.
11170   CanQualType ClassType
11171     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11172   SourceLocation ClassLoc = ClassDecl->getLocation();
11173   DeclarationName Name
11174     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11175   DeclarationNameInfo NameInfo(Name, ClassLoc);
11176   CXXDestructorDecl *Destructor
11177       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11178                                   QualType(), nullptr, /*isInline=*/true,
11179                                   /*isImplicitlyDeclared=*/true);
11180   Destructor->setAccess(AS_public);
11181   Destructor->setDefaulted();
11182 
11183   if (getLangOpts().CUDA) {
11184     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11185                                             Destructor,
11186                                             /* ConstRHS */ false,
11187                                             /* Diagnose */ false);
11188   }
11189 
11190   // Build an exception specification pointing back at this destructor.
11191   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11192   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11193 
11194   // We don't need to use SpecialMemberIsTrivial here; triviality for
11195   // destructors is easy to compute.
11196   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11197   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11198                                 ClassDecl->hasTrivialDestructorForCall());
11199 
11200   // Note that we have declared this destructor.
11201   ++ASTContext::NumImplicitDestructorsDeclared;
11202 
11203   Scope *S = getScopeForContext(ClassDecl);
11204   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11205 
11206   // We can't check whether an implicit destructor is deleted before we complete
11207   // the definition of the class, because its validity depends on the alignment
11208   // of the class. We'll check this from ActOnFields once the class is complete.
11209   if (ClassDecl->isCompleteDefinition() &&
11210       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11211     SetDeclDeleted(Destructor, ClassLoc);
11212 
11213   // Introduce this destructor into its scope.
11214   if (S)
11215     PushOnScopeChains(Destructor, S, false);
11216   ClassDecl->addDecl(Destructor);
11217 
11218   return Destructor;
11219 }
11220 
11221 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11222                                     CXXDestructorDecl *Destructor) {
11223   assert((Destructor->isDefaulted() &&
11224           !Destructor->doesThisDeclarationHaveABody() &&
11225           !Destructor->isDeleted()) &&
11226          "DefineImplicitDestructor - call it for implicit default dtor");
11227   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11228     return;
11229 
11230   CXXRecordDecl *ClassDecl = Destructor->getParent();
11231   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11232 
11233   SynthesizedFunctionScope Scope(*this, Destructor);
11234 
11235   // The exception specification is needed because we are defining the
11236   // function.
11237   ResolveExceptionSpec(CurrentLocation,
11238                        Destructor->getType()->castAs<FunctionProtoType>());
11239   MarkVTableUsed(CurrentLocation, ClassDecl);
11240 
11241   // Add a context note for diagnostics produced after this point.
11242   Scope.addContextNote(CurrentLocation);
11243 
11244   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11245                                          Destructor->getParent());
11246 
11247   if (CheckDestructor(Destructor)) {
11248     Destructor->setInvalidDecl();
11249     return;
11250   }
11251 
11252   SourceLocation Loc = Destructor->getEndLoc().isValid()
11253                            ? Destructor->getEndLoc()
11254                            : Destructor->getLocation();
11255   Destructor->setBody(new (Context) CompoundStmt(Loc));
11256   Destructor->markUsed(Context);
11257 
11258   if (ASTMutationListener *L = getASTMutationListener()) {
11259     L->CompletedImplicitDefinition(Destructor);
11260   }
11261 }
11262 
11263 /// Perform any semantic analysis which needs to be delayed until all
11264 /// pending class member declarations have been parsed.
11265 void Sema::ActOnFinishCXXMemberDecls() {
11266   // If the context is an invalid C++ class, just suppress these checks.
11267   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11268     if (Record->isInvalidDecl()) {
11269       DelayedOverridingExceptionSpecChecks.clear();
11270       DelayedEquivalentExceptionSpecChecks.clear();
11271       DelayedDefaultedMemberExceptionSpecs.clear();
11272       return;
11273     }
11274     checkForMultipleExportedDefaultConstructors(*this, Record);
11275   }
11276 }
11277 
11278 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11279   referenceDLLExportedClassMethods();
11280 }
11281 
11282 void Sema::referenceDLLExportedClassMethods() {
11283   if (!DelayedDllExportClasses.empty()) {
11284     // Calling ReferenceDllExportedMembers might cause the current function to
11285     // be called again, so use a local copy of DelayedDllExportClasses.
11286     SmallVector<CXXRecordDecl *, 4> WorkList;
11287     std::swap(DelayedDllExportClasses, WorkList);
11288     for (CXXRecordDecl *Class : WorkList)
11289       ReferenceDllExportedMembers(*this, Class);
11290   }
11291 }
11292 
11293 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11294   assert(getLangOpts().CPlusPlus11 &&
11295          "adjusting dtor exception specs was introduced in c++11");
11296 
11297   if (Destructor->isDependentContext())
11298     return;
11299 
11300   // C++11 [class.dtor]p3:
11301   //   A declaration of a destructor that does not have an exception-
11302   //   specification is implicitly considered to have the same exception-
11303   //   specification as an implicit declaration.
11304   const FunctionProtoType *DtorType = Destructor->getType()->
11305                                         getAs<FunctionProtoType>();
11306   if (DtorType->hasExceptionSpec())
11307     return;
11308 
11309   // Replace the destructor's type, building off the existing one. Fortunately,
11310   // the only thing of interest in the destructor type is its extended info.
11311   // The return and arguments are fixed.
11312   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11313   EPI.ExceptionSpec.Type = EST_Unevaluated;
11314   EPI.ExceptionSpec.SourceDecl = Destructor;
11315   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11316 
11317   // FIXME: If the destructor has a body that could throw, and the newly created
11318   // spec doesn't allow exceptions, we should emit a warning, because this
11319   // change in behavior can break conforming C++03 programs at runtime.
11320   // However, we don't have a body or an exception specification yet, so it
11321   // needs to be done somewhere else.
11322 }
11323 
11324 namespace {
11325 /// An abstract base class for all helper classes used in building the
11326 //  copy/move operators. These classes serve as factory functions and help us
11327 //  avoid using the same Expr* in the AST twice.
11328 class ExprBuilder {
11329   ExprBuilder(const ExprBuilder&) = delete;
11330   ExprBuilder &operator=(const ExprBuilder&) = delete;
11331 
11332 protected:
11333   static Expr *assertNotNull(Expr *E) {
11334     assert(E && "Expression construction must not fail.");
11335     return E;
11336   }
11337 
11338 public:
11339   ExprBuilder() {}
11340   virtual ~ExprBuilder() {}
11341 
11342   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11343 };
11344 
11345 class RefBuilder: public ExprBuilder {
11346   VarDecl *Var;
11347   QualType VarType;
11348 
11349 public:
11350   Expr *build(Sema &S, SourceLocation Loc) const override {
11351     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11352   }
11353 
11354   RefBuilder(VarDecl *Var, QualType VarType)
11355       : Var(Var), VarType(VarType) {}
11356 };
11357 
11358 class ThisBuilder: public ExprBuilder {
11359 public:
11360   Expr *build(Sema &S, SourceLocation Loc) const override {
11361     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11362   }
11363 };
11364 
11365 class CastBuilder: public ExprBuilder {
11366   const ExprBuilder &Builder;
11367   QualType Type;
11368   ExprValueKind Kind;
11369   const CXXCastPath &Path;
11370 
11371 public:
11372   Expr *build(Sema &S, SourceLocation Loc) const override {
11373     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11374                                              CK_UncheckedDerivedToBase, Kind,
11375                                              &Path).get());
11376   }
11377 
11378   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11379               const CXXCastPath &Path)
11380       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11381 };
11382 
11383 class DerefBuilder: public ExprBuilder {
11384   const ExprBuilder &Builder;
11385 
11386 public:
11387   Expr *build(Sema &S, SourceLocation Loc) const override {
11388     return assertNotNull(
11389         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11390   }
11391 
11392   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11393 };
11394 
11395 class MemberBuilder: public ExprBuilder {
11396   const ExprBuilder &Builder;
11397   QualType Type;
11398   CXXScopeSpec SS;
11399   bool IsArrow;
11400   LookupResult &MemberLookup;
11401 
11402 public:
11403   Expr *build(Sema &S, SourceLocation Loc) const override {
11404     return assertNotNull(S.BuildMemberReferenceExpr(
11405         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11406         nullptr, MemberLookup, nullptr, nullptr).get());
11407   }
11408 
11409   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11410                 LookupResult &MemberLookup)
11411       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11412         MemberLookup(MemberLookup) {}
11413 };
11414 
11415 class MoveCastBuilder: public ExprBuilder {
11416   const ExprBuilder &Builder;
11417 
11418 public:
11419   Expr *build(Sema &S, SourceLocation Loc) const override {
11420     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11421   }
11422 
11423   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11424 };
11425 
11426 class LvalueConvBuilder: public ExprBuilder {
11427   const ExprBuilder &Builder;
11428 
11429 public:
11430   Expr *build(Sema &S, SourceLocation Loc) const override {
11431     return assertNotNull(
11432         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11433   }
11434 
11435   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11436 };
11437 
11438 class SubscriptBuilder: public ExprBuilder {
11439   const ExprBuilder &Base;
11440   const ExprBuilder &Index;
11441 
11442 public:
11443   Expr *build(Sema &S, SourceLocation Loc) const override {
11444     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11445         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11446   }
11447 
11448   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11449       : Base(Base), Index(Index) {}
11450 };
11451 
11452 } // end anonymous namespace
11453 
11454 /// When generating a defaulted copy or move assignment operator, if a field
11455 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11456 /// do so. This optimization only applies for arrays of scalars, and for arrays
11457 /// of class type where the selected copy/move-assignment operator is trivial.
11458 static StmtResult
11459 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11460                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11461   // Compute the size of the memory buffer to be copied.
11462   QualType SizeType = S.Context.getSizeType();
11463   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11464                    S.Context.getTypeSizeInChars(T).getQuantity());
11465 
11466   // Take the address of the field references for "from" and "to". We
11467   // directly construct UnaryOperators here because semantic analysis
11468   // does not permit us to take the address of an xvalue.
11469   Expr *From = FromB.build(S, Loc);
11470   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11471                          S.Context.getPointerType(From->getType()),
11472                          VK_RValue, OK_Ordinary, Loc, false);
11473   Expr *To = ToB.build(S, Loc);
11474   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11475                        S.Context.getPointerType(To->getType()),
11476                        VK_RValue, OK_Ordinary, Loc, false);
11477 
11478   const Type *E = T->getBaseElementTypeUnsafe();
11479   bool NeedsCollectableMemCpy =
11480     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11481 
11482   // Create a reference to the __builtin_objc_memmove_collectable function
11483   StringRef MemCpyName = NeedsCollectableMemCpy ?
11484     "__builtin_objc_memmove_collectable" :
11485     "__builtin_memcpy";
11486   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11487                  Sema::LookupOrdinaryName);
11488   S.LookupName(R, S.TUScope, true);
11489 
11490   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11491   if (!MemCpy)
11492     // Something went horribly wrong earlier, and we will have complained
11493     // about it.
11494     return StmtError();
11495 
11496   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11497                                             VK_RValue, Loc, nullptr);
11498   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11499 
11500   Expr *CallArgs[] = {
11501     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11502   };
11503   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11504                                     Loc, CallArgs, Loc);
11505 
11506   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11507   return Call.getAs<Stmt>();
11508 }
11509 
11510 /// Builds a statement that copies/moves the given entity from \p From to
11511 /// \c To.
11512 ///
11513 /// This routine is used to copy/move the members of a class with an
11514 /// implicitly-declared copy/move assignment operator. When the entities being
11515 /// copied are arrays, this routine builds for loops to copy them.
11516 ///
11517 /// \param S The Sema object used for type-checking.
11518 ///
11519 /// \param Loc The location where the implicit copy/move is being generated.
11520 ///
11521 /// \param T The type of the expressions being copied/moved. Both expressions
11522 /// must have this type.
11523 ///
11524 /// \param To The expression we are copying/moving to.
11525 ///
11526 /// \param From The expression we are copying/moving from.
11527 ///
11528 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11529 /// Otherwise, it's a non-static member subobject.
11530 ///
11531 /// \param Copying Whether we're copying or moving.
11532 ///
11533 /// \param Depth Internal parameter recording the depth of the recursion.
11534 ///
11535 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11536 /// if a memcpy should be used instead.
11537 static StmtResult
11538 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11539                                  const ExprBuilder &To, const ExprBuilder &From,
11540                                  bool CopyingBaseSubobject, bool Copying,
11541                                  unsigned Depth = 0) {
11542   // C++11 [class.copy]p28:
11543   //   Each subobject is assigned in the manner appropriate to its type:
11544   //
11545   //     - if the subobject is of class type, as if by a call to operator= with
11546   //       the subobject as the object expression and the corresponding
11547   //       subobject of x as a single function argument (as if by explicit
11548   //       qualification; that is, ignoring any possible virtual overriding
11549   //       functions in more derived classes);
11550   //
11551   // C++03 [class.copy]p13:
11552   //     - if the subobject is of class type, the copy assignment operator for
11553   //       the class is used (as if by explicit qualification; that is,
11554   //       ignoring any possible virtual overriding functions in more derived
11555   //       classes);
11556   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11557     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11558 
11559     // Look for operator=.
11560     DeclarationName Name
11561       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11562     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11563     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11564 
11565     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11566     // operator.
11567     if (!S.getLangOpts().CPlusPlus11) {
11568       LookupResult::Filter F = OpLookup.makeFilter();
11569       while (F.hasNext()) {
11570         NamedDecl *D = F.next();
11571         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11572           if (Method->isCopyAssignmentOperator() ||
11573               (!Copying && Method->isMoveAssignmentOperator()))
11574             continue;
11575 
11576         F.erase();
11577       }
11578       F.done();
11579     }
11580 
11581     // Suppress the protected check (C++ [class.protected]) for each of the
11582     // assignment operators we found. This strange dance is required when
11583     // we're assigning via a base classes's copy-assignment operator. To
11584     // ensure that we're getting the right base class subobject (without
11585     // ambiguities), we need to cast "this" to that subobject type; to
11586     // ensure that we don't go through the virtual call mechanism, we need
11587     // to qualify the operator= name with the base class (see below). However,
11588     // this means that if the base class has a protected copy assignment
11589     // operator, the protected member access check will fail. So, we
11590     // rewrite "protected" access to "public" access in this case, since we
11591     // know by construction that we're calling from a derived class.
11592     if (CopyingBaseSubobject) {
11593       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11594            L != LEnd; ++L) {
11595         if (L.getAccess() == AS_protected)
11596           L.setAccess(AS_public);
11597       }
11598     }
11599 
11600     // Create the nested-name-specifier that will be used to qualify the
11601     // reference to operator=; this is required to suppress the virtual
11602     // call mechanism.
11603     CXXScopeSpec SS;
11604     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11605     SS.MakeTrivial(S.Context,
11606                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11607                                                CanonicalT),
11608                    Loc);
11609 
11610     // Create the reference to operator=.
11611     ExprResult OpEqualRef
11612       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11613                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11614                                    /*FirstQualifierInScope=*/nullptr,
11615                                    OpLookup,
11616                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11617                                    /*SuppressQualifierCheck=*/true);
11618     if (OpEqualRef.isInvalid())
11619       return StmtError();
11620 
11621     // Build the call to the assignment operator.
11622 
11623     Expr *FromInst = From.build(S, Loc);
11624     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11625                                                   OpEqualRef.getAs<Expr>(),
11626                                                   Loc, FromInst, Loc);
11627     if (Call.isInvalid())
11628       return StmtError();
11629 
11630     // If we built a call to a trivial 'operator=' while copying an array,
11631     // bail out. We'll replace the whole shebang with a memcpy.
11632     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11633     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11634       return StmtResult((Stmt*)nullptr);
11635 
11636     // Convert to an expression-statement, and clean up any produced
11637     // temporaries.
11638     return S.ActOnExprStmt(Call);
11639   }
11640 
11641   //     - if the subobject is of scalar type, the built-in assignment
11642   //       operator is used.
11643   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11644   if (!ArrayTy) {
11645     ExprResult Assignment = S.CreateBuiltinBinOp(
11646         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11647     if (Assignment.isInvalid())
11648       return StmtError();
11649     return S.ActOnExprStmt(Assignment);
11650   }
11651 
11652   //     - if the subobject is an array, each element is assigned, in the
11653   //       manner appropriate to the element type;
11654 
11655   // Construct a loop over the array bounds, e.g.,
11656   //
11657   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11658   //
11659   // that will copy each of the array elements.
11660   QualType SizeType = S.Context.getSizeType();
11661 
11662   // Create the iteration variable.
11663   IdentifierInfo *IterationVarName = nullptr;
11664   {
11665     SmallString<8> Str;
11666     llvm::raw_svector_ostream OS(Str);
11667     OS << "__i" << Depth;
11668     IterationVarName = &S.Context.Idents.get(OS.str());
11669   }
11670   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11671                                           IterationVarName, SizeType,
11672                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11673                                           SC_None);
11674 
11675   // Initialize the iteration variable to zero.
11676   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11677   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11678 
11679   // Creates a reference to the iteration variable.
11680   RefBuilder IterationVarRef(IterationVar, SizeType);
11681   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11682 
11683   // Create the DeclStmt that holds the iteration variable.
11684   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11685 
11686   // Subscript the "from" and "to" expressions with the iteration variable.
11687   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11688   MoveCastBuilder FromIndexMove(FromIndexCopy);
11689   const ExprBuilder *FromIndex;
11690   if (Copying)
11691     FromIndex = &FromIndexCopy;
11692   else
11693     FromIndex = &FromIndexMove;
11694 
11695   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11696 
11697   // Build the copy/move for an individual element of the array.
11698   StmtResult Copy =
11699     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11700                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11701                                      Copying, Depth + 1);
11702   // Bail out if copying fails or if we determined that we should use memcpy.
11703   if (Copy.isInvalid() || !Copy.get())
11704     return Copy;
11705 
11706   // Create the comparison against the array bound.
11707   llvm::APInt Upper
11708     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11709   Expr *Comparison
11710     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11711                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11712                                      BO_NE, S.Context.BoolTy,
11713                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11714 
11715   // Create the pre-increment of the iteration variable. We can determine
11716   // whether the increment will overflow based on the value of the array
11717   // bound.
11718   Expr *Increment = new (S.Context)
11719       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11720                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11721 
11722   // Construct the loop that copies all elements of this array.
11723   return S.ActOnForStmt(
11724       Loc, Loc, InitStmt,
11725       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11726       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11727 }
11728 
11729 static StmtResult
11730 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11731                       const ExprBuilder &To, const ExprBuilder &From,
11732                       bool CopyingBaseSubobject, bool Copying) {
11733   // Maybe we should use a memcpy?
11734   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11735       T.isTriviallyCopyableType(S.Context))
11736     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11737 
11738   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11739                                                      CopyingBaseSubobject,
11740                                                      Copying, 0));
11741 
11742   // If we ended up picking a trivial assignment operator for an array of a
11743   // non-trivially-copyable class type, just emit a memcpy.
11744   if (!Result.isInvalid() && !Result.get())
11745     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11746 
11747   return Result;
11748 }
11749 
11750 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11751   // Note: The following rules are largely analoguous to the copy
11752   // constructor rules. Note that virtual bases are not taken into account
11753   // for determining the argument type of the operator. Note also that
11754   // operators taking an object instead of a reference are allowed.
11755   assert(ClassDecl->needsImplicitCopyAssignment());
11756 
11757   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11758   if (DSM.isAlreadyBeingDeclared())
11759     return nullptr;
11760 
11761   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11762   QualType RetType = Context.getLValueReferenceType(ArgType);
11763   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11764   if (Const)
11765     ArgType = ArgType.withConst();
11766   ArgType = Context.getLValueReferenceType(ArgType);
11767 
11768   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11769                                                      CXXCopyAssignment,
11770                                                      Const);
11771 
11772   //   An implicitly-declared copy assignment operator is an inline public
11773   //   member of its class.
11774   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11775   SourceLocation ClassLoc = ClassDecl->getLocation();
11776   DeclarationNameInfo NameInfo(Name, ClassLoc);
11777   CXXMethodDecl *CopyAssignment =
11778       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11779                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11780                             /*isInline=*/true, Constexpr, SourceLocation());
11781   CopyAssignment->setAccess(AS_public);
11782   CopyAssignment->setDefaulted();
11783   CopyAssignment->setImplicit();
11784 
11785   if (getLangOpts().CUDA) {
11786     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11787                                             CopyAssignment,
11788                                             /* ConstRHS */ Const,
11789                                             /* Diagnose */ false);
11790   }
11791 
11792   // Build an exception specification pointing back at this member.
11793   FunctionProtoType::ExtProtoInfo EPI =
11794       getImplicitMethodEPI(*this, CopyAssignment);
11795   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11796 
11797   // Add the parameter to the operator.
11798   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11799                                                ClassLoc, ClassLoc,
11800                                                /*Id=*/nullptr, ArgType,
11801                                                /*TInfo=*/nullptr, SC_None,
11802                                                nullptr);
11803   CopyAssignment->setParams(FromParam);
11804 
11805   CopyAssignment->setTrivial(
11806     ClassDecl->needsOverloadResolutionForCopyAssignment()
11807       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11808       : ClassDecl->hasTrivialCopyAssignment());
11809 
11810   // Note that we have added this copy-assignment operator.
11811   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11812 
11813   Scope *S = getScopeForContext(ClassDecl);
11814   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11815 
11816   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11817     SetDeclDeleted(CopyAssignment, ClassLoc);
11818 
11819   if (S)
11820     PushOnScopeChains(CopyAssignment, S, false);
11821   ClassDecl->addDecl(CopyAssignment);
11822 
11823   return CopyAssignment;
11824 }
11825 
11826 /// Diagnose an implicit copy operation for a class which is odr-used, but
11827 /// which is deprecated because the class has a user-declared copy constructor,
11828 /// copy assignment operator, or destructor.
11829 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11830   assert(CopyOp->isImplicit());
11831 
11832   CXXRecordDecl *RD = CopyOp->getParent();
11833   CXXMethodDecl *UserDeclaredOperation = nullptr;
11834 
11835   // In Microsoft mode, assignment operations don't affect constructors and
11836   // vice versa.
11837   if (RD->hasUserDeclaredDestructor()) {
11838     UserDeclaredOperation = RD->getDestructor();
11839   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11840              RD->hasUserDeclaredCopyConstructor() &&
11841              !S.getLangOpts().MSVCCompat) {
11842     // Find any user-declared copy constructor.
11843     for (auto *I : RD->ctors()) {
11844       if (I->isCopyConstructor()) {
11845         UserDeclaredOperation = I;
11846         break;
11847       }
11848     }
11849     assert(UserDeclaredOperation);
11850   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11851              RD->hasUserDeclaredCopyAssignment() &&
11852              !S.getLangOpts().MSVCCompat) {
11853     // Find any user-declared move assignment operator.
11854     for (auto *I : RD->methods()) {
11855       if (I->isCopyAssignmentOperator()) {
11856         UserDeclaredOperation = I;
11857         break;
11858       }
11859     }
11860     assert(UserDeclaredOperation);
11861   }
11862 
11863   if (UserDeclaredOperation) {
11864     S.Diag(UserDeclaredOperation->getLocation(),
11865          diag::warn_deprecated_copy_operation)
11866       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11867       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11868   }
11869 }
11870 
11871 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11872                                         CXXMethodDecl *CopyAssignOperator) {
11873   assert((CopyAssignOperator->isDefaulted() &&
11874           CopyAssignOperator->isOverloadedOperator() &&
11875           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11876           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11877           !CopyAssignOperator->isDeleted()) &&
11878          "DefineImplicitCopyAssignment called for wrong function");
11879   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11880     return;
11881 
11882   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11883   if (ClassDecl->isInvalidDecl()) {
11884     CopyAssignOperator->setInvalidDecl();
11885     return;
11886   }
11887 
11888   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11889 
11890   // The exception specification is needed because we are defining the
11891   // function.
11892   ResolveExceptionSpec(CurrentLocation,
11893                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11894 
11895   // Add a context note for diagnostics produced after this point.
11896   Scope.addContextNote(CurrentLocation);
11897 
11898   // C++11 [class.copy]p18:
11899   //   The [definition of an implicitly declared copy assignment operator] is
11900   //   deprecated if the class has a user-declared copy constructor or a
11901   //   user-declared destructor.
11902   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11903     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11904 
11905   // C++0x [class.copy]p30:
11906   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11907   //   for a non-union class X performs memberwise copy assignment of its
11908   //   subobjects. The direct base classes of X are assigned first, in the
11909   //   order of their declaration in the base-specifier-list, and then the
11910   //   immediate non-static data members of X are assigned, in the order in
11911   //   which they were declared in the class definition.
11912 
11913   // The statements that form the synthesized function body.
11914   SmallVector<Stmt*, 8> Statements;
11915 
11916   // The parameter for the "other" object, which we are copying from.
11917   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11918   Qualifiers OtherQuals = Other->getType().getQualifiers();
11919   QualType OtherRefType = Other->getType();
11920   if (const LValueReferenceType *OtherRef
11921                                 = OtherRefType->getAs<LValueReferenceType>()) {
11922     OtherRefType = OtherRef->getPointeeType();
11923     OtherQuals = OtherRefType.getQualifiers();
11924   }
11925 
11926   // Our location for everything implicitly-generated.
11927   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11928                            ? CopyAssignOperator->getEndLoc()
11929                            : CopyAssignOperator->getLocation();
11930 
11931   // Builds a DeclRefExpr for the "other" object.
11932   RefBuilder OtherRef(Other, OtherRefType);
11933 
11934   // Builds the "this" pointer.
11935   ThisBuilder This;
11936 
11937   // Assign base classes.
11938   bool Invalid = false;
11939   for (auto &Base : ClassDecl->bases()) {
11940     // Form the assignment:
11941     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11942     QualType BaseType = Base.getType().getUnqualifiedType();
11943     if (!BaseType->isRecordType()) {
11944       Invalid = true;
11945       continue;
11946     }
11947 
11948     CXXCastPath BasePath;
11949     BasePath.push_back(&Base);
11950 
11951     // Construct the "from" expression, which is an implicit cast to the
11952     // appropriately-qualified base type.
11953     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11954                      VK_LValue, BasePath);
11955 
11956     // Dereference "this".
11957     DerefBuilder DerefThis(This);
11958     CastBuilder To(DerefThis,
11959                    Context.getCVRQualifiedType(
11960                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11961                    VK_LValue, BasePath);
11962 
11963     // Build the copy.
11964     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11965                                             To, From,
11966                                             /*CopyingBaseSubobject=*/true,
11967                                             /*Copying=*/true);
11968     if (Copy.isInvalid()) {
11969       CopyAssignOperator->setInvalidDecl();
11970       return;
11971     }
11972 
11973     // Success! Record the copy.
11974     Statements.push_back(Copy.getAs<Expr>());
11975   }
11976 
11977   // Assign non-static members.
11978   for (auto *Field : ClassDecl->fields()) {
11979     // FIXME: We should form some kind of AST representation for the implied
11980     // memcpy in a union copy operation.
11981     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11982       continue;
11983 
11984     if (Field->isInvalidDecl()) {
11985       Invalid = true;
11986       continue;
11987     }
11988 
11989     // Check for members of reference type; we can't copy those.
11990     if (Field->getType()->isReferenceType()) {
11991       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11992         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11993       Diag(Field->getLocation(), diag::note_declared_at);
11994       Invalid = true;
11995       continue;
11996     }
11997 
11998     // Check for members of const-qualified, non-class type.
11999     QualType BaseType = Context.getBaseElementType(Field->getType());
12000     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12001       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12002         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12003       Diag(Field->getLocation(), diag::note_declared_at);
12004       Invalid = true;
12005       continue;
12006     }
12007 
12008     // Suppress assigning zero-width bitfields.
12009     if (Field->isZeroLengthBitField(Context))
12010       continue;
12011 
12012     QualType FieldType = Field->getType().getNonReferenceType();
12013     if (FieldType->isIncompleteArrayType()) {
12014       assert(ClassDecl->hasFlexibleArrayMember() &&
12015              "Incomplete array type is not valid");
12016       continue;
12017     }
12018 
12019     // Build references to the field in the object we're copying from and to.
12020     CXXScopeSpec SS; // Intentionally empty
12021     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12022                               LookupMemberName);
12023     MemberLookup.addDecl(Field);
12024     MemberLookup.resolveKind();
12025 
12026     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12027 
12028     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12029 
12030     // Build the copy of this field.
12031     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12032                                             To, From,
12033                                             /*CopyingBaseSubobject=*/false,
12034                                             /*Copying=*/true);
12035     if (Copy.isInvalid()) {
12036       CopyAssignOperator->setInvalidDecl();
12037       return;
12038     }
12039 
12040     // Success! Record the copy.
12041     Statements.push_back(Copy.getAs<Stmt>());
12042   }
12043 
12044   if (!Invalid) {
12045     // Add a "return *this;"
12046     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12047 
12048     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12049     if (Return.isInvalid())
12050       Invalid = true;
12051     else
12052       Statements.push_back(Return.getAs<Stmt>());
12053   }
12054 
12055   if (Invalid) {
12056     CopyAssignOperator->setInvalidDecl();
12057     return;
12058   }
12059 
12060   StmtResult Body;
12061   {
12062     CompoundScopeRAII CompoundScope(*this);
12063     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12064                              /*isStmtExpr=*/false);
12065     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12066   }
12067   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12068   CopyAssignOperator->markUsed(Context);
12069 
12070   if (ASTMutationListener *L = getASTMutationListener()) {
12071     L->CompletedImplicitDefinition(CopyAssignOperator);
12072   }
12073 }
12074 
12075 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12076   assert(ClassDecl->needsImplicitMoveAssignment());
12077 
12078   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12079   if (DSM.isAlreadyBeingDeclared())
12080     return nullptr;
12081 
12082   // Note: The following rules are largely analoguous to the move
12083   // constructor rules.
12084 
12085   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12086   QualType RetType = Context.getLValueReferenceType(ArgType);
12087   ArgType = Context.getRValueReferenceType(ArgType);
12088 
12089   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12090                                                      CXXMoveAssignment,
12091                                                      false);
12092 
12093   //   An implicitly-declared move assignment operator is an inline public
12094   //   member of its class.
12095   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12096   SourceLocation ClassLoc = ClassDecl->getLocation();
12097   DeclarationNameInfo NameInfo(Name, ClassLoc);
12098   CXXMethodDecl *MoveAssignment =
12099       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12100                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12101                             /*isInline=*/true, Constexpr, SourceLocation());
12102   MoveAssignment->setAccess(AS_public);
12103   MoveAssignment->setDefaulted();
12104   MoveAssignment->setImplicit();
12105 
12106   if (getLangOpts().CUDA) {
12107     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12108                                             MoveAssignment,
12109                                             /* ConstRHS */ false,
12110                                             /* Diagnose */ false);
12111   }
12112 
12113   // Build an exception specification pointing back at this member.
12114   FunctionProtoType::ExtProtoInfo EPI =
12115       getImplicitMethodEPI(*this, MoveAssignment);
12116   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12117 
12118   // Add the parameter to the operator.
12119   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12120                                                ClassLoc, ClassLoc,
12121                                                /*Id=*/nullptr, ArgType,
12122                                                /*TInfo=*/nullptr, SC_None,
12123                                                nullptr);
12124   MoveAssignment->setParams(FromParam);
12125 
12126   MoveAssignment->setTrivial(
12127     ClassDecl->needsOverloadResolutionForMoveAssignment()
12128       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12129       : ClassDecl->hasTrivialMoveAssignment());
12130 
12131   // Note that we have added this copy-assignment operator.
12132   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12133 
12134   Scope *S = getScopeForContext(ClassDecl);
12135   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12136 
12137   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12138     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12139     SetDeclDeleted(MoveAssignment, ClassLoc);
12140   }
12141 
12142   if (S)
12143     PushOnScopeChains(MoveAssignment, S, false);
12144   ClassDecl->addDecl(MoveAssignment);
12145 
12146   return MoveAssignment;
12147 }
12148 
12149 /// Check if we're implicitly defining a move assignment operator for a class
12150 /// with virtual bases. Such a move assignment might move-assign the virtual
12151 /// base multiple times.
12152 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12153                                                SourceLocation CurrentLocation) {
12154   assert(!Class->isDependentContext() && "should not define dependent move");
12155 
12156   // Only a virtual base could get implicitly move-assigned multiple times.
12157   // Only a non-trivial move assignment can observe this. We only want to
12158   // diagnose if we implicitly define an assignment operator that assigns
12159   // two base classes, both of which move-assign the same virtual base.
12160   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12161       Class->getNumBases() < 2)
12162     return;
12163 
12164   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12165   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12166   VBaseMap VBases;
12167 
12168   for (auto &BI : Class->bases()) {
12169     Worklist.push_back(&BI);
12170     while (!Worklist.empty()) {
12171       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12172       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12173 
12174       // If the base has no non-trivial move assignment operators,
12175       // we don't care about moves from it.
12176       if (!Base->hasNonTrivialMoveAssignment())
12177         continue;
12178 
12179       // If there's nothing virtual here, skip it.
12180       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12181         continue;
12182 
12183       // If we're not actually going to call a move assignment for this base,
12184       // or the selected move assignment is trivial, skip it.
12185       Sema::SpecialMemberOverloadResult SMOR =
12186         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12187                               /*ConstArg*/false, /*VolatileArg*/false,
12188                               /*RValueThis*/true, /*ConstThis*/false,
12189                               /*VolatileThis*/false);
12190       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12191           !SMOR.getMethod()->isMoveAssignmentOperator())
12192         continue;
12193 
12194       if (BaseSpec->isVirtual()) {
12195         // We're going to move-assign this virtual base, and its move
12196         // assignment operator is not trivial. If this can happen for
12197         // multiple distinct direct bases of Class, diagnose it. (If it
12198         // only happens in one base, we'll diagnose it when synthesizing
12199         // that base class's move assignment operator.)
12200         CXXBaseSpecifier *&Existing =
12201             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12202                 .first->second;
12203         if (Existing && Existing != &BI) {
12204           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12205             << Class << Base;
12206           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12207               << (Base->getCanonicalDecl() ==
12208                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12209               << Base << Existing->getType() << Existing->getSourceRange();
12210           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12211               << (Base->getCanonicalDecl() ==
12212                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12213               << Base << BI.getType() << BaseSpec->getSourceRange();
12214 
12215           // Only diagnose each vbase once.
12216           Existing = nullptr;
12217         }
12218       } else {
12219         // Only walk over bases that have defaulted move assignment operators.
12220         // We assume that any user-provided move assignment operator handles
12221         // the multiple-moves-of-vbase case itself somehow.
12222         if (!SMOR.getMethod()->isDefaulted())
12223           continue;
12224 
12225         // We're going to move the base classes of Base. Add them to the list.
12226         for (auto &BI : Base->bases())
12227           Worklist.push_back(&BI);
12228       }
12229     }
12230   }
12231 }
12232 
12233 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12234                                         CXXMethodDecl *MoveAssignOperator) {
12235   assert((MoveAssignOperator->isDefaulted() &&
12236           MoveAssignOperator->isOverloadedOperator() &&
12237           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12238           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12239           !MoveAssignOperator->isDeleted()) &&
12240          "DefineImplicitMoveAssignment called for wrong function");
12241   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12242     return;
12243 
12244   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12245   if (ClassDecl->isInvalidDecl()) {
12246     MoveAssignOperator->setInvalidDecl();
12247     return;
12248   }
12249 
12250   // C++0x [class.copy]p28:
12251   //   The implicitly-defined or move assignment operator for a non-union class
12252   //   X performs memberwise move assignment of its subobjects. The direct base
12253   //   classes of X are assigned first, in the order of their declaration in the
12254   //   base-specifier-list, and then the immediate non-static data members of X
12255   //   are assigned, in the order in which they were declared in the class
12256   //   definition.
12257 
12258   // Issue a warning if our implicit move assignment operator will move
12259   // from a virtual base more than once.
12260   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12261 
12262   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12263 
12264   // The exception specification is needed because we are defining the
12265   // function.
12266   ResolveExceptionSpec(CurrentLocation,
12267                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12268 
12269   // Add a context note for diagnostics produced after this point.
12270   Scope.addContextNote(CurrentLocation);
12271 
12272   // The statements that form the synthesized function body.
12273   SmallVector<Stmt*, 8> Statements;
12274 
12275   // The parameter for the "other" object, which we are move from.
12276   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12277   QualType OtherRefType = Other->getType()->
12278       getAs<RValueReferenceType>()->getPointeeType();
12279   assert(!OtherRefType.getQualifiers() &&
12280          "Bad argument type of defaulted move assignment");
12281 
12282   // Our location for everything implicitly-generated.
12283   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12284                            ? MoveAssignOperator->getEndLoc()
12285                            : MoveAssignOperator->getLocation();
12286 
12287   // Builds a reference to the "other" object.
12288   RefBuilder OtherRef(Other, OtherRefType);
12289   // Cast to rvalue.
12290   MoveCastBuilder MoveOther(OtherRef);
12291 
12292   // Builds the "this" pointer.
12293   ThisBuilder This;
12294 
12295   // Assign base classes.
12296   bool Invalid = false;
12297   for (auto &Base : ClassDecl->bases()) {
12298     // C++11 [class.copy]p28:
12299     //   It is unspecified whether subobjects representing virtual base classes
12300     //   are assigned more than once by the implicitly-defined copy assignment
12301     //   operator.
12302     // FIXME: Do not assign to a vbase that will be assigned by some other base
12303     // class. For a move-assignment, this can result in the vbase being moved
12304     // multiple times.
12305 
12306     // Form the assignment:
12307     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12308     QualType BaseType = Base.getType().getUnqualifiedType();
12309     if (!BaseType->isRecordType()) {
12310       Invalid = true;
12311       continue;
12312     }
12313 
12314     CXXCastPath BasePath;
12315     BasePath.push_back(&Base);
12316 
12317     // Construct the "from" expression, which is an implicit cast to the
12318     // appropriately-qualified base type.
12319     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12320 
12321     // Dereference "this".
12322     DerefBuilder DerefThis(This);
12323 
12324     // Implicitly cast "this" to the appropriately-qualified base type.
12325     CastBuilder To(DerefThis,
12326                    Context.getCVRQualifiedType(
12327                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12328                    VK_LValue, BasePath);
12329 
12330     // Build the move.
12331     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12332                                             To, From,
12333                                             /*CopyingBaseSubobject=*/true,
12334                                             /*Copying=*/false);
12335     if (Move.isInvalid()) {
12336       MoveAssignOperator->setInvalidDecl();
12337       return;
12338     }
12339 
12340     // Success! Record the move.
12341     Statements.push_back(Move.getAs<Expr>());
12342   }
12343 
12344   // Assign non-static members.
12345   for (auto *Field : ClassDecl->fields()) {
12346     // FIXME: We should form some kind of AST representation for the implied
12347     // memcpy in a union copy operation.
12348     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12349       continue;
12350 
12351     if (Field->isInvalidDecl()) {
12352       Invalid = true;
12353       continue;
12354     }
12355 
12356     // Check for members of reference type; we can't move those.
12357     if (Field->getType()->isReferenceType()) {
12358       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12359         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12360       Diag(Field->getLocation(), diag::note_declared_at);
12361       Invalid = true;
12362       continue;
12363     }
12364 
12365     // Check for members of const-qualified, non-class type.
12366     QualType BaseType = Context.getBaseElementType(Field->getType());
12367     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12368       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12369         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12370       Diag(Field->getLocation(), diag::note_declared_at);
12371       Invalid = true;
12372       continue;
12373     }
12374 
12375     // Suppress assigning zero-width bitfields.
12376     if (Field->isZeroLengthBitField(Context))
12377       continue;
12378 
12379     QualType FieldType = Field->getType().getNonReferenceType();
12380     if (FieldType->isIncompleteArrayType()) {
12381       assert(ClassDecl->hasFlexibleArrayMember() &&
12382              "Incomplete array type is not valid");
12383       continue;
12384     }
12385 
12386     // Build references to the field in the object we're copying from and to.
12387     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12388                               LookupMemberName);
12389     MemberLookup.addDecl(Field);
12390     MemberLookup.resolveKind();
12391     MemberBuilder From(MoveOther, OtherRefType,
12392                        /*IsArrow=*/false, MemberLookup);
12393     MemberBuilder To(This, getCurrentThisType(),
12394                      /*IsArrow=*/true, MemberLookup);
12395 
12396     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12397         "Member reference with rvalue base must be rvalue except for reference "
12398         "members, which aren't allowed for move assignment.");
12399 
12400     // Build the move of this field.
12401     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12402                                             To, From,
12403                                             /*CopyingBaseSubobject=*/false,
12404                                             /*Copying=*/false);
12405     if (Move.isInvalid()) {
12406       MoveAssignOperator->setInvalidDecl();
12407       return;
12408     }
12409 
12410     // Success! Record the copy.
12411     Statements.push_back(Move.getAs<Stmt>());
12412   }
12413 
12414   if (!Invalid) {
12415     // Add a "return *this;"
12416     ExprResult ThisObj =
12417         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12418 
12419     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12420     if (Return.isInvalid())
12421       Invalid = true;
12422     else
12423       Statements.push_back(Return.getAs<Stmt>());
12424   }
12425 
12426   if (Invalid) {
12427     MoveAssignOperator->setInvalidDecl();
12428     return;
12429   }
12430 
12431   StmtResult Body;
12432   {
12433     CompoundScopeRAII CompoundScope(*this);
12434     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12435                              /*isStmtExpr=*/false);
12436     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12437   }
12438   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12439   MoveAssignOperator->markUsed(Context);
12440 
12441   if (ASTMutationListener *L = getASTMutationListener()) {
12442     L->CompletedImplicitDefinition(MoveAssignOperator);
12443   }
12444 }
12445 
12446 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12447                                                     CXXRecordDecl *ClassDecl) {
12448   // C++ [class.copy]p4:
12449   //   If the class definition does not explicitly declare a copy
12450   //   constructor, one is declared implicitly.
12451   assert(ClassDecl->needsImplicitCopyConstructor());
12452 
12453   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12454   if (DSM.isAlreadyBeingDeclared())
12455     return nullptr;
12456 
12457   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12458   QualType ArgType = ClassType;
12459   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12460   if (Const)
12461     ArgType = ArgType.withConst();
12462   ArgType = Context.getLValueReferenceType(ArgType);
12463 
12464   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12465                                                      CXXCopyConstructor,
12466                                                      Const);
12467 
12468   DeclarationName Name
12469     = Context.DeclarationNames.getCXXConstructorName(
12470                                            Context.getCanonicalType(ClassType));
12471   SourceLocation ClassLoc = ClassDecl->getLocation();
12472   DeclarationNameInfo NameInfo(Name, ClassLoc);
12473 
12474   //   An implicitly-declared copy constructor is an inline public
12475   //   member of its class.
12476   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12477       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12478       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12479       Constexpr);
12480   CopyConstructor->setAccess(AS_public);
12481   CopyConstructor->setDefaulted();
12482 
12483   if (getLangOpts().CUDA) {
12484     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12485                                             CopyConstructor,
12486                                             /* ConstRHS */ Const,
12487                                             /* Diagnose */ false);
12488   }
12489 
12490   // Build an exception specification pointing back at this member.
12491   FunctionProtoType::ExtProtoInfo EPI =
12492       getImplicitMethodEPI(*this, CopyConstructor);
12493   CopyConstructor->setType(
12494       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12495 
12496   // Add the parameter to the constructor.
12497   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12498                                                ClassLoc, ClassLoc,
12499                                                /*IdentifierInfo=*/nullptr,
12500                                                ArgType, /*TInfo=*/nullptr,
12501                                                SC_None, nullptr);
12502   CopyConstructor->setParams(FromParam);
12503 
12504   CopyConstructor->setTrivial(
12505       ClassDecl->needsOverloadResolutionForCopyConstructor()
12506           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12507           : ClassDecl->hasTrivialCopyConstructor());
12508 
12509   CopyConstructor->setTrivialForCall(
12510       ClassDecl->hasAttr<TrivialABIAttr>() ||
12511       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12512            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12513              TAH_ConsiderTrivialABI)
12514            : ClassDecl->hasTrivialCopyConstructorForCall()));
12515 
12516   // Note that we have declared this constructor.
12517   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12518 
12519   Scope *S = getScopeForContext(ClassDecl);
12520   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12521 
12522   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12523     ClassDecl->setImplicitCopyConstructorIsDeleted();
12524     SetDeclDeleted(CopyConstructor, ClassLoc);
12525   }
12526 
12527   if (S)
12528     PushOnScopeChains(CopyConstructor, S, false);
12529   ClassDecl->addDecl(CopyConstructor);
12530 
12531   return CopyConstructor;
12532 }
12533 
12534 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12535                                          CXXConstructorDecl *CopyConstructor) {
12536   assert((CopyConstructor->isDefaulted() &&
12537           CopyConstructor->isCopyConstructor() &&
12538           !CopyConstructor->doesThisDeclarationHaveABody() &&
12539           !CopyConstructor->isDeleted()) &&
12540          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12541   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12542     return;
12543 
12544   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12545   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12546 
12547   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12548 
12549   // The exception specification is needed because we are defining the
12550   // function.
12551   ResolveExceptionSpec(CurrentLocation,
12552                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12553   MarkVTableUsed(CurrentLocation, ClassDecl);
12554 
12555   // Add a context note for diagnostics produced after this point.
12556   Scope.addContextNote(CurrentLocation);
12557 
12558   // C++11 [class.copy]p7:
12559   //   The [definition of an implicitly declared copy constructor] is
12560   //   deprecated if the class has a user-declared copy assignment operator
12561   //   or a user-declared destructor.
12562   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12563     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12564 
12565   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12566     CopyConstructor->setInvalidDecl();
12567   }  else {
12568     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12569                              ? CopyConstructor->getEndLoc()
12570                              : CopyConstructor->getLocation();
12571     Sema::CompoundScopeRAII CompoundScope(*this);
12572     CopyConstructor->setBody(
12573         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12574     CopyConstructor->markUsed(Context);
12575   }
12576 
12577   if (ASTMutationListener *L = getASTMutationListener()) {
12578     L->CompletedImplicitDefinition(CopyConstructor);
12579   }
12580 }
12581 
12582 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12583                                                     CXXRecordDecl *ClassDecl) {
12584   assert(ClassDecl->needsImplicitMoveConstructor());
12585 
12586   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12587   if (DSM.isAlreadyBeingDeclared())
12588     return nullptr;
12589 
12590   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12591   QualType ArgType = Context.getRValueReferenceType(ClassType);
12592 
12593   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12594                                                      CXXMoveConstructor,
12595                                                      false);
12596 
12597   DeclarationName Name
12598     = Context.DeclarationNames.getCXXConstructorName(
12599                                            Context.getCanonicalType(ClassType));
12600   SourceLocation ClassLoc = ClassDecl->getLocation();
12601   DeclarationNameInfo NameInfo(Name, ClassLoc);
12602 
12603   // C++11 [class.copy]p11:
12604   //   An implicitly-declared copy/move constructor is an inline public
12605   //   member of its class.
12606   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12607       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12608       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12609       Constexpr);
12610   MoveConstructor->setAccess(AS_public);
12611   MoveConstructor->setDefaulted();
12612 
12613   if (getLangOpts().CUDA) {
12614     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12615                                             MoveConstructor,
12616                                             /* ConstRHS */ false,
12617                                             /* Diagnose */ false);
12618   }
12619 
12620   // Build an exception specification pointing back at this member.
12621   FunctionProtoType::ExtProtoInfo EPI =
12622       getImplicitMethodEPI(*this, MoveConstructor);
12623   MoveConstructor->setType(
12624       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12625 
12626   // Add the parameter to the constructor.
12627   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12628                                                ClassLoc, ClassLoc,
12629                                                /*IdentifierInfo=*/nullptr,
12630                                                ArgType, /*TInfo=*/nullptr,
12631                                                SC_None, nullptr);
12632   MoveConstructor->setParams(FromParam);
12633 
12634   MoveConstructor->setTrivial(
12635       ClassDecl->needsOverloadResolutionForMoveConstructor()
12636           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12637           : ClassDecl->hasTrivialMoveConstructor());
12638 
12639   MoveConstructor->setTrivialForCall(
12640       ClassDecl->hasAttr<TrivialABIAttr>() ||
12641       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12642            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12643                                     TAH_ConsiderTrivialABI)
12644            : ClassDecl->hasTrivialMoveConstructorForCall()));
12645 
12646   // Note that we have declared this constructor.
12647   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12648 
12649   Scope *S = getScopeForContext(ClassDecl);
12650   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12651 
12652   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12653     ClassDecl->setImplicitMoveConstructorIsDeleted();
12654     SetDeclDeleted(MoveConstructor, ClassLoc);
12655   }
12656 
12657   if (S)
12658     PushOnScopeChains(MoveConstructor, S, false);
12659   ClassDecl->addDecl(MoveConstructor);
12660 
12661   return MoveConstructor;
12662 }
12663 
12664 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12665                                          CXXConstructorDecl *MoveConstructor) {
12666   assert((MoveConstructor->isDefaulted() &&
12667           MoveConstructor->isMoveConstructor() &&
12668           !MoveConstructor->doesThisDeclarationHaveABody() &&
12669           !MoveConstructor->isDeleted()) &&
12670          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12671   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12672     return;
12673 
12674   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12675   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12676 
12677   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12678 
12679   // The exception specification is needed because we are defining the
12680   // function.
12681   ResolveExceptionSpec(CurrentLocation,
12682                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12683   MarkVTableUsed(CurrentLocation, ClassDecl);
12684 
12685   // Add a context note for diagnostics produced after this point.
12686   Scope.addContextNote(CurrentLocation);
12687 
12688   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12689     MoveConstructor->setInvalidDecl();
12690   } else {
12691     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12692                              ? MoveConstructor->getEndLoc()
12693                              : MoveConstructor->getLocation();
12694     Sema::CompoundScopeRAII CompoundScope(*this);
12695     MoveConstructor->setBody(ActOnCompoundStmt(
12696         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12697     MoveConstructor->markUsed(Context);
12698   }
12699 
12700   if (ASTMutationListener *L = getASTMutationListener()) {
12701     L->CompletedImplicitDefinition(MoveConstructor);
12702   }
12703 }
12704 
12705 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12706   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12707 }
12708 
12709 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12710                             SourceLocation CurrentLocation,
12711                             CXXConversionDecl *Conv) {
12712   SynthesizedFunctionScope Scope(*this, Conv);
12713   assert(!Conv->getReturnType()->isUndeducedType());
12714 
12715   CXXRecordDecl *Lambda = Conv->getParent();
12716   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12717   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12718 
12719   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12720     CallOp = InstantiateFunctionDeclaration(
12721         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12722     if (!CallOp)
12723       return;
12724 
12725     Invoker = InstantiateFunctionDeclaration(
12726         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12727     if (!Invoker)
12728       return;
12729   }
12730 
12731   if (CallOp->isInvalidDecl())
12732     return;
12733 
12734   // Mark the call operator referenced (and add to pending instantiations
12735   // if necessary).
12736   // For both the conversion and static-invoker template specializations
12737   // we construct their body's in this function, so no need to add them
12738   // to the PendingInstantiations.
12739   MarkFunctionReferenced(CurrentLocation, CallOp);
12740 
12741   // Fill in the __invoke function with a dummy implementation. IR generation
12742   // will fill in the actual details. Update its type in case it contained
12743   // an 'auto'.
12744   Invoker->markUsed(Context);
12745   Invoker->setReferenced();
12746   Invoker->setType(Conv->getReturnType()->getPointeeType());
12747   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12748 
12749   // Construct the body of the conversion function { return __invoke; }.
12750   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12751                                        VK_LValue, Conv->getLocation()).get();
12752   assert(FunctionRef && "Can't refer to __invoke function?");
12753   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12754   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12755                                      Conv->getLocation()));
12756   Conv->markUsed(Context);
12757   Conv->setReferenced();
12758 
12759   if (ASTMutationListener *L = getASTMutationListener()) {
12760     L->CompletedImplicitDefinition(Conv);
12761     L->CompletedImplicitDefinition(Invoker);
12762   }
12763 }
12764 
12765 
12766 
12767 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12768        SourceLocation CurrentLocation,
12769        CXXConversionDecl *Conv)
12770 {
12771   assert(!Conv->getParent()->isGenericLambda());
12772 
12773   SynthesizedFunctionScope Scope(*this, Conv);
12774 
12775   // Copy-initialize the lambda object as needed to capture it.
12776   Expr *This = ActOnCXXThis(CurrentLocation).get();
12777   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12778 
12779   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12780                                                         Conv->getLocation(),
12781                                                         Conv, DerefThis);
12782 
12783   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12784   // behavior.  Note that only the general conversion function does this
12785   // (since it's unusable otherwise); in the case where we inline the
12786   // block literal, it has block literal lifetime semantics.
12787   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12788     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12789                                           CK_CopyAndAutoreleaseBlockObject,
12790                                           BuildBlock.get(), nullptr, VK_RValue);
12791 
12792   if (BuildBlock.isInvalid()) {
12793     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12794     Conv->setInvalidDecl();
12795     return;
12796   }
12797 
12798   // Create the return statement that returns the block from the conversion
12799   // function.
12800   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12801   if (Return.isInvalid()) {
12802     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12803     Conv->setInvalidDecl();
12804     return;
12805   }
12806 
12807   // Set the body of the conversion function.
12808   Stmt *ReturnS = Return.get();
12809   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12810                                      Conv->getLocation()));
12811   Conv->markUsed(Context);
12812 
12813   // We're done; notify the mutation listener, if any.
12814   if (ASTMutationListener *L = getASTMutationListener()) {
12815     L->CompletedImplicitDefinition(Conv);
12816   }
12817 }
12818 
12819 /// Determine whether the given list arguments contains exactly one
12820 /// "real" (non-default) argument.
12821 static bool hasOneRealArgument(MultiExprArg Args) {
12822   switch (Args.size()) {
12823   case 0:
12824     return false;
12825 
12826   default:
12827     if (!Args[1]->isDefaultArgument())
12828       return false;
12829 
12830     LLVM_FALLTHROUGH;
12831   case 1:
12832     return !Args[0]->isDefaultArgument();
12833   }
12834 
12835   return false;
12836 }
12837 
12838 ExprResult
12839 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12840                             NamedDecl *FoundDecl,
12841                             CXXConstructorDecl *Constructor,
12842                             MultiExprArg ExprArgs,
12843                             bool HadMultipleCandidates,
12844                             bool IsListInitialization,
12845                             bool IsStdInitListInitialization,
12846                             bool RequiresZeroInit,
12847                             unsigned ConstructKind,
12848                             SourceRange ParenRange) {
12849   bool Elidable = false;
12850 
12851   // C++0x [class.copy]p34:
12852   //   When certain criteria are met, an implementation is allowed to
12853   //   omit the copy/move construction of a class object, even if the
12854   //   copy/move constructor and/or destructor for the object have
12855   //   side effects. [...]
12856   //     - when a temporary class object that has not been bound to a
12857   //       reference (12.2) would be copied/moved to a class object
12858   //       with the same cv-unqualified type, the copy/move operation
12859   //       can be omitted by constructing the temporary object
12860   //       directly into the target of the omitted copy/move
12861   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12862       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12863     Expr *SubExpr = ExprArgs[0];
12864     Elidable = SubExpr->isTemporaryObject(
12865         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12866   }
12867 
12868   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12869                                FoundDecl, Constructor,
12870                                Elidable, ExprArgs, HadMultipleCandidates,
12871                                IsListInitialization,
12872                                IsStdInitListInitialization, RequiresZeroInit,
12873                                ConstructKind, ParenRange);
12874 }
12875 
12876 ExprResult
12877 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12878                             NamedDecl *FoundDecl,
12879                             CXXConstructorDecl *Constructor,
12880                             bool Elidable,
12881                             MultiExprArg ExprArgs,
12882                             bool HadMultipleCandidates,
12883                             bool IsListInitialization,
12884                             bool IsStdInitListInitialization,
12885                             bool RequiresZeroInit,
12886                             unsigned ConstructKind,
12887                             SourceRange ParenRange) {
12888   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12889     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12890     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12891       return ExprError();
12892   }
12893 
12894   return BuildCXXConstructExpr(
12895       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12896       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12897       RequiresZeroInit, ConstructKind, ParenRange);
12898 }
12899 
12900 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12901 /// including handling of its default argument expressions.
12902 ExprResult
12903 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12904                             CXXConstructorDecl *Constructor,
12905                             bool Elidable,
12906                             MultiExprArg ExprArgs,
12907                             bool HadMultipleCandidates,
12908                             bool IsListInitialization,
12909                             bool IsStdInitListInitialization,
12910                             bool RequiresZeroInit,
12911                             unsigned ConstructKind,
12912                             SourceRange ParenRange) {
12913   assert(declaresSameEntity(
12914              Constructor->getParent(),
12915              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12916          "given constructor for wrong type");
12917   MarkFunctionReferenced(ConstructLoc, Constructor);
12918   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12919     return ExprError();
12920 
12921   return CXXConstructExpr::Create(
12922       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12923       ExprArgs, HadMultipleCandidates, IsListInitialization,
12924       IsStdInitListInitialization, RequiresZeroInit,
12925       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12926       ParenRange);
12927 }
12928 
12929 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12930   assert(Field->hasInClassInitializer());
12931 
12932   // If we already have the in-class initializer nothing needs to be done.
12933   if (Field->getInClassInitializer())
12934     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12935 
12936   // If we might have already tried and failed to instantiate, don't try again.
12937   if (Field->isInvalidDecl())
12938     return ExprError();
12939 
12940   // Maybe we haven't instantiated the in-class initializer. Go check the
12941   // pattern FieldDecl to see if it has one.
12942   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12943 
12944   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12945     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12946     DeclContext::lookup_result Lookup =
12947         ClassPattern->lookup(Field->getDeclName());
12948 
12949     // Lookup can return at most two results: the pattern for the field, or the
12950     // injected class name of the parent record. No other member can have the
12951     // same name as the field.
12952     // In modules mode, lookup can return multiple results (coming from
12953     // different modules).
12954     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12955            "more than two lookup results for field name");
12956     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12957     if (!Pattern) {
12958       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12959              "cannot have other non-field member with same name");
12960       for (auto L : Lookup)
12961         if (isa<FieldDecl>(L)) {
12962           Pattern = cast<FieldDecl>(L);
12963           break;
12964         }
12965       assert(Pattern && "We must have set the Pattern!");
12966     }
12967 
12968     if (!Pattern->hasInClassInitializer() ||
12969         InstantiateInClassInitializer(Loc, Field, Pattern,
12970                                       getTemplateInstantiationArgs(Field))) {
12971       // Don't diagnose this again.
12972       Field->setInvalidDecl();
12973       return ExprError();
12974     }
12975     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12976   }
12977 
12978   // DR1351:
12979   //   If the brace-or-equal-initializer of a non-static data member
12980   //   invokes a defaulted default constructor of its class or of an
12981   //   enclosing class in a potentially evaluated subexpression, the
12982   //   program is ill-formed.
12983   //
12984   // This resolution is unworkable: the exception specification of the
12985   // default constructor can be needed in an unevaluated context, in
12986   // particular, in the operand of a noexcept-expression, and we can be
12987   // unable to compute an exception specification for an enclosed class.
12988   //
12989   // Any attempt to resolve the exception specification of a defaulted default
12990   // constructor before the initializer is lexically complete will ultimately
12991   // come here at which point we can diagnose it.
12992   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12993   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12994       << OutermostClass << Field;
12995   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
12996   // Recover by marking the field invalid, unless we're in a SFINAE context.
12997   if (!isSFINAEContext())
12998     Field->setInvalidDecl();
12999   return ExprError();
13000 }
13001 
13002 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13003   if (VD->isInvalidDecl()) return;
13004 
13005   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13006   if (ClassDecl->isInvalidDecl()) return;
13007   if (ClassDecl->hasIrrelevantDestructor()) return;
13008   if (ClassDecl->isDependentContext()) return;
13009 
13010   if (VD->isNoDestroy(getASTContext()))
13011     return;
13012 
13013   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13014   MarkFunctionReferenced(VD->getLocation(), Destructor);
13015   CheckDestructorAccess(VD->getLocation(), Destructor,
13016                         PDiag(diag::err_access_dtor_var)
13017                         << VD->getDeclName()
13018                         << VD->getType());
13019   DiagnoseUseOfDecl(Destructor, VD->getLocation());
13020 
13021   if (Destructor->isTrivial()) return;
13022   if (!VD->hasGlobalStorage()) return;
13023 
13024   // Emit warning for non-trivial dtor in global scope (a real global,
13025   // class-static, function-static).
13026   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13027 
13028   // TODO: this should be re-enabled for static locals by !CXAAtExit
13029   if (!VD->isStaticLocal())
13030     Diag(VD->getLocation(), diag::warn_global_destructor);
13031 }
13032 
13033 /// Given a constructor and the set of arguments provided for the
13034 /// constructor, convert the arguments and add any required default arguments
13035 /// to form a proper call to this constructor.
13036 ///
13037 /// \returns true if an error occurred, false otherwise.
13038 bool
13039 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13040                               MultiExprArg ArgsPtr,
13041                               SourceLocation Loc,
13042                               SmallVectorImpl<Expr*> &ConvertedArgs,
13043                               bool AllowExplicit,
13044                               bool IsListInitialization) {
13045   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13046   unsigned NumArgs = ArgsPtr.size();
13047   Expr **Args = ArgsPtr.data();
13048 
13049   const FunctionProtoType *Proto
13050     = Constructor->getType()->getAs<FunctionProtoType>();
13051   assert(Proto && "Constructor without a prototype?");
13052   unsigned NumParams = Proto->getNumParams();
13053 
13054   // If too few arguments are available, we'll fill in the rest with defaults.
13055   if (NumArgs < NumParams)
13056     ConvertedArgs.reserve(NumParams);
13057   else
13058     ConvertedArgs.reserve(NumArgs);
13059 
13060   VariadicCallType CallType =
13061     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13062   SmallVector<Expr *, 8> AllArgs;
13063   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13064                                         Proto, 0,
13065                                         llvm::makeArrayRef(Args, NumArgs),
13066                                         AllArgs,
13067                                         CallType, AllowExplicit,
13068                                         IsListInitialization);
13069   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13070 
13071   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13072 
13073   CheckConstructorCall(Constructor,
13074                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13075                        Proto, Loc);
13076 
13077   return Invalid;
13078 }
13079 
13080 static inline bool
13081 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13082                                        const FunctionDecl *FnDecl) {
13083   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13084   if (isa<NamespaceDecl>(DC)) {
13085     return SemaRef.Diag(FnDecl->getLocation(),
13086                         diag::err_operator_new_delete_declared_in_namespace)
13087       << FnDecl->getDeclName();
13088   }
13089 
13090   if (isa<TranslationUnitDecl>(DC) &&
13091       FnDecl->getStorageClass() == SC_Static) {
13092     return SemaRef.Diag(FnDecl->getLocation(),
13093                         diag::err_operator_new_delete_declared_static)
13094       << FnDecl->getDeclName();
13095   }
13096 
13097   return false;
13098 }
13099 
13100 static QualType
13101 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13102   QualType QTy = PtrTy->getPointeeType();
13103   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13104   return SemaRef.Context.getPointerType(QTy);
13105 }
13106 
13107 static inline bool
13108 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13109                             CanQualType ExpectedResultType,
13110                             CanQualType ExpectedFirstParamType,
13111                             unsigned DependentParamTypeDiag,
13112                             unsigned InvalidParamTypeDiag) {
13113   QualType ResultType =
13114       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13115 
13116   // Check that the result type is not dependent.
13117   if (ResultType->isDependentType())
13118     return SemaRef.Diag(FnDecl->getLocation(),
13119                         diag::err_operator_new_delete_dependent_result_type)
13120     << FnDecl->getDeclName() << ExpectedResultType;
13121 
13122   // OpenCL C++: the operator is valid on any address space.
13123   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13124     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13125       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13126     }
13127   }
13128 
13129   // Check that the result type is what we expect.
13130   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13131     return SemaRef.Diag(FnDecl->getLocation(),
13132                         diag::err_operator_new_delete_invalid_result_type)
13133     << FnDecl->getDeclName() << ExpectedResultType;
13134 
13135   // A function template must have at least 2 parameters.
13136   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13137     return SemaRef.Diag(FnDecl->getLocation(),
13138                       diag::err_operator_new_delete_template_too_few_parameters)
13139         << FnDecl->getDeclName();
13140 
13141   // The function decl must have at least 1 parameter.
13142   if (FnDecl->getNumParams() == 0)
13143     return SemaRef.Diag(FnDecl->getLocation(),
13144                         diag::err_operator_new_delete_too_few_parameters)
13145       << FnDecl->getDeclName();
13146 
13147   // Check the first parameter type is not dependent.
13148   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13149   if (FirstParamType->isDependentType())
13150     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13151       << FnDecl->getDeclName() << ExpectedFirstParamType;
13152 
13153   // Check that the first parameter type is what we expect.
13154   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13155     // OpenCL C++: the operator is valid on any address space.
13156     if (auto *PtrTy =
13157             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13158       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13159     }
13160   }
13161   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13162       ExpectedFirstParamType)
13163     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13164     << FnDecl->getDeclName() << ExpectedFirstParamType;
13165 
13166   return false;
13167 }
13168 
13169 static bool
13170 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13171   // C++ [basic.stc.dynamic.allocation]p1:
13172   //   A program is ill-formed if an allocation function is declared in a
13173   //   namespace scope other than global scope or declared static in global
13174   //   scope.
13175   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13176     return true;
13177 
13178   CanQualType SizeTy =
13179     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13180 
13181   // C++ [basic.stc.dynamic.allocation]p1:
13182   //  The return type shall be void*. The first parameter shall have type
13183   //  std::size_t.
13184   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13185                                   SizeTy,
13186                                   diag::err_operator_new_dependent_param_type,
13187                                   diag::err_operator_new_param_type))
13188     return true;
13189 
13190   // C++ [basic.stc.dynamic.allocation]p1:
13191   //  The first parameter shall not have an associated default argument.
13192   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13193     return SemaRef.Diag(FnDecl->getLocation(),
13194                         diag::err_operator_new_default_arg)
13195       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13196 
13197   return false;
13198 }
13199 
13200 static bool
13201 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13202   // C++ [basic.stc.dynamic.deallocation]p1:
13203   //   A program is ill-formed if deallocation functions are declared in a
13204   //   namespace scope other than global scope or declared static in global
13205   //   scope.
13206   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13207     return true;
13208 
13209   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13210 
13211   // C++ P0722:
13212   //   Within a class C, the first parameter of a destroying operator delete
13213   //   shall be of type C *. The first parameter of any other deallocation
13214   //   function shall be of type void *.
13215   CanQualType ExpectedFirstParamType =
13216       MD && MD->isDestroyingOperatorDelete()
13217           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13218                 SemaRef.Context.getRecordType(MD->getParent())))
13219           : SemaRef.Context.VoidPtrTy;
13220 
13221   // C++ [basic.stc.dynamic.deallocation]p2:
13222   //   Each deallocation function shall return void
13223   if (CheckOperatorNewDeleteTypes(
13224           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13225           diag::err_operator_delete_dependent_param_type,
13226           diag::err_operator_delete_param_type))
13227     return true;
13228 
13229   // C++ P0722:
13230   //   A destroying operator delete shall be a usual deallocation function.
13231   if (MD && !MD->getParent()->isDependentContext() &&
13232       MD->isDestroyingOperatorDelete() &&
13233       !SemaRef.isUsualDeallocationFunction(MD)) {
13234     SemaRef.Diag(MD->getLocation(),
13235                  diag::err_destroying_operator_delete_not_usual);
13236     return true;
13237   }
13238 
13239   return false;
13240 }
13241 
13242 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13243 /// of this overloaded operator is well-formed. If so, returns false;
13244 /// otherwise, emits appropriate diagnostics and returns true.
13245 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13246   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13247          "Expected an overloaded operator declaration");
13248 
13249   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13250 
13251   // C++ [over.oper]p5:
13252   //   The allocation and deallocation functions, operator new,
13253   //   operator new[], operator delete and operator delete[], are
13254   //   described completely in 3.7.3. The attributes and restrictions
13255   //   found in the rest of this subclause do not apply to them unless
13256   //   explicitly stated in 3.7.3.
13257   if (Op == OO_Delete || Op == OO_Array_Delete)
13258     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13259 
13260   if (Op == OO_New || Op == OO_Array_New)
13261     return CheckOperatorNewDeclaration(*this, FnDecl);
13262 
13263   // C++ [over.oper]p6:
13264   //   An operator function shall either be a non-static member
13265   //   function or be a non-member function and have at least one
13266   //   parameter whose type is a class, a reference to a class, an
13267   //   enumeration, or a reference to an enumeration.
13268   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13269     if (MethodDecl->isStatic())
13270       return Diag(FnDecl->getLocation(),
13271                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13272   } else {
13273     bool ClassOrEnumParam = false;
13274     for (auto Param : FnDecl->parameters()) {
13275       QualType ParamType = Param->getType().getNonReferenceType();
13276       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13277           ParamType->isEnumeralType()) {
13278         ClassOrEnumParam = true;
13279         break;
13280       }
13281     }
13282 
13283     if (!ClassOrEnumParam)
13284       return Diag(FnDecl->getLocation(),
13285                   diag::err_operator_overload_needs_class_or_enum)
13286         << FnDecl->getDeclName();
13287   }
13288 
13289   // C++ [over.oper]p8:
13290   //   An operator function cannot have default arguments (8.3.6),
13291   //   except where explicitly stated below.
13292   //
13293   // Only the function-call operator allows default arguments
13294   // (C++ [over.call]p1).
13295   if (Op != OO_Call) {
13296     for (auto Param : FnDecl->parameters()) {
13297       if (Param->hasDefaultArg())
13298         return Diag(Param->getLocation(),
13299                     diag::err_operator_overload_default_arg)
13300           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13301     }
13302   }
13303 
13304   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13305     { false, false, false }
13306 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13307     , { Unary, Binary, MemberOnly }
13308 #include "clang/Basic/OperatorKinds.def"
13309   };
13310 
13311   bool CanBeUnaryOperator = OperatorUses[Op][0];
13312   bool CanBeBinaryOperator = OperatorUses[Op][1];
13313   bool MustBeMemberOperator = OperatorUses[Op][2];
13314 
13315   // C++ [over.oper]p8:
13316   //   [...] Operator functions cannot have more or fewer parameters
13317   //   than the number required for the corresponding operator, as
13318   //   described in the rest of this subclause.
13319   unsigned NumParams = FnDecl->getNumParams()
13320                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13321   if (Op != OO_Call &&
13322       ((NumParams == 1 && !CanBeUnaryOperator) ||
13323        (NumParams == 2 && !CanBeBinaryOperator) ||
13324        (NumParams < 1) || (NumParams > 2))) {
13325     // We have the wrong number of parameters.
13326     unsigned ErrorKind;
13327     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13328       ErrorKind = 2;  // 2 -> unary or binary.
13329     } else if (CanBeUnaryOperator) {
13330       ErrorKind = 0;  // 0 -> unary
13331     } else {
13332       assert(CanBeBinaryOperator &&
13333              "All non-call overloaded operators are unary or binary!");
13334       ErrorKind = 1;  // 1 -> binary
13335     }
13336 
13337     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13338       << FnDecl->getDeclName() << NumParams << ErrorKind;
13339   }
13340 
13341   // Overloaded operators other than operator() cannot be variadic.
13342   if (Op != OO_Call &&
13343       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13344     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13345       << FnDecl->getDeclName();
13346   }
13347 
13348   // Some operators must be non-static member functions.
13349   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13350     return Diag(FnDecl->getLocation(),
13351                 diag::err_operator_overload_must_be_member)
13352       << FnDecl->getDeclName();
13353   }
13354 
13355   // C++ [over.inc]p1:
13356   //   The user-defined function called operator++ implements the
13357   //   prefix and postfix ++ operator. If this function is a member
13358   //   function with no parameters, or a non-member function with one
13359   //   parameter of class or enumeration type, it defines the prefix
13360   //   increment operator ++ for objects of that type. If the function
13361   //   is a member function with one parameter (which shall be of type
13362   //   int) or a non-member function with two parameters (the second
13363   //   of which shall be of type int), it defines the postfix
13364   //   increment operator ++ for objects of that type.
13365   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13366     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13367     QualType ParamType = LastParam->getType();
13368 
13369     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13370         !ParamType->isDependentType())
13371       return Diag(LastParam->getLocation(),
13372                   diag::err_operator_overload_post_incdec_must_be_int)
13373         << LastParam->getType() << (Op == OO_MinusMinus);
13374   }
13375 
13376   return false;
13377 }
13378 
13379 static bool
13380 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13381                                           FunctionTemplateDecl *TpDecl) {
13382   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13383 
13384   // Must have one or two template parameters.
13385   if (TemplateParams->size() == 1) {
13386     NonTypeTemplateParmDecl *PmDecl =
13387         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13388 
13389     // The template parameter must be a char parameter pack.
13390     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13391         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13392       return false;
13393 
13394   } else if (TemplateParams->size() == 2) {
13395     TemplateTypeParmDecl *PmType =
13396         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13397     NonTypeTemplateParmDecl *PmArgs =
13398         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13399 
13400     // The second template parameter must be a parameter pack with the
13401     // first template parameter as its type.
13402     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13403         PmArgs->isTemplateParameterPack()) {
13404       const TemplateTypeParmType *TArgs =
13405           PmArgs->getType()->getAs<TemplateTypeParmType>();
13406       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13407           TArgs->getIndex() == PmType->getIndex()) {
13408         if (!SemaRef.inTemplateInstantiation())
13409           SemaRef.Diag(TpDecl->getLocation(),
13410                        diag::ext_string_literal_operator_template);
13411         return false;
13412       }
13413     }
13414   }
13415 
13416   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13417                diag::err_literal_operator_template)
13418       << TpDecl->getTemplateParameters()->getSourceRange();
13419   return true;
13420 }
13421 
13422 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13423 /// of this literal operator function is well-formed. If so, returns
13424 /// false; otherwise, emits appropriate diagnostics and returns true.
13425 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13426   if (isa<CXXMethodDecl>(FnDecl)) {
13427     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13428       << FnDecl->getDeclName();
13429     return true;
13430   }
13431 
13432   if (FnDecl->isExternC()) {
13433     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13434     if (const LinkageSpecDecl *LSD =
13435             FnDecl->getDeclContext()->getExternCContext())
13436       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13437     return true;
13438   }
13439 
13440   // This might be the definition of a literal operator template.
13441   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13442 
13443   // This might be a specialization of a literal operator template.
13444   if (!TpDecl)
13445     TpDecl = FnDecl->getPrimaryTemplate();
13446 
13447   // template <char...> type operator "" name() and
13448   // template <class T, T...> type operator "" name() are the only valid
13449   // template signatures, and the only valid signatures with no parameters.
13450   if (TpDecl) {
13451     if (FnDecl->param_size() != 0) {
13452       Diag(FnDecl->getLocation(),
13453            diag::err_literal_operator_template_with_params);
13454       return true;
13455     }
13456 
13457     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13458       return true;
13459 
13460   } else if (FnDecl->param_size() == 1) {
13461     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13462 
13463     QualType ParamType = Param->getType().getUnqualifiedType();
13464 
13465     // Only unsigned long long int, long double, any character type, and const
13466     // char * are allowed as the only parameters.
13467     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13468         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13469         Context.hasSameType(ParamType, Context.CharTy) ||
13470         Context.hasSameType(ParamType, Context.WideCharTy) ||
13471         Context.hasSameType(ParamType, Context.Char8Ty) ||
13472         Context.hasSameType(ParamType, Context.Char16Ty) ||
13473         Context.hasSameType(ParamType, Context.Char32Ty)) {
13474     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13475       QualType InnerType = Ptr->getPointeeType();
13476 
13477       // Pointer parameter must be a const char *.
13478       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13479                                 Context.CharTy) &&
13480             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13481         Diag(Param->getSourceRange().getBegin(),
13482              diag::err_literal_operator_param)
13483             << ParamType << "'const char *'" << Param->getSourceRange();
13484         return true;
13485       }
13486 
13487     } else if (ParamType->isRealFloatingType()) {
13488       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13489           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13490       return true;
13491 
13492     } else if (ParamType->isIntegerType()) {
13493       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13494           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13495       return true;
13496 
13497     } else {
13498       Diag(Param->getSourceRange().getBegin(),
13499            diag::err_literal_operator_invalid_param)
13500           << ParamType << Param->getSourceRange();
13501       return true;
13502     }
13503 
13504   } else if (FnDecl->param_size() == 2) {
13505     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13506 
13507     // First, verify that the first parameter is correct.
13508 
13509     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13510 
13511     // Two parameter function must have a pointer to const as a
13512     // first parameter; let's strip those qualifiers.
13513     const PointerType *PT = FirstParamType->getAs<PointerType>();
13514 
13515     if (!PT) {
13516       Diag((*Param)->getSourceRange().getBegin(),
13517            diag::err_literal_operator_param)
13518           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13519       return true;
13520     }
13521 
13522     QualType PointeeType = PT->getPointeeType();
13523     // First parameter must be const
13524     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13525       Diag((*Param)->getSourceRange().getBegin(),
13526            diag::err_literal_operator_param)
13527           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13528       return true;
13529     }
13530 
13531     QualType InnerType = PointeeType.getUnqualifiedType();
13532     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13533     // const char32_t* are allowed as the first parameter to a two-parameter
13534     // function
13535     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13536           Context.hasSameType(InnerType, Context.WideCharTy) ||
13537           Context.hasSameType(InnerType, Context.Char8Ty) ||
13538           Context.hasSameType(InnerType, Context.Char16Ty) ||
13539           Context.hasSameType(InnerType, Context.Char32Ty))) {
13540       Diag((*Param)->getSourceRange().getBegin(),
13541            diag::err_literal_operator_param)
13542           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13543       return true;
13544     }
13545 
13546     // Move on to the second and final parameter.
13547     ++Param;
13548 
13549     // The second parameter must be a std::size_t.
13550     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13551     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13552       Diag((*Param)->getSourceRange().getBegin(),
13553            diag::err_literal_operator_param)
13554           << SecondParamType << Context.getSizeType()
13555           << (*Param)->getSourceRange();
13556       return true;
13557     }
13558   } else {
13559     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13560     return true;
13561   }
13562 
13563   // Parameters are good.
13564 
13565   // A parameter-declaration-clause containing a default argument is not
13566   // equivalent to any of the permitted forms.
13567   for (auto Param : FnDecl->parameters()) {
13568     if (Param->hasDefaultArg()) {
13569       Diag(Param->getDefaultArgRange().getBegin(),
13570            diag::err_literal_operator_default_argument)
13571         << Param->getDefaultArgRange();
13572       break;
13573     }
13574   }
13575 
13576   StringRef LiteralName
13577     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13578   if (LiteralName[0] != '_' &&
13579       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13580     // C++11 [usrlit.suffix]p1:
13581     //   Literal suffix identifiers that do not start with an underscore
13582     //   are reserved for future standardization.
13583     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13584       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13585   }
13586 
13587   return false;
13588 }
13589 
13590 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13591 /// linkage specification, including the language and (if present)
13592 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13593 /// language string literal. LBraceLoc, if valid, provides the location of
13594 /// the '{' brace. Otherwise, this linkage specification does not
13595 /// have any braces.
13596 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13597                                            Expr *LangStr,
13598                                            SourceLocation LBraceLoc) {
13599   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13600   if (!Lit->isAscii()) {
13601     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13602       << LangStr->getSourceRange();
13603     return nullptr;
13604   }
13605 
13606   StringRef Lang = Lit->getString();
13607   LinkageSpecDecl::LanguageIDs Language;
13608   if (Lang == "C")
13609     Language = LinkageSpecDecl::lang_c;
13610   else if (Lang == "C++")
13611     Language = LinkageSpecDecl::lang_cxx;
13612   else {
13613     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13614       << LangStr->getSourceRange();
13615     return nullptr;
13616   }
13617 
13618   // FIXME: Add all the various semantics of linkage specifications
13619 
13620   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13621                                                LangStr->getExprLoc(), Language,
13622                                                LBraceLoc.isValid());
13623   CurContext->addDecl(D);
13624   PushDeclContext(S, D);
13625   return D;
13626 }
13627 
13628 /// ActOnFinishLinkageSpecification - Complete the definition of
13629 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13630 /// valid, it's the position of the closing '}' brace in a linkage
13631 /// specification that uses braces.
13632 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13633                                             Decl *LinkageSpec,
13634                                             SourceLocation RBraceLoc) {
13635   if (RBraceLoc.isValid()) {
13636     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13637     LSDecl->setRBraceLoc(RBraceLoc);
13638   }
13639   PopDeclContext();
13640   return LinkageSpec;
13641 }
13642 
13643 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13644                                   const ParsedAttributesView &AttrList,
13645                                   SourceLocation SemiLoc) {
13646   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13647   // Attribute declarations appertain to empty declaration so we handle
13648   // them here.
13649   ProcessDeclAttributeList(S, ED, AttrList);
13650 
13651   CurContext->addDecl(ED);
13652   return ED;
13653 }
13654 
13655 /// Perform semantic analysis for the variable declaration that
13656 /// occurs within a C++ catch clause, returning the newly-created
13657 /// variable.
13658 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13659                                          TypeSourceInfo *TInfo,
13660                                          SourceLocation StartLoc,
13661                                          SourceLocation Loc,
13662                                          IdentifierInfo *Name) {
13663   bool Invalid = false;
13664   QualType ExDeclType = TInfo->getType();
13665 
13666   // Arrays and functions decay.
13667   if (ExDeclType->isArrayType())
13668     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13669   else if (ExDeclType->isFunctionType())
13670     ExDeclType = Context.getPointerType(ExDeclType);
13671 
13672   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13673   // The exception-declaration shall not denote a pointer or reference to an
13674   // incomplete type, other than [cv] void*.
13675   // N2844 forbids rvalue references.
13676   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13677     Diag(Loc, diag::err_catch_rvalue_ref);
13678     Invalid = true;
13679   }
13680 
13681   if (ExDeclType->isVariablyModifiedType()) {
13682     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13683     Invalid = true;
13684   }
13685 
13686   QualType BaseType = ExDeclType;
13687   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13688   unsigned DK = diag::err_catch_incomplete;
13689   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13690     BaseType = Ptr->getPointeeType();
13691     Mode = 1;
13692     DK = diag::err_catch_incomplete_ptr;
13693   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13694     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13695     BaseType = Ref->getPointeeType();
13696     Mode = 2;
13697     DK = diag::err_catch_incomplete_ref;
13698   }
13699   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13700       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13701     Invalid = true;
13702 
13703   if (!Invalid && !ExDeclType->isDependentType() &&
13704       RequireNonAbstractType(Loc, ExDeclType,
13705                              diag::err_abstract_type_in_decl,
13706                              AbstractVariableType))
13707     Invalid = true;
13708 
13709   // Only the non-fragile NeXT runtime currently supports C++ catches
13710   // of ObjC types, and no runtime supports catching ObjC types by value.
13711   if (!Invalid && getLangOpts().ObjC) {
13712     QualType T = ExDeclType;
13713     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13714       T = RT->getPointeeType();
13715 
13716     if (T->isObjCObjectType()) {
13717       Diag(Loc, diag::err_objc_object_catch);
13718       Invalid = true;
13719     } else if (T->isObjCObjectPointerType()) {
13720       // FIXME: should this be a test for macosx-fragile specifically?
13721       if (getLangOpts().ObjCRuntime.isFragile())
13722         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13723     }
13724   }
13725 
13726   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13727                                     ExDeclType, TInfo, SC_None);
13728   ExDecl->setExceptionVariable(true);
13729 
13730   // In ARC, infer 'retaining' for variables of retainable type.
13731   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13732     Invalid = true;
13733 
13734   if (!Invalid && !ExDeclType->isDependentType()) {
13735     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13736       // Insulate this from anything else we might currently be parsing.
13737       EnterExpressionEvaluationContext scope(
13738           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13739 
13740       // C++ [except.handle]p16:
13741       //   The object declared in an exception-declaration or, if the
13742       //   exception-declaration does not specify a name, a temporary (12.2) is
13743       //   copy-initialized (8.5) from the exception object. [...]
13744       //   The object is destroyed when the handler exits, after the destruction
13745       //   of any automatic objects initialized within the handler.
13746       //
13747       // We just pretend to initialize the object with itself, then make sure
13748       // it can be destroyed later.
13749       QualType initType = Context.getExceptionObjectType(ExDeclType);
13750 
13751       InitializedEntity entity =
13752         InitializedEntity::InitializeVariable(ExDecl);
13753       InitializationKind initKind =
13754         InitializationKind::CreateCopy(Loc, SourceLocation());
13755 
13756       Expr *opaqueValue =
13757         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13758       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13759       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13760       if (result.isInvalid())
13761         Invalid = true;
13762       else {
13763         // If the constructor used was non-trivial, set this as the
13764         // "initializer".
13765         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13766         if (!construct->getConstructor()->isTrivial()) {
13767           Expr *init = MaybeCreateExprWithCleanups(construct);
13768           ExDecl->setInit(init);
13769         }
13770 
13771         // And make sure it's destructable.
13772         FinalizeVarWithDestructor(ExDecl, recordType);
13773       }
13774     }
13775   }
13776 
13777   if (Invalid)
13778     ExDecl->setInvalidDecl();
13779 
13780   return ExDecl;
13781 }
13782 
13783 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13784 /// handler.
13785 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13786   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13787   bool Invalid = D.isInvalidType();
13788 
13789   // Check for unexpanded parameter packs.
13790   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13791                                       UPPC_ExceptionType)) {
13792     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13793                                              D.getIdentifierLoc());
13794     Invalid = true;
13795   }
13796 
13797   IdentifierInfo *II = D.getIdentifier();
13798   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13799                                              LookupOrdinaryName,
13800                                              ForVisibleRedeclaration)) {
13801     // The scope should be freshly made just for us. There is just no way
13802     // it contains any previous declaration, except for function parameters in
13803     // a function-try-block's catch statement.
13804     assert(!S->isDeclScope(PrevDecl));
13805     if (isDeclInScope(PrevDecl, CurContext, S)) {
13806       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13807         << D.getIdentifier();
13808       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13809       Invalid = true;
13810     } else if (PrevDecl->isTemplateParameter())
13811       // Maybe we will complain about the shadowed template parameter.
13812       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13813   }
13814 
13815   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13816     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13817       << D.getCXXScopeSpec().getRange();
13818     Invalid = true;
13819   }
13820 
13821   VarDecl *ExDecl = BuildExceptionDeclaration(
13822       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13823   if (Invalid)
13824     ExDecl->setInvalidDecl();
13825 
13826   // Add the exception declaration into this scope.
13827   if (II)
13828     PushOnScopeChains(ExDecl, S);
13829   else
13830     CurContext->addDecl(ExDecl);
13831 
13832   ProcessDeclAttributes(S, ExDecl, D);
13833   return ExDecl;
13834 }
13835 
13836 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13837                                          Expr *AssertExpr,
13838                                          Expr *AssertMessageExpr,
13839                                          SourceLocation RParenLoc) {
13840   StringLiteral *AssertMessage =
13841       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13842 
13843   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13844     return nullptr;
13845 
13846   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13847                                       AssertMessage, RParenLoc, false);
13848 }
13849 
13850 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13851                                          Expr *AssertExpr,
13852                                          StringLiteral *AssertMessage,
13853                                          SourceLocation RParenLoc,
13854                                          bool Failed) {
13855   assert(AssertExpr != nullptr && "Expected non-null condition");
13856   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13857       !Failed) {
13858     // In a static_assert-declaration, the constant-expression shall be a
13859     // constant expression that can be contextually converted to bool.
13860     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13861     if (Converted.isInvalid())
13862       Failed = true;
13863     else
13864       Converted = ConstantExpr::Create(Context, Converted.get());
13865 
13866     llvm::APSInt Cond;
13867     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13868           diag::err_static_assert_expression_is_not_constant,
13869           /*AllowFold=*/false).isInvalid())
13870       Failed = true;
13871 
13872     if (!Failed && !Cond) {
13873       SmallString<256> MsgBuffer;
13874       llvm::raw_svector_ostream Msg(MsgBuffer);
13875       if (AssertMessage)
13876         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13877 
13878       Expr *InnerCond = nullptr;
13879       std::string InnerCondDescription;
13880       std::tie(InnerCond, InnerCondDescription) =
13881         findFailedBooleanCondition(Converted.get(),
13882                                    /*AllowTopLevelCond=*/false);
13883       if (InnerCond) {
13884         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13885           << InnerCondDescription << !AssertMessage
13886           << Msg.str() << InnerCond->getSourceRange();
13887       } else {
13888         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13889           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13890       }
13891       Failed = true;
13892     }
13893   }
13894 
13895   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13896                                                   /*DiscardedValue*/false,
13897                                                   /*IsConstexpr*/true);
13898   if (FullAssertExpr.isInvalid())
13899     Failed = true;
13900   else
13901     AssertExpr = FullAssertExpr.get();
13902 
13903   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13904                                         AssertExpr, AssertMessage, RParenLoc,
13905                                         Failed);
13906 
13907   CurContext->addDecl(Decl);
13908   return Decl;
13909 }
13910 
13911 /// Perform semantic analysis of the given friend type declaration.
13912 ///
13913 /// \returns A friend declaration that.
13914 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13915                                       SourceLocation FriendLoc,
13916                                       TypeSourceInfo *TSInfo) {
13917   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13918 
13919   QualType T = TSInfo->getType();
13920   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13921 
13922   // C++03 [class.friend]p2:
13923   //   An elaborated-type-specifier shall be used in a friend declaration
13924   //   for a class.*
13925   //
13926   //   * The class-key of the elaborated-type-specifier is required.
13927   if (!CodeSynthesisContexts.empty()) {
13928     // Do not complain about the form of friend template types during any kind
13929     // of code synthesis. For template instantiation, we will have complained
13930     // when the template was defined.
13931   } else {
13932     if (!T->isElaboratedTypeSpecifier()) {
13933       // If we evaluated the type to a record type, suggest putting
13934       // a tag in front.
13935       if (const RecordType *RT = T->getAs<RecordType>()) {
13936         RecordDecl *RD = RT->getDecl();
13937 
13938         SmallString<16> InsertionText(" ");
13939         InsertionText += RD->getKindName();
13940 
13941         Diag(TypeRange.getBegin(),
13942              getLangOpts().CPlusPlus11 ?
13943                diag::warn_cxx98_compat_unelaborated_friend_type :
13944                diag::ext_unelaborated_friend_type)
13945           << (unsigned) RD->getTagKind()
13946           << T
13947           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13948                                         InsertionText);
13949       } else {
13950         Diag(FriendLoc,
13951              getLangOpts().CPlusPlus11 ?
13952                diag::warn_cxx98_compat_nonclass_type_friend :
13953                diag::ext_nonclass_type_friend)
13954           << T
13955           << TypeRange;
13956       }
13957     } else if (T->getAs<EnumType>()) {
13958       Diag(FriendLoc,
13959            getLangOpts().CPlusPlus11 ?
13960              diag::warn_cxx98_compat_enum_friend :
13961              diag::ext_enum_friend)
13962         << T
13963         << TypeRange;
13964     }
13965 
13966     // C++11 [class.friend]p3:
13967     //   A friend declaration that does not declare a function shall have one
13968     //   of the following forms:
13969     //     friend elaborated-type-specifier ;
13970     //     friend simple-type-specifier ;
13971     //     friend typename-specifier ;
13972     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13973       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13974   }
13975 
13976   //   If the type specifier in a friend declaration designates a (possibly
13977   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13978   //   the friend declaration is ignored.
13979   return FriendDecl::Create(Context, CurContext,
13980                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
13981                             FriendLoc);
13982 }
13983 
13984 /// Handle a friend tag declaration where the scope specifier was
13985 /// templated.
13986 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13987                                     unsigned TagSpec, SourceLocation TagLoc,
13988                                     CXXScopeSpec &SS, IdentifierInfo *Name,
13989                                     SourceLocation NameLoc,
13990                                     const ParsedAttributesView &Attr,
13991                                     MultiTemplateParamsArg TempParamLists) {
13992   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13993 
13994   bool IsMemberSpecialization = false;
13995   bool Invalid = false;
13996 
13997   if (TemplateParameterList *TemplateParams =
13998           MatchTemplateParametersToScopeSpecifier(
13999               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14000               IsMemberSpecialization, Invalid)) {
14001     if (TemplateParams->size() > 0) {
14002       // This is a declaration of a class template.
14003       if (Invalid)
14004         return nullptr;
14005 
14006       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14007                                 NameLoc, Attr, TemplateParams, AS_public,
14008                                 /*ModulePrivateLoc=*/SourceLocation(),
14009                                 FriendLoc, TempParamLists.size() - 1,
14010                                 TempParamLists.data()).get();
14011     } else {
14012       // The "template<>" header is extraneous.
14013       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14014         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14015       IsMemberSpecialization = true;
14016     }
14017   }
14018 
14019   if (Invalid) return nullptr;
14020 
14021   bool isAllExplicitSpecializations = true;
14022   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14023     if (TempParamLists[I]->size()) {
14024       isAllExplicitSpecializations = false;
14025       break;
14026     }
14027   }
14028 
14029   // FIXME: don't ignore attributes.
14030 
14031   // If it's explicit specializations all the way down, just forget
14032   // about the template header and build an appropriate non-templated
14033   // friend.  TODO: for source fidelity, remember the headers.
14034   if (isAllExplicitSpecializations) {
14035     if (SS.isEmpty()) {
14036       bool Owned = false;
14037       bool IsDependent = false;
14038       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14039                       Attr, AS_public,
14040                       /*ModulePrivateLoc=*/SourceLocation(),
14041                       MultiTemplateParamsArg(), Owned, IsDependent,
14042                       /*ScopedEnumKWLoc=*/SourceLocation(),
14043                       /*ScopedEnumUsesClassTag=*/false,
14044                       /*UnderlyingType=*/TypeResult(),
14045                       /*IsTypeSpecifier=*/false,
14046                       /*IsTemplateParamOrArg=*/false);
14047     }
14048 
14049     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14050     ElaboratedTypeKeyword Keyword
14051       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14052     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14053                                    *Name, NameLoc);
14054     if (T.isNull())
14055       return nullptr;
14056 
14057     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14058     if (isa<DependentNameType>(T)) {
14059       DependentNameTypeLoc TL =
14060           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14061       TL.setElaboratedKeywordLoc(TagLoc);
14062       TL.setQualifierLoc(QualifierLoc);
14063       TL.setNameLoc(NameLoc);
14064     } else {
14065       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14066       TL.setElaboratedKeywordLoc(TagLoc);
14067       TL.setQualifierLoc(QualifierLoc);
14068       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14069     }
14070 
14071     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14072                                             TSI, FriendLoc, TempParamLists);
14073     Friend->setAccess(AS_public);
14074     CurContext->addDecl(Friend);
14075     return Friend;
14076   }
14077 
14078   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14079 
14080 
14081 
14082   // Handle the case of a templated-scope friend class.  e.g.
14083   //   template <class T> class A<T>::B;
14084   // FIXME: we don't support these right now.
14085   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14086     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14087   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14088   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14089   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14090   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14091   TL.setElaboratedKeywordLoc(TagLoc);
14092   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14093   TL.setNameLoc(NameLoc);
14094 
14095   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14096                                           TSI, FriendLoc, TempParamLists);
14097   Friend->setAccess(AS_public);
14098   Friend->setUnsupportedFriend(true);
14099   CurContext->addDecl(Friend);
14100   return Friend;
14101 }
14102 
14103 /// Handle a friend type declaration.  This works in tandem with
14104 /// ActOnTag.
14105 ///
14106 /// Notes on friend class templates:
14107 ///
14108 /// We generally treat friend class declarations as if they were
14109 /// declaring a class.  So, for example, the elaborated type specifier
14110 /// in a friend declaration is required to obey the restrictions of a
14111 /// class-head (i.e. no typedefs in the scope chain), template
14112 /// parameters are required to match up with simple template-ids, &c.
14113 /// However, unlike when declaring a template specialization, it's
14114 /// okay to refer to a template specialization without an empty
14115 /// template parameter declaration, e.g.
14116 ///   friend class A<T>::B<unsigned>;
14117 /// We permit this as a special case; if there are any template
14118 /// parameters present at all, require proper matching, i.e.
14119 ///   template <> template \<class T> friend class A<int>::B;
14120 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14121                                 MultiTemplateParamsArg TempParams) {
14122   SourceLocation Loc = DS.getBeginLoc();
14123 
14124   assert(DS.isFriendSpecified());
14125   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14126 
14127   // C++ [class.friend]p3:
14128   // A friend declaration that does not declare a function shall have one of
14129   // the following forms:
14130   //     friend elaborated-type-specifier ;
14131   //     friend simple-type-specifier ;
14132   //     friend typename-specifier ;
14133   //
14134   // Any declaration with a type qualifier does not have that form. (It's
14135   // legal to specify a qualified type as a friend, you just can't write the
14136   // keywords.)
14137   if (DS.getTypeQualifiers()) {
14138     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14139       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14140     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14141       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14142     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14143       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14144     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14145       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14146     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14147       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14148   }
14149 
14150   // Try to convert the decl specifier to a type.  This works for
14151   // friend templates because ActOnTag never produces a ClassTemplateDecl
14152   // for a TUK_Friend.
14153   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14154   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14155   QualType T = TSI->getType();
14156   if (TheDeclarator.isInvalidType())
14157     return nullptr;
14158 
14159   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14160     return nullptr;
14161 
14162   // This is definitely an error in C++98.  It's probably meant to
14163   // be forbidden in C++0x, too, but the specification is just
14164   // poorly written.
14165   //
14166   // The problem is with declarations like the following:
14167   //   template <T> friend A<T>::foo;
14168   // where deciding whether a class C is a friend or not now hinges
14169   // on whether there exists an instantiation of A that causes
14170   // 'foo' to equal C.  There are restrictions on class-heads
14171   // (which we declare (by fiat) elaborated friend declarations to
14172   // be) that makes this tractable.
14173   //
14174   // FIXME: handle "template <> friend class A<T>;", which
14175   // is possibly well-formed?  Who even knows?
14176   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14177     Diag(Loc, diag::err_tagless_friend_type_template)
14178       << DS.getSourceRange();
14179     return nullptr;
14180   }
14181 
14182   // C++98 [class.friend]p1: A friend of a class is a function
14183   //   or class that is not a member of the class . . .
14184   // This is fixed in DR77, which just barely didn't make the C++03
14185   // deadline.  It's also a very silly restriction that seriously
14186   // affects inner classes and which nobody else seems to implement;
14187   // thus we never diagnose it, not even in -pedantic.
14188   //
14189   // But note that we could warn about it: it's always useless to
14190   // friend one of your own members (it's not, however, worthless to
14191   // friend a member of an arbitrary specialization of your template).
14192 
14193   Decl *D;
14194   if (!TempParams.empty())
14195     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14196                                    TempParams,
14197                                    TSI,
14198                                    DS.getFriendSpecLoc());
14199   else
14200     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14201 
14202   if (!D)
14203     return nullptr;
14204 
14205   D->setAccess(AS_public);
14206   CurContext->addDecl(D);
14207 
14208   return D;
14209 }
14210 
14211 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14212                                         MultiTemplateParamsArg TemplateParams) {
14213   const DeclSpec &DS = D.getDeclSpec();
14214 
14215   assert(DS.isFriendSpecified());
14216   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14217 
14218   SourceLocation Loc = D.getIdentifierLoc();
14219   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14220 
14221   // C++ [class.friend]p1
14222   //   A friend of a class is a function or class....
14223   // Note that this sees through typedefs, which is intended.
14224   // It *doesn't* see through dependent types, which is correct
14225   // according to [temp.arg.type]p3:
14226   //   If a declaration acquires a function type through a
14227   //   type dependent on a template-parameter and this causes
14228   //   a declaration that does not use the syntactic form of a
14229   //   function declarator to have a function type, the program
14230   //   is ill-formed.
14231   if (!TInfo->getType()->isFunctionType()) {
14232     Diag(Loc, diag::err_unexpected_friend);
14233 
14234     // It might be worthwhile to try to recover by creating an
14235     // appropriate declaration.
14236     return nullptr;
14237   }
14238 
14239   // C++ [namespace.memdef]p3
14240   //  - If a friend declaration in a non-local class first declares a
14241   //    class or function, the friend class or function is a member
14242   //    of the innermost enclosing namespace.
14243   //  - The name of the friend is not found by simple name lookup
14244   //    until a matching declaration is provided in that namespace
14245   //    scope (either before or after the class declaration granting
14246   //    friendship).
14247   //  - If a friend function is called, its name may be found by the
14248   //    name lookup that considers functions from namespaces and
14249   //    classes associated with the types of the function arguments.
14250   //  - When looking for a prior declaration of a class or a function
14251   //    declared as a friend, scopes outside the innermost enclosing
14252   //    namespace scope are not considered.
14253 
14254   CXXScopeSpec &SS = D.getCXXScopeSpec();
14255   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14256   DeclarationName Name = NameInfo.getName();
14257   assert(Name);
14258 
14259   // Check for unexpanded parameter packs.
14260   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14261       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14262       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14263     return nullptr;
14264 
14265   // The context we found the declaration in, or in which we should
14266   // create the declaration.
14267   DeclContext *DC;
14268   Scope *DCScope = S;
14269   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14270                         ForExternalRedeclaration);
14271 
14272   // There are five cases here.
14273   //   - There's no scope specifier and we're in a local class. Only look
14274   //     for functions declared in the immediately-enclosing block scope.
14275   // We recover from invalid scope qualifiers as if they just weren't there.
14276   FunctionDecl *FunctionContainingLocalClass = nullptr;
14277   if ((SS.isInvalid() || !SS.isSet()) &&
14278       (FunctionContainingLocalClass =
14279            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14280     // C++11 [class.friend]p11:
14281     //   If a friend declaration appears in a local class and the name
14282     //   specified is an unqualified name, a prior declaration is
14283     //   looked up without considering scopes that are outside the
14284     //   innermost enclosing non-class scope. For a friend function
14285     //   declaration, if there is no prior declaration, the program is
14286     //   ill-formed.
14287 
14288     // Find the innermost enclosing non-class scope. This is the block
14289     // scope containing the local class definition (or for a nested class,
14290     // the outer local class).
14291     DCScope = S->getFnParent();
14292 
14293     // Look up the function name in the scope.
14294     Previous.clear(LookupLocalFriendName);
14295     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14296 
14297     if (!Previous.empty()) {
14298       // All possible previous declarations must have the same context:
14299       // either they were declared at block scope or they are members of
14300       // one of the enclosing local classes.
14301       DC = Previous.getRepresentativeDecl()->getDeclContext();
14302     } else {
14303       // This is ill-formed, but provide the context that we would have
14304       // declared the function in, if we were permitted to, for error recovery.
14305       DC = FunctionContainingLocalClass;
14306     }
14307     adjustContextForLocalExternDecl(DC);
14308 
14309     // C++ [class.friend]p6:
14310     //   A function can be defined in a friend declaration of a class if and
14311     //   only if the class is a non-local class (9.8), the function name is
14312     //   unqualified, and the function has namespace scope.
14313     if (D.isFunctionDefinition()) {
14314       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14315     }
14316 
14317   //   - There's no scope specifier, in which case we just go to the
14318   //     appropriate scope and look for a function or function template
14319   //     there as appropriate.
14320   } else if (SS.isInvalid() || !SS.isSet()) {
14321     // C++11 [namespace.memdef]p3:
14322     //   If the name in a friend declaration is neither qualified nor
14323     //   a template-id and the declaration is a function or an
14324     //   elaborated-type-specifier, the lookup to determine whether
14325     //   the entity has been previously declared shall not consider
14326     //   any scopes outside the innermost enclosing namespace.
14327     bool isTemplateId =
14328         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14329 
14330     // Find the appropriate context according to the above.
14331     DC = CurContext;
14332 
14333     // Skip class contexts.  If someone can cite chapter and verse
14334     // for this behavior, that would be nice --- it's what GCC and
14335     // EDG do, and it seems like a reasonable intent, but the spec
14336     // really only says that checks for unqualified existing
14337     // declarations should stop at the nearest enclosing namespace,
14338     // not that they should only consider the nearest enclosing
14339     // namespace.
14340     while (DC->isRecord())
14341       DC = DC->getParent();
14342 
14343     DeclContext *LookupDC = DC;
14344     while (LookupDC->isTransparentContext())
14345       LookupDC = LookupDC->getParent();
14346 
14347     while (true) {
14348       LookupQualifiedName(Previous, LookupDC);
14349 
14350       if (!Previous.empty()) {
14351         DC = LookupDC;
14352         break;
14353       }
14354 
14355       if (isTemplateId) {
14356         if (isa<TranslationUnitDecl>(LookupDC)) break;
14357       } else {
14358         if (LookupDC->isFileContext()) break;
14359       }
14360       LookupDC = LookupDC->getParent();
14361     }
14362 
14363     DCScope = getScopeForDeclContext(S, DC);
14364 
14365   //   - There's a non-dependent scope specifier, in which case we
14366   //     compute it and do a previous lookup there for a function
14367   //     or function template.
14368   } else if (!SS.getScopeRep()->isDependent()) {
14369     DC = computeDeclContext(SS);
14370     if (!DC) return nullptr;
14371 
14372     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14373 
14374     LookupQualifiedName(Previous, DC);
14375 
14376     // Ignore things found implicitly in the wrong scope.
14377     // TODO: better diagnostics for this case.  Suggesting the right
14378     // qualified scope would be nice...
14379     LookupResult::Filter F = Previous.makeFilter();
14380     while (F.hasNext()) {
14381       NamedDecl *D = F.next();
14382       if (!DC->InEnclosingNamespaceSetOf(
14383               D->getDeclContext()->getRedeclContext()))
14384         F.erase();
14385     }
14386     F.done();
14387 
14388     if (Previous.empty()) {
14389       D.setInvalidType();
14390       Diag(Loc, diag::err_qualified_friend_not_found)
14391           << Name << TInfo->getType();
14392       return nullptr;
14393     }
14394 
14395     // C++ [class.friend]p1: A friend of a class is a function or
14396     //   class that is not a member of the class . . .
14397     if (DC->Equals(CurContext))
14398       Diag(DS.getFriendSpecLoc(),
14399            getLangOpts().CPlusPlus11 ?
14400              diag::warn_cxx98_compat_friend_is_member :
14401              diag::err_friend_is_member);
14402 
14403     if (D.isFunctionDefinition()) {
14404       // C++ [class.friend]p6:
14405       //   A function can be defined in a friend declaration of a class if and
14406       //   only if the class is a non-local class (9.8), the function name is
14407       //   unqualified, and the function has namespace scope.
14408       SemaDiagnosticBuilder DB
14409         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14410 
14411       DB << SS.getScopeRep();
14412       if (DC->isFileContext())
14413         DB << FixItHint::CreateRemoval(SS.getRange());
14414       SS.clear();
14415     }
14416 
14417   //   - There's a scope specifier that does not match any template
14418   //     parameter lists, in which case we use some arbitrary context,
14419   //     create a method or method template, and wait for instantiation.
14420   //   - There's a scope specifier that does match some template
14421   //     parameter lists, which we don't handle right now.
14422   } else {
14423     if (D.isFunctionDefinition()) {
14424       // C++ [class.friend]p6:
14425       //   A function can be defined in a friend declaration of a class if and
14426       //   only if the class is a non-local class (9.8), the function name is
14427       //   unqualified, and the function has namespace scope.
14428       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14429         << SS.getScopeRep();
14430     }
14431 
14432     DC = CurContext;
14433     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14434   }
14435 
14436   if (!DC->isRecord()) {
14437     int DiagArg = -1;
14438     switch (D.getName().getKind()) {
14439     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14440     case UnqualifiedIdKind::IK_ConstructorName:
14441       DiagArg = 0;
14442       break;
14443     case UnqualifiedIdKind::IK_DestructorName:
14444       DiagArg = 1;
14445       break;
14446     case UnqualifiedIdKind::IK_ConversionFunctionId:
14447       DiagArg = 2;
14448       break;
14449     case UnqualifiedIdKind::IK_DeductionGuideName:
14450       DiagArg = 3;
14451       break;
14452     case UnqualifiedIdKind::IK_Identifier:
14453     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14454     case UnqualifiedIdKind::IK_LiteralOperatorId:
14455     case UnqualifiedIdKind::IK_OperatorFunctionId:
14456     case UnqualifiedIdKind::IK_TemplateId:
14457       break;
14458     }
14459     // This implies that it has to be an operator or function.
14460     if (DiagArg >= 0) {
14461       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14462       return nullptr;
14463     }
14464   }
14465 
14466   // FIXME: This is an egregious hack to cope with cases where the scope stack
14467   // does not contain the declaration context, i.e., in an out-of-line
14468   // definition of a class.
14469   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14470   if (!DCScope) {
14471     FakeDCScope.setEntity(DC);
14472     DCScope = &FakeDCScope;
14473   }
14474 
14475   bool AddToScope = true;
14476   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14477                                           TemplateParams, AddToScope);
14478   if (!ND) return nullptr;
14479 
14480   assert(ND->getLexicalDeclContext() == CurContext);
14481 
14482   // If we performed typo correction, we might have added a scope specifier
14483   // and changed the decl context.
14484   DC = ND->getDeclContext();
14485 
14486   // Add the function declaration to the appropriate lookup tables,
14487   // adjusting the redeclarations list as necessary.  We don't
14488   // want to do this yet if the friending class is dependent.
14489   //
14490   // Also update the scope-based lookup if the target context's
14491   // lookup context is in lexical scope.
14492   if (!CurContext->isDependentContext()) {
14493     DC = DC->getRedeclContext();
14494     DC->makeDeclVisibleInContext(ND);
14495     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14496       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14497   }
14498 
14499   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14500                                        D.getIdentifierLoc(), ND,
14501                                        DS.getFriendSpecLoc());
14502   FrD->setAccess(AS_public);
14503   CurContext->addDecl(FrD);
14504 
14505   if (ND->isInvalidDecl()) {
14506     FrD->setInvalidDecl();
14507   } else {
14508     if (DC->isRecord()) CheckFriendAccess(ND);
14509 
14510     FunctionDecl *FD;
14511     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14512       FD = FTD->getTemplatedDecl();
14513     else
14514       FD = cast<FunctionDecl>(ND);
14515 
14516     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14517     // default argument expression, that declaration shall be a definition
14518     // and shall be the only declaration of the function or function
14519     // template in the translation unit.
14520     if (functionDeclHasDefaultArgument(FD)) {
14521       // We can't look at FD->getPreviousDecl() because it may not have been set
14522       // if we're in a dependent context. If the function is known to be a
14523       // redeclaration, we will have narrowed Previous down to the right decl.
14524       if (D.isRedeclaration()) {
14525         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14526         Diag(Previous.getRepresentativeDecl()->getLocation(),
14527              diag::note_previous_declaration);
14528       } else if (!D.isFunctionDefinition())
14529         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14530     }
14531 
14532     // Mark templated-scope function declarations as unsupported.
14533     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14534       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14535         << SS.getScopeRep() << SS.getRange()
14536         << cast<CXXRecordDecl>(CurContext);
14537       FrD->setUnsupportedFriend(true);
14538     }
14539   }
14540 
14541   return ND;
14542 }
14543 
14544 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14545   AdjustDeclIfTemplate(Dcl);
14546 
14547   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14548   if (!Fn) {
14549     Diag(DelLoc, diag::err_deleted_non_function);
14550     return;
14551   }
14552 
14553   // Deleted function does not have a body.
14554   Fn->setWillHaveBody(false);
14555 
14556   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14557     // Don't consider the implicit declaration we generate for explicit
14558     // specializations. FIXME: Do not generate these implicit declarations.
14559     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14560          Prev->getPreviousDecl()) &&
14561         !Prev->isDefined()) {
14562       Diag(DelLoc, diag::err_deleted_decl_not_first);
14563       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14564            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14565                               : diag::note_previous_declaration);
14566     }
14567     // If the declaration wasn't the first, we delete the function anyway for
14568     // recovery.
14569     Fn = Fn->getCanonicalDecl();
14570   }
14571 
14572   // dllimport/dllexport cannot be deleted.
14573   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14574     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14575     Fn->setInvalidDecl();
14576   }
14577 
14578   if (Fn->isDeleted())
14579     return;
14580 
14581   // See if we're deleting a function which is already known to override a
14582   // non-deleted virtual function.
14583   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14584     bool IssuedDiagnostic = false;
14585     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14586       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14587         if (!IssuedDiagnostic) {
14588           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14589           IssuedDiagnostic = true;
14590         }
14591         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14592       }
14593     }
14594     // If this function was implicitly deleted because it was defaulted,
14595     // explain why it was deleted.
14596     if (IssuedDiagnostic && MD->isDefaulted())
14597       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14598                                 /*Diagnose*/true);
14599   }
14600 
14601   // C++11 [basic.start.main]p3:
14602   //   A program that defines main as deleted [...] is ill-formed.
14603   if (Fn->isMain())
14604     Diag(DelLoc, diag::err_deleted_main);
14605 
14606   // C++11 [dcl.fct.def.delete]p4:
14607   //  A deleted function is implicitly inline.
14608   Fn->setImplicitlyInline();
14609   Fn->setDeletedAsWritten();
14610 }
14611 
14612 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14613   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14614 
14615   if (MD) {
14616     if (MD->getParent()->isDependentType()) {
14617       MD->setDefaulted();
14618       MD->setExplicitlyDefaulted();
14619       return;
14620     }
14621 
14622     CXXSpecialMember Member = getSpecialMember(MD);
14623     if (Member == CXXInvalid) {
14624       if (!MD->isInvalidDecl())
14625         Diag(DefaultLoc, diag::err_default_special_members);
14626       return;
14627     }
14628 
14629     MD->setDefaulted();
14630     MD->setExplicitlyDefaulted();
14631 
14632     // Unset that we will have a body for this function. We might not,
14633     // if it turns out to be trivial, and we don't need this marking now
14634     // that we've marked it as defaulted.
14635     MD->setWillHaveBody(false);
14636 
14637     // If this definition appears within the record, do the checking when
14638     // the record is complete.
14639     const FunctionDecl *Primary = MD;
14640     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14641       // Ask the template instantiation pattern that actually had the
14642       // '= default' on it.
14643       Primary = Pattern;
14644 
14645     // If the method was defaulted on its first declaration, we will have
14646     // already performed the checking in CheckCompletedCXXClass. Such a
14647     // declaration doesn't trigger an implicit definition.
14648     if (Primary->getCanonicalDecl()->isDefaulted())
14649       return;
14650 
14651     CheckExplicitlyDefaultedSpecialMember(MD);
14652 
14653     if (!MD->isInvalidDecl())
14654       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14655   } else {
14656     Diag(DefaultLoc, diag::err_default_special_members);
14657   }
14658 }
14659 
14660 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14661   for (Stmt *SubStmt : S->children()) {
14662     if (!SubStmt)
14663       continue;
14664     if (isa<ReturnStmt>(SubStmt))
14665       Self.Diag(SubStmt->getBeginLoc(),
14666                 diag::err_return_in_constructor_handler);
14667     if (!isa<Expr>(SubStmt))
14668       SearchForReturnInStmt(Self, SubStmt);
14669   }
14670 }
14671 
14672 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14673   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14674     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14675     SearchForReturnInStmt(*this, Handler);
14676   }
14677 }
14678 
14679 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14680                                              const CXXMethodDecl *Old) {
14681   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14682   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14683 
14684   if (OldFT->hasExtParameterInfos()) {
14685     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14686       // A parameter of the overriding method should be annotated with noescape
14687       // if the corresponding parameter of the overridden method is annotated.
14688       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14689           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14690         Diag(New->getParamDecl(I)->getLocation(),
14691              diag::warn_overriding_method_missing_noescape);
14692         Diag(Old->getParamDecl(I)->getLocation(),
14693              diag::note_overridden_marked_noescape);
14694       }
14695   }
14696 
14697   // Virtual overrides must have the same code_seg.
14698   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14699   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14700   if ((NewCSA || OldCSA) &&
14701       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14702     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14703     Diag(Old->getLocation(), diag::note_previous_declaration);
14704     return true;
14705   }
14706 
14707   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14708 
14709   // If the calling conventions match, everything is fine
14710   if (NewCC == OldCC)
14711     return false;
14712 
14713   // If the calling conventions mismatch because the new function is static,
14714   // suppress the calling convention mismatch error; the error about static
14715   // function override (err_static_overrides_virtual from
14716   // Sema::CheckFunctionDeclaration) is more clear.
14717   if (New->getStorageClass() == SC_Static)
14718     return false;
14719 
14720   Diag(New->getLocation(),
14721        diag::err_conflicting_overriding_cc_attributes)
14722     << New->getDeclName() << New->getType() << Old->getType();
14723   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14724   return true;
14725 }
14726 
14727 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14728                                              const CXXMethodDecl *Old) {
14729   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14730   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14731 
14732   if (Context.hasSameType(NewTy, OldTy) ||
14733       NewTy->isDependentType() || OldTy->isDependentType())
14734     return false;
14735 
14736   // Check if the return types are covariant
14737   QualType NewClassTy, OldClassTy;
14738 
14739   /// Both types must be pointers or references to classes.
14740   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14741     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14742       NewClassTy = NewPT->getPointeeType();
14743       OldClassTy = OldPT->getPointeeType();
14744     }
14745   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14746     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14747       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14748         NewClassTy = NewRT->getPointeeType();
14749         OldClassTy = OldRT->getPointeeType();
14750       }
14751     }
14752   }
14753 
14754   // The return types aren't either both pointers or references to a class type.
14755   if (NewClassTy.isNull()) {
14756     Diag(New->getLocation(),
14757          diag::err_different_return_type_for_overriding_virtual_function)
14758         << New->getDeclName() << NewTy << OldTy
14759         << New->getReturnTypeSourceRange();
14760     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14761         << Old->getReturnTypeSourceRange();
14762 
14763     return true;
14764   }
14765 
14766   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14767     // C++14 [class.virtual]p8:
14768     //   If the class type in the covariant return type of D::f differs from
14769     //   that of B::f, the class type in the return type of D::f shall be
14770     //   complete at the point of declaration of D::f or shall be the class
14771     //   type D.
14772     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14773       if (!RT->isBeingDefined() &&
14774           RequireCompleteType(New->getLocation(), NewClassTy,
14775                               diag::err_covariant_return_incomplete,
14776                               New->getDeclName()))
14777         return true;
14778     }
14779 
14780     // Check if the new class derives from the old class.
14781     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14782       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14783           << New->getDeclName() << NewTy << OldTy
14784           << New->getReturnTypeSourceRange();
14785       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14786           << Old->getReturnTypeSourceRange();
14787       return true;
14788     }
14789 
14790     // Check if we the conversion from derived to base is valid.
14791     if (CheckDerivedToBaseConversion(
14792             NewClassTy, OldClassTy,
14793             diag::err_covariant_return_inaccessible_base,
14794             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14795             New->getLocation(), New->getReturnTypeSourceRange(),
14796             New->getDeclName(), nullptr)) {
14797       // FIXME: this note won't trigger for delayed access control
14798       // diagnostics, and it's impossible to get an undelayed error
14799       // here from access control during the original parse because
14800       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14801       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14802           << Old->getReturnTypeSourceRange();
14803       return true;
14804     }
14805   }
14806 
14807   // The qualifiers of the return types must be the same.
14808   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14809     Diag(New->getLocation(),
14810          diag::err_covariant_return_type_different_qualifications)
14811         << New->getDeclName() << NewTy << OldTy
14812         << New->getReturnTypeSourceRange();
14813     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14814         << Old->getReturnTypeSourceRange();
14815     return true;
14816   }
14817 
14818 
14819   // The new class type must have the same or less qualifiers as the old type.
14820   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14821     Diag(New->getLocation(),
14822          diag::err_covariant_return_type_class_type_more_qualified)
14823         << New->getDeclName() << NewTy << OldTy
14824         << New->getReturnTypeSourceRange();
14825     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14826         << Old->getReturnTypeSourceRange();
14827     return true;
14828   }
14829 
14830   return false;
14831 }
14832 
14833 /// Mark the given method pure.
14834 ///
14835 /// \param Method the method to be marked pure.
14836 ///
14837 /// \param InitRange the source range that covers the "0" initializer.
14838 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14839   SourceLocation EndLoc = InitRange.getEnd();
14840   if (EndLoc.isValid())
14841     Method->setRangeEnd(EndLoc);
14842 
14843   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14844     Method->setPure();
14845     return false;
14846   }
14847 
14848   if (!Method->isInvalidDecl())
14849     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14850       << Method->getDeclName() << InitRange;
14851   return true;
14852 }
14853 
14854 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14855   if (D->getFriendObjectKind())
14856     Diag(D->getLocation(), diag::err_pure_friend);
14857   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14858     CheckPureMethod(M, ZeroLoc);
14859   else
14860     Diag(D->getLocation(), diag::err_illegal_initializer);
14861 }
14862 
14863 /// Determine whether the given declaration is a global variable or
14864 /// static data member.
14865 static bool isNonlocalVariable(const Decl *D) {
14866   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14867     return Var->hasGlobalStorage();
14868 
14869   return false;
14870 }
14871 
14872 /// Invoked when we are about to parse an initializer for the declaration
14873 /// 'Dcl'.
14874 ///
14875 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14876 /// static data member of class X, names should be looked up in the scope of
14877 /// class X. If the declaration had a scope specifier, a scope will have
14878 /// been created and passed in for this purpose. Otherwise, S will be null.
14879 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14880   // If there is no declaration, there was an error parsing it.
14881   if (!D || D->isInvalidDecl())
14882     return;
14883 
14884   // We will always have a nested name specifier here, but this declaration
14885   // might not be out of line if the specifier names the current namespace:
14886   //   extern int n;
14887   //   int ::n = 0;
14888   if (S && D->isOutOfLine())
14889     EnterDeclaratorContext(S, D->getDeclContext());
14890 
14891   // If we are parsing the initializer for a static data member, push a
14892   // new expression evaluation context that is associated with this static
14893   // data member.
14894   if (isNonlocalVariable(D))
14895     PushExpressionEvaluationContext(
14896         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14897 }
14898 
14899 /// Invoked after we are finished parsing an initializer for the declaration D.
14900 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14901   // If there is no declaration, there was an error parsing it.
14902   if (!D || D->isInvalidDecl())
14903     return;
14904 
14905   if (isNonlocalVariable(D))
14906     PopExpressionEvaluationContext();
14907 
14908   if (S && D->isOutOfLine())
14909     ExitDeclaratorContext(S);
14910 }
14911 
14912 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14913 /// C++ if/switch/while/for statement.
14914 /// e.g: "if (int x = f()) {...}"
14915 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14916   // C++ 6.4p2:
14917   // The declarator shall not specify a function or an array.
14918   // The type-specifier-seq shall not contain typedef and shall not declare a
14919   // new class or enumeration.
14920   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14921          "Parser allowed 'typedef' as storage class of condition decl.");
14922 
14923   Decl *Dcl = ActOnDeclarator(S, D);
14924   if (!Dcl)
14925     return true;
14926 
14927   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14928     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14929       << D.getSourceRange();
14930     return true;
14931   }
14932 
14933   return Dcl;
14934 }
14935 
14936 void Sema::LoadExternalVTableUses() {
14937   if (!ExternalSource)
14938     return;
14939 
14940   SmallVector<ExternalVTableUse, 4> VTables;
14941   ExternalSource->ReadUsedVTables(VTables);
14942   SmallVector<VTableUse, 4> NewUses;
14943   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14944     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14945       = VTablesUsed.find(VTables[I].Record);
14946     // Even if a definition wasn't required before, it may be required now.
14947     if (Pos != VTablesUsed.end()) {
14948       if (!Pos->second && VTables[I].DefinitionRequired)
14949         Pos->second = true;
14950       continue;
14951     }
14952 
14953     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14954     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14955   }
14956 
14957   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14958 }
14959 
14960 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14961                           bool DefinitionRequired) {
14962   // Ignore any vtable uses in unevaluated operands or for classes that do
14963   // not have a vtable.
14964   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14965       CurContext->isDependentContext() || isUnevaluatedContext())
14966     return;
14967   // Do not mark as used if compiling for the device outside of the target
14968   // region.
14969   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
14970       !isInOpenMPDeclareTargetContext() &&
14971       !isInOpenMPTargetExecutionDirective()) {
14972     if (!DefinitionRequired)
14973       MarkVirtualMembersReferenced(Loc, Class);
14974     return;
14975   }
14976 
14977   // Try to insert this class into the map.
14978   LoadExternalVTableUses();
14979   Class = Class->getCanonicalDecl();
14980   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14981     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14982   if (!Pos.second) {
14983     // If we already had an entry, check to see if we are promoting this vtable
14984     // to require a definition. If so, we need to reappend to the VTableUses
14985     // list, since we may have already processed the first entry.
14986     if (DefinitionRequired && !Pos.first->second) {
14987       Pos.first->second = true;
14988     } else {
14989       // Otherwise, we can early exit.
14990       return;
14991     }
14992   } else {
14993     // The Microsoft ABI requires that we perform the destructor body
14994     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14995     // the deleting destructor is emitted with the vtable, not with the
14996     // destructor definition as in the Itanium ABI.
14997     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14998       CXXDestructorDecl *DD = Class->getDestructor();
14999       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15000         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15001           // If this is an out-of-line declaration, marking it referenced will
15002           // not do anything. Manually call CheckDestructor to look up operator
15003           // delete().
15004           ContextRAII SavedContext(*this, DD);
15005           CheckDestructor(DD);
15006         } else {
15007           MarkFunctionReferenced(Loc, Class->getDestructor());
15008         }
15009       }
15010     }
15011   }
15012 
15013   // Local classes need to have their virtual members marked
15014   // immediately. For all other classes, we mark their virtual members
15015   // at the end of the translation unit.
15016   if (Class->isLocalClass())
15017     MarkVirtualMembersReferenced(Loc, Class);
15018   else
15019     VTableUses.push_back(std::make_pair(Class, Loc));
15020 }
15021 
15022 bool Sema::DefineUsedVTables() {
15023   LoadExternalVTableUses();
15024   if (VTableUses.empty())
15025     return false;
15026 
15027   // Note: The VTableUses vector could grow as a result of marking
15028   // the members of a class as "used", so we check the size each
15029   // time through the loop and prefer indices (which are stable) to
15030   // iterators (which are not).
15031   bool DefinedAnything = false;
15032   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15033     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15034     if (!Class)
15035       continue;
15036     TemplateSpecializationKind ClassTSK =
15037         Class->getTemplateSpecializationKind();
15038 
15039     SourceLocation Loc = VTableUses[I].second;
15040 
15041     bool DefineVTable = true;
15042 
15043     // If this class has a key function, but that key function is
15044     // defined in another translation unit, we don't need to emit the
15045     // vtable even though we're using it.
15046     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15047     if (KeyFunction && !KeyFunction->hasBody()) {
15048       // The key function is in another translation unit.
15049       DefineVTable = false;
15050       TemplateSpecializationKind TSK =
15051           KeyFunction->getTemplateSpecializationKind();
15052       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15053              TSK != TSK_ImplicitInstantiation &&
15054              "Instantiations don't have key functions");
15055       (void)TSK;
15056     } else if (!KeyFunction) {
15057       // If we have a class with no key function that is the subject
15058       // of an explicit instantiation declaration, suppress the
15059       // vtable; it will live with the explicit instantiation
15060       // definition.
15061       bool IsExplicitInstantiationDeclaration =
15062           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15063       for (auto R : Class->redecls()) {
15064         TemplateSpecializationKind TSK
15065           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15066         if (TSK == TSK_ExplicitInstantiationDeclaration)
15067           IsExplicitInstantiationDeclaration = true;
15068         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15069           IsExplicitInstantiationDeclaration = false;
15070           break;
15071         }
15072       }
15073 
15074       if (IsExplicitInstantiationDeclaration)
15075         DefineVTable = false;
15076     }
15077 
15078     // The exception specifications for all virtual members may be needed even
15079     // if we are not providing an authoritative form of the vtable in this TU.
15080     // We may choose to emit it available_externally anyway.
15081     if (!DefineVTable) {
15082       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15083       continue;
15084     }
15085 
15086     // Mark all of the virtual members of this class as referenced, so
15087     // that we can build a vtable. Then, tell the AST consumer that a
15088     // vtable for this class is required.
15089     DefinedAnything = true;
15090     MarkVirtualMembersReferenced(Loc, Class);
15091     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15092     if (VTablesUsed[Canonical])
15093       Consumer.HandleVTable(Class);
15094 
15095     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15096     // no key function or the key function is inlined. Don't warn in C++ ABIs
15097     // that lack key functions, since the user won't be able to make one.
15098     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15099         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15100       const FunctionDecl *KeyFunctionDef = nullptr;
15101       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15102                            KeyFunctionDef->isInlined())) {
15103         Diag(Class->getLocation(),
15104              ClassTSK == TSK_ExplicitInstantiationDefinition
15105                  ? diag::warn_weak_template_vtable
15106                  : diag::warn_weak_vtable)
15107             << Class;
15108       }
15109     }
15110   }
15111   VTableUses.clear();
15112 
15113   return DefinedAnything;
15114 }
15115 
15116 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15117                                                  const CXXRecordDecl *RD) {
15118   for (const auto *I : RD->methods())
15119     if (I->isVirtual() && !I->isPure())
15120       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15121 }
15122 
15123 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15124                                         const CXXRecordDecl *RD) {
15125   // Mark all functions which will appear in RD's vtable as used.
15126   CXXFinalOverriderMap FinalOverriders;
15127   RD->getFinalOverriders(FinalOverriders);
15128   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15129                                             E = FinalOverriders.end();
15130        I != E; ++I) {
15131     for (OverridingMethods::const_iterator OI = I->second.begin(),
15132                                            OE = I->second.end();
15133          OI != OE; ++OI) {
15134       assert(OI->second.size() > 0 && "no final overrider");
15135       CXXMethodDecl *Overrider = OI->second.front().Method;
15136 
15137       // C++ [basic.def.odr]p2:
15138       //   [...] A virtual member function is used if it is not pure. [...]
15139       if (!Overrider->isPure())
15140         MarkFunctionReferenced(Loc, Overrider);
15141     }
15142   }
15143 
15144   // Only classes that have virtual bases need a VTT.
15145   if (RD->getNumVBases() == 0)
15146     return;
15147 
15148   for (const auto &I : RD->bases()) {
15149     const CXXRecordDecl *Base =
15150         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15151     if (Base->getNumVBases() == 0)
15152       continue;
15153     MarkVirtualMembersReferenced(Loc, Base);
15154   }
15155 }
15156 
15157 /// SetIvarInitializers - This routine builds initialization ASTs for the
15158 /// Objective-C implementation whose ivars need be initialized.
15159 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15160   if (!getLangOpts().CPlusPlus)
15161     return;
15162   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15163     SmallVector<ObjCIvarDecl*, 8> ivars;
15164     CollectIvarsToConstructOrDestruct(OID, ivars);
15165     if (ivars.empty())
15166       return;
15167     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15168     for (unsigned i = 0; i < ivars.size(); i++) {
15169       FieldDecl *Field = ivars[i];
15170       if (Field->isInvalidDecl())
15171         continue;
15172 
15173       CXXCtorInitializer *Member;
15174       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15175       InitializationKind InitKind =
15176         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15177 
15178       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15179       ExprResult MemberInit =
15180         InitSeq.Perform(*this, InitEntity, InitKind, None);
15181       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15182       // Note, MemberInit could actually come back empty if no initialization
15183       // is required (e.g., because it would call a trivial default constructor)
15184       if (!MemberInit.get() || MemberInit.isInvalid())
15185         continue;
15186 
15187       Member =
15188         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15189                                          SourceLocation(),
15190                                          MemberInit.getAs<Expr>(),
15191                                          SourceLocation());
15192       AllToInit.push_back(Member);
15193 
15194       // Be sure that the destructor is accessible and is marked as referenced.
15195       if (const RecordType *RecordTy =
15196               Context.getBaseElementType(Field->getType())
15197                   ->getAs<RecordType>()) {
15198         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15199         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15200           MarkFunctionReferenced(Field->getLocation(), Destructor);
15201           CheckDestructorAccess(Field->getLocation(), Destructor,
15202                             PDiag(diag::err_access_dtor_ivar)
15203                               << Context.getBaseElementType(Field->getType()));
15204         }
15205       }
15206     }
15207     ObjCImplementation->setIvarInitializers(Context,
15208                                             AllToInit.data(), AllToInit.size());
15209   }
15210 }
15211 
15212 static
15213 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15214                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15215                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15216                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15217                            Sema &S) {
15218   if (Ctor->isInvalidDecl())
15219     return;
15220 
15221   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15222 
15223   // Target may not be determinable yet, for instance if this is a dependent
15224   // call in an uninstantiated template.
15225   if (Target) {
15226     const FunctionDecl *FNTarget = nullptr;
15227     (void)Target->hasBody(FNTarget);
15228     Target = const_cast<CXXConstructorDecl*>(
15229       cast_or_null<CXXConstructorDecl>(FNTarget));
15230   }
15231 
15232   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15233                      // Avoid dereferencing a null pointer here.
15234                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15235 
15236   if (!Current.insert(Canonical).second)
15237     return;
15238 
15239   // We know that beyond here, we aren't chaining into a cycle.
15240   if (!Target || !Target->isDelegatingConstructor() ||
15241       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15242     Valid.insert(Current.begin(), Current.end());
15243     Current.clear();
15244   // We've hit a cycle.
15245   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15246              Current.count(TCanonical)) {
15247     // If we haven't diagnosed this cycle yet, do so now.
15248     if (!Invalid.count(TCanonical)) {
15249       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15250              diag::warn_delegating_ctor_cycle)
15251         << Ctor;
15252 
15253       // Don't add a note for a function delegating directly to itself.
15254       if (TCanonical != Canonical)
15255         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15256 
15257       CXXConstructorDecl *C = Target;
15258       while (C->getCanonicalDecl() != Canonical) {
15259         const FunctionDecl *FNTarget = nullptr;
15260         (void)C->getTargetConstructor()->hasBody(FNTarget);
15261         assert(FNTarget && "Ctor cycle through bodiless function");
15262 
15263         C = const_cast<CXXConstructorDecl*>(
15264           cast<CXXConstructorDecl>(FNTarget));
15265         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15266       }
15267     }
15268 
15269     Invalid.insert(Current.begin(), Current.end());
15270     Current.clear();
15271   } else {
15272     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15273   }
15274 }
15275 
15276 
15277 void Sema::CheckDelegatingCtorCycles() {
15278   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15279 
15280   for (DelegatingCtorDeclsType::iterator
15281          I = DelegatingCtorDecls.begin(ExternalSource),
15282          E = DelegatingCtorDecls.end();
15283        I != E; ++I)
15284     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15285 
15286   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15287     (*CI)->setInvalidDecl();
15288 }
15289 
15290 namespace {
15291   /// AST visitor that finds references to the 'this' expression.
15292   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15293     Sema &S;
15294 
15295   public:
15296     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15297 
15298     bool VisitCXXThisExpr(CXXThisExpr *E) {
15299       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15300         << E->isImplicit();
15301       return false;
15302     }
15303   };
15304 }
15305 
15306 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15307   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15308   if (!TSInfo)
15309     return false;
15310 
15311   TypeLoc TL = TSInfo->getTypeLoc();
15312   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15313   if (!ProtoTL)
15314     return false;
15315 
15316   // C++11 [expr.prim.general]p3:
15317   //   [The expression this] shall not appear before the optional
15318   //   cv-qualifier-seq and it shall not appear within the declaration of a
15319   //   static member function (although its type and value category are defined
15320   //   within a static member function as they are within a non-static member
15321   //   function). [ Note: this is because declaration matching does not occur
15322   //  until the complete declarator is known. - end note ]
15323   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15324   FindCXXThisExpr Finder(*this);
15325 
15326   // If the return type came after the cv-qualifier-seq, check it now.
15327   if (Proto->hasTrailingReturn() &&
15328       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15329     return true;
15330 
15331   // Check the exception specification.
15332   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15333     return true;
15334 
15335   return checkThisInStaticMemberFunctionAttributes(Method);
15336 }
15337 
15338 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15339   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15340   if (!TSInfo)
15341     return false;
15342 
15343   TypeLoc TL = TSInfo->getTypeLoc();
15344   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15345   if (!ProtoTL)
15346     return false;
15347 
15348   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15349   FindCXXThisExpr Finder(*this);
15350 
15351   switch (Proto->getExceptionSpecType()) {
15352   case EST_Unparsed:
15353   case EST_Uninstantiated:
15354   case EST_Unevaluated:
15355   case EST_BasicNoexcept:
15356   case EST_DynamicNone:
15357   case EST_MSAny:
15358   case EST_None:
15359     break;
15360 
15361   case EST_DependentNoexcept:
15362   case EST_NoexceptFalse:
15363   case EST_NoexceptTrue:
15364     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15365       return true;
15366     LLVM_FALLTHROUGH;
15367 
15368   case EST_Dynamic:
15369     for (const auto &E : Proto->exceptions()) {
15370       if (!Finder.TraverseType(E))
15371         return true;
15372     }
15373     break;
15374   }
15375 
15376   return false;
15377 }
15378 
15379 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15380   FindCXXThisExpr Finder(*this);
15381 
15382   // Check attributes.
15383   for (const auto *A : Method->attrs()) {
15384     // FIXME: This should be emitted by tblgen.
15385     Expr *Arg = nullptr;
15386     ArrayRef<Expr *> Args;
15387     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15388       Arg = G->getArg();
15389     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15390       Arg = G->getArg();
15391     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15392       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15393     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15394       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15395     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15396       Arg = ETLF->getSuccessValue();
15397       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15398     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15399       Arg = STLF->getSuccessValue();
15400       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15401     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15402       Arg = LR->getArg();
15403     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15404       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15405     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15406       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15407     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15408       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15409     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15410       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15411     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15412       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15413 
15414     if (Arg && !Finder.TraverseStmt(Arg))
15415       return true;
15416 
15417     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15418       if (!Finder.TraverseStmt(Args[I]))
15419         return true;
15420     }
15421   }
15422 
15423   return false;
15424 }
15425 
15426 void Sema::checkExceptionSpecification(
15427     bool IsTopLevel, ExceptionSpecificationType EST,
15428     ArrayRef<ParsedType> DynamicExceptions,
15429     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15430     SmallVectorImpl<QualType> &Exceptions,
15431     FunctionProtoType::ExceptionSpecInfo &ESI) {
15432   Exceptions.clear();
15433   ESI.Type = EST;
15434   if (EST == EST_Dynamic) {
15435     Exceptions.reserve(DynamicExceptions.size());
15436     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15437       // FIXME: Preserve type source info.
15438       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15439 
15440       if (IsTopLevel) {
15441         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15442         collectUnexpandedParameterPacks(ET, Unexpanded);
15443         if (!Unexpanded.empty()) {
15444           DiagnoseUnexpandedParameterPacks(
15445               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15446               Unexpanded);
15447           continue;
15448         }
15449       }
15450 
15451       // Check that the type is valid for an exception spec, and
15452       // drop it if not.
15453       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15454         Exceptions.push_back(ET);
15455     }
15456     ESI.Exceptions = Exceptions;
15457     return;
15458   }
15459 
15460   if (isComputedNoexcept(EST)) {
15461     assert((NoexceptExpr->isTypeDependent() ||
15462             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15463             Context.BoolTy) &&
15464            "Parser should have made sure that the expression is boolean");
15465     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15466       ESI.Type = EST_BasicNoexcept;
15467       return;
15468     }
15469 
15470     ESI.NoexceptExpr = NoexceptExpr;
15471     return;
15472   }
15473 }
15474 
15475 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15476              ExceptionSpecificationType EST,
15477              SourceRange SpecificationRange,
15478              ArrayRef<ParsedType> DynamicExceptions,
15479              ArrayRef<SourceRange> DynamicExceptionRanges,
15480              Expr *NoexceptExpr) {
15481   if (!MethodD)
15482     return;
15483 
15484   // Dig out the method we're referring to.
15485   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15486     MethodD = FunTmpl->getTemplatedDecl();
15487 
15488   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15489   if (!Method)
15490     return;
15491 
15492   // Check the exception specification.
15493   llvm::SmallVector<QualType, 4> Exceptions;
15494   FunctionProtoType::ExceptionSpecInfo ESI;
15495   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15496                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15497                               ESI);
15498 
15499   // Update the exception specification on the function type.
15500   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15501 
15502   if (Method->isStatic())
15503     checkThisInStaticMemberFunctionExceptionSpec(Method);
15504 
15505   if (Method->isVirtual()) {
15506     // Check overrides, which we previously had to delay.
15507     for (const CXXMethodDecl *O : Method->overridden_methods())
15508       CheckOverridingFunctionExceptionSpec(Method, O);
15509   }
15510 }
15511 
15512 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15513 ///
15514 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15515                                        SourceLocation DeclStart, Declarator &D,
15516                                        Expr *BitWidth,
15517                                        InClassInitStyle InitStyle,
15518                                        AccessSpecifier AS,
15519                                        const ParsedAttr &MSPropertyAttr) {
15520   IdentifierInfo *II = D.getIdentifier();
15521   if (!II) {
15522     Diag(DeclStart, diag::err_anonymous_property);
15523     return nullptr;
15524   }
15525   SourceLocation Loc = D.getIdentifierLoc();
15526 
15527   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15528   QualType T = TInfo->getType();
15529   if (getLangOpts().CPlusPlus) {
15530     CheckExtraCXXDefaultArguments(D);
15531 
15532     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15533                                         UPPC_DataMemberType)) {
15534       D.setInvalidType();
15535       T = Context.IntTy;
15536       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15537     }
15538   }
15539 
15540   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15541 
15542   if (D.getDeclSpec().isInlineSpecified())
15543     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15544         << getLangOpts().CPlusPlus17;
15545   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15546     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15547          diag::err_invalid_thread)
15548       << DeclSpec::getSpecifierName(TSCS);
15549 
15550   // Check to see if this name was declared as a member previously
15551   NamedDecl *PrevDecl = nullptr;
15552   LookupResult Previous(*this, II, Loc, LookupMemberName,
15553                         ForVisibleRedeclaration);
15554   LookupName(Previous, S);
15555   switch (Previous.getResultKind()) {
15556   case LookupResult::Found:
15557   case LookupResult::FoundUnresolvedValue:
15558     PrevDecl = Previous.getAsSingle<NamedDecl>();
15559     break;
15560 
15561   case LookupResult::FoundOverloaded:
15562     PrevDecl = Previous.getRepresentativeDecl();
15563     break;
15564 
15565   case LookupResult::NotFound:
15566   case LookupResult::NotFoundInCurrentInstantiation:
15567   case LookupResult::Ambiguous:
15568     break;
15569   }
15570 
15571   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15572     // Maybe we will complain about the shadowed template parameter.
15573     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15574     // Just pretend that we didn't see the previous declaration.
15575     PrevDecl = nullptr;
15576   }
15577 
15578   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15579     PrevDecl = nullptr;
15580 
15581   SourceLocation TSSL = D.getBeginLoc();
15582   MSPropertyDecl *NewPD =
15583       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15584                              MSPropertyAttr.getPropertyDataGetter(),
15585                              MSPropertyAttr.getPropertyDataSetter());
15586   ProcessDeclAttributes(TUScope, NewPD, D);
15587   NewPD->setAccess(AS);
15588 
15589   if (NewPD->isInvalidDecl())
15590     Record->setInvalidDecl();
15591 
15592   if (D.getDeclSpec().isModulePrivateSpecified())
15593     NewPD->setModulePrivate();
15594 
15595   if (NewPD->isInvalidDecl() && PrevDecl) {
15596     // Don't introduce NewFD into scope; there's already something
15597     // with the same name in the same scope.
15598   } else if (II) {
15599     PushOnScopeChains(NewPD, S);
15600   } else
15601     Record->addDecl(NewPD);
15602 
15603   return NewPD;
15604 }
15605