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, SourceLocation &Cxx2aLoc) {
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, Cxx2aLoc))
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, Cxx2aLoc))
1862       return false;
1863     if (If->getElse() &&
1864         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1865                                     Cxx1yLoc, Cxx2aLoc))
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, Cxx2aLoc))
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, Cxx2aLoc))
1900         return false;
1901     return true;
1902 
1903   case Stmt::CXXTryStmtClass:
1904     if (Cxx2aLoc.isInvalid())
1905       Cxx2aLoc = S->getBeginLoc();
1906     for (Stmt *SubStmt : S->children()) {
1907       if (SubStmt &&
1908           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1909                                       Cxx1yLoc, Cxx2aLoc))
1910         return false;
1911     }
1912     return true;
1913 
1914   case Stmt::CXXCatchStmtClass:
1915     // Do not bother checking the language mode (already covered by the
1916     // try block check).
1917     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1918                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
1919                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1920       return false;
1921     return true;
1922 
1923   default:
1924     if (!isa<Expr>(S))
1925       break;
1926 
1927     // C++1y allows expression-statements.
1928     if (!Cxx1yLoc.isValid())
1929       Cxx1yLoc = S->getBeginLoc();
1930     return true;
1931   }
1932 
1933   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1934       << isa<CXXConstructorDecl>(Dcl);
1935   return false;
1936 }
1937 
1938 /// Check the body for the given constexpr function declaration only contains
1939 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1940 ///
1941 /// \return true if the body is OK, false if we have diagnosed a problem.
1942 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1943   SmallVector<SourceLocation, 4> ReturnStmts;
1944 
1945   if (isa<CXXTryStmt>(Body)) {
1946     // C++11 [dcl.constexpr]p3:
1947     //  The definition of a constexpr function shall satisfy the following
1948     //  constraints: [...]
1949     // - its function-body shall be = delete, = default, or a
1950     //   compound-statement
1951     //
1952     // C++11 [dcl.constexpr]p4:
1953     //  In the definition of a constexpr constructor, [...]
1954     // - its function-body shall not be a function-try-block;
1955     //
1956     // This restriction is lifted in C++2a, as long as inner statements also
1957     // apply the general constexpr rules.
1958     Diag(Body->getBeginLoc(),
1959          !getLangOpts().CPlusPlus2a
1960              ? diag::ext_constexpr_function_try_block_cxx2a
1961              : diag::warn_cxx17_compat_constexpr_function_try_block)
1962         << isa<CXXConstructorDecl>(Dcl);
1963   }
1964 
1965   // - its function-body shall be [...] a compound-statement that contains only
1966   //   [... list of cases ...]
1967   //
1968   // Note that walking the children here is enough to properly check for
1969   // CompoundStmt and CXXTryStmt body.
1970   SourceLocation Cxx1yLoc, Cxx2aLoc;
1971   for (Stmt *SubStmt : Body->children()) {
1972     if (SubStmt &&
1973         !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1974                                     Cxx1yLoc, Cxx2aLoc))
1975       return false;
1976   }
1977 
1978   if (Cxx2aLoc.isValid())
1979     Diag(Cxx2aLoc,
1980          getLangOpts().CPlusPlus2a
1981            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1982            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1983       << isa<CXXConstructorDecl>(Dcl);
1984   if (Cxx1yLoc.isValid())
1985     Diag(Cxx1yLoc,
1986          getLangOpts().CPlusPlus14
1987            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1988            : diag::ext_constexpr_body_invalid_stmt)
1989       << isa<CXXConstructorDecl>(Dcl);
1990 
1991   if (const CXXConstructorDecl *Constructor
1992         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1993     const CXXRecordDecl *RD = Constructor->getParent();
1994     // DR1359:
1995     // - every non-variant non-static data member and base class sub-object
1996     //   shall be initialized;
1997     // DR1460:
1998     // - if the class is a union having variant members, exactly one of them
1999     //   shall be initialized;
2000     if (RD->isUnion()) {
2001       if (Constructor->getNumCtorInitializers() == 0 &&
2002           RD->hasVariantMembers()) {
2003         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2004         return false;
2005       }
2006     } else if (!Constructor->isDependentContext() &&
2007                !Constructor->isDelegatingConstructor()) {
2008       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2009 
2010       // Skip detailed checking if we have enough initializers, and we would
2011       // allow at most one initializer per member.
2012       bool AnyAnonStructUnionMembers = false;
2013       unsigned Fields = 0;
2014       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2015            E = RD->field_end(); I != E; ++I, ++Fields) {
2016         if (I->isAnonymousStructOrUnion()) {
2017           AnyAnonStructUnionMembers = true;
2018           break;
2019         }
2020       }
2021       // DR1460:
2022       // - if the class is a union-like class, but is not a union, for each of
2023       //   its anonymous union members having variant members, exactly one of
2024       //   them shall be initialized;
2025       if (AnyAnonStructUnionMembers ||
2026           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2027         // Check initialization of non-static data members. Base classes are
2028         // always initialized so do not need to be checked. Dependent bases
2029         // might not have initializers in the member initializer list.
2030         llvm::SmallSet<Decl*, 16> Inits;
2031         for (const auto *I: Constructor->inits()) {
2032           if (FieldDecl *FD = I->getMember())
2033             Inits.insert(FD);
2034           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2035             Inits.insert(ID->chain_begin(), ID->chain_end());
2036         }
2037 
2038         bool Diagnosed = false;
2039         for (auto *I : RD->fields())
2040           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2041         if (Diagnosed)
2042           return false;
2043       }
2044     }
2045   } else {
2046     if (ReturnStmts.empty()) {
2047       // C++1y doesn't require constexpr functions to contain a 'return'
2048       // statement. We still do, unless the return type might be void, because
2049       // otherwise if there's no return statement, the function cannot
2050       // be used in a core constant expression.
2051       bool OK = getLangOpts().CPlusPlus14 &&
2052                 (Dcl->getReturnType()->isVoidType() ||
2053                  Dcl->getReturnType()->isDependentType());
2054       Diag(Dcl->getLocation(),
2055            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2056               : diag::err_constexpr_body_no_return);
2057       if (!OK)
2058         return false;
2059     } else if (ReturnStmts.size() > 1) {
2060       Diag(ReturnStmts.back(),
2061            getLangOpts().CPlusPlus14
2062              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2063              : diag::ext_constexpr_body_multiple_return);
2064       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2065         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2066     }
2067   }
2068 
2069   // C++11 [dcl.constexpr]p5:
2070   //   if no function argument values exist such that the function invocation
2071   //   substitution would produce a constant expression, the program is
2072   //   ill-formed; no diagnostic required.
2073   // C++11 [dcl.constexpr]p3:
2074   //   - every constructor call and implicit conversion used in initializing the
2075   //     return value shall be one of those allowed in a constant expression.
2076   // C++11 [dcl.constexpr]p4:
2077   //   - every constructor involved in initializing non-static data members and
2078   //     base class sub-objects shall be a constexpr constructor.
2079   SmallVector<PartialDiagnosticAt, 8> Diags;
2080   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2081     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2082       << isa<CXXConstructorDecl>(Dcl);
2083     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2084       Diag(Diags[I].first, Diags[I].second);
2085     // Don't return false here: we allow this for compatibility in
2086     // system headers.
2087   }
2088 
2089   return true;
2090 }
2091 
2092 /// Get the class that is directly named by the current context. This is the
2093 /// class for which an unqualified-id in this scope could name a constructor
2094 /// or destructor.
2095 ///
2096 /// If the scope specifier denotes a class, this will be that class.
2097 /// If the scope specifier is empty, this will be the class whose
2098 /// member-specification we are currently within. Otherwise, there
2099 /// is no such class.
2100 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2101   assert(getLangOpts().CPlusPlus && "No class names in C!");
2102 
2103   if (SS && SS->isInvalid())
2104     return nullptr;
2105 
2106   if (SS && SS->isNotEmpty()) {
2107     DeclContext *DC = computeDeclContext(*SS, true);
2108     return dyn_cast_or_null<CXXRecordDecl>(DC);
2109   }
2110 
2111   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2112 }
2113 
2114 /// isCurrentClassName - Determine whether the identifier II is the
2115 /// name of the class type currently being defined. In the case of
2116 /// nested classes, this will only return true if II is the name of
2117 /// the innermost class.
2118 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2119                               const CXXScopeSpec *SS) {
2120   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2121   return CurDecl && &II == CurDecl->getIdentifier();
2122 }
2123 
2124 /// Determine whether the identifier II is a typo for the name of
2125 /// the class type currently being defined. If so, update it to the identifier
2126 /// that should have been used.
2127 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2128   assert(getLangOpts().CPlusPlus && "No class names in C!");
2129 
2130   if (!getLangOpts().SpellChecking)
2131     return false;
2132 
2133   CXXRecordDecl *CurDecl;
2134   if (SS && SS->isSet() && !SS->isInvalid()) {
2135     DeclContext *DC = computeDeclContext(*SS, true);
2136     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2137   } else
2138     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2139 
2140   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2141       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2142           < II->getLength()) {
2143     II = CurDecl->getIdentifier();
2144     return true;
2145   }
2146 
2147   return false;
2148 }
2149 
2150 /// Determine whether the given class is a base class of the given
2151 /// class, including looking at dependent bases.
2152 static bool findCircularInheritance(const CXXRecordDecl *Class,
2153                                     const CXXRecordDecl *Current) {
2154   SmallVector<const CXXRecordDecl*, 8> Queue;
2155 
2156   Class = Class->getCanonicalDecl();
2157   while (true) {
2158     for (const auto &I : Current->bases()) {
2159       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2160       if (!Base)
2161         continue;
2162 
2163       Base = Base->getDefinition();
2164       if (!Base)
2165         continue;
2166 
2167       if (Base->getCanonicalDecl() == Class)
2168         return true;
2169 
2170       Queue.push_back(Base);
2171     }
2172 
2173     if (Queue.empty())
2174       return false;
2175 
2176     Current = Queue.pop_back_val();
2177   }
2178 
2179   return false;
2180 }
2181 
2182 /// Check the validity of a C++ base class specifier.
2183 ///
2184 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2185 /// and returns NULL otherwise.
2186 CXXBaseSpecifier *
2187 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2188                          SourceRange SpecifierRange,
2189                          bool Virtual, AccessSpecifier Access,
2190                          TypeSourceInfo *TInfo,
2191                          SourceLocation EllipsisLoc) {
2192   QualType BaseType = TInfo->getType();
2193 
2194   // C++ [class.union]p1:
2195   //   A union shall not have base classes.
2196   if (Class->isUnion()) {
2197     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2198       << SpecifierRange;
2199     return nullptr;
2200   }
2201 
2202   if (EllipsisLoc.isValid() &&
2203       !TInfo->getType()->containsUnexpandedParameterPack()) {
2204     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2205       << TInfo->getTypeLoc().getSourceRange();
2206     EllipsisLoc = SourceLocation();
2207   }
2208 
2209   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2210 
2211   if (BaseType->isDependentType()) {
2212     // Make sure that we don't have circular inheritance among our dependent
2213     // bases. For non-dependent bases, the check for completeness below handles
2214     // this.
2215     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2216       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2217           ((BaseDecl = BaseDecl->getDefinition()) &&
2218            findCircularInheritance(Class, BaseDecl))) {
2219         Diag(BaseLoc, diag::err_circular_inheritance)
2220           << BaseType << Context.getTypeDeclType(Class);
2221 
2222         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2223           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2224             << BaseType;
2225 
2226         return nullptr;
2227       }
2228     }
2229 
2230     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2231                                           Class->getTagKind() == TTK_Class,
2232                                           Access, TInfo, EllipsisLoc);
2233   }
2234 
2235   // Base specifiers must be record types.
2236   if (!BaseType->isRecordType()) {
2237     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2238     return nullptr;
2239   }
2240 
2241   // C++ [class.union]p1:
2242   //   A union shall not be used as a base class.
2243   if (BaseType->isUnionType()) {
2244     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2245     return nullptr;
2246   }
2247 
2248   // For the MS ABI, propagate DLL attributes to base class templates.
2249   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2250     if (Attr *ClassAttr = getDLLAttr(Class)) {
2251       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2252               BaseType->getAsCXXRecordDecl())) {
2253         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2254                                             BaseLoc);
2255       }
2256     }
2257   }
2258 
2259   // C++ [class.derived]p2:
2260   //   The class-name in a base-specifier shall not be an incompletely
2261   //   defined class.
2262   if (RequireCompleteType(BaseLoc, BaseType,
2263                           diag::err_incomplete_base_class, SpecifierRange)) {
2264     Class->setInvalidDecl();
2265     return nullptr;
2266   }
2267 
2268   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2269   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2270   assert(BaseDecl && "Record type has no declaration");
2271   BaseDecl = BaseDecl->getDefinition();
2272   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2273   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2274   assert(CXXBaseDecl && "Base type is not a C++ type");
2275 
2276   // Microsoft docs say:
2277   // "If a base-class has a code_seg attribute, derived classes must have the
2278   // same attribute."
2279   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2280   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2281   if ((DerivedCSA || BaseCSA) &&
2282       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2283     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2284     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2285       << CXXBaseDecl;
2286     return nullptr;
2287   }
2288 
2289   // A class which contains a flexible array member is not suitable for use as a
2290   // base class:
2291   //   - If the layout determines that a base comes before another base,
2292   //     the flexible array member would index into the subsequent base.
2293   //   - If the layout determines that base comes before the derived class,
2294   //     the flexible array member would index into the derived class.
2295   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2296     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2297       << CXXBaseDecl->getDeclName();
2298     return nullptr;
2299   }
2300 
2301   // C++ [class]p3:
2302   //   If a class is marked final and it appears as a base-type-specifier in
2303   //   base-clause, the program is ill-formed.
2304   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2305     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2306       << CXXBaseDecl->getDeclName()
2307       << FA->isSpelledAsSealed();
2308     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2309         << CXXBaseDecl->getDeclName() << FA->getRange();
2310     return nullptr;
2311   }
2312 
2313   if (BaseDecl->isInvalidDecl())
2314     Class->setInvalidDecl();
2315 
2316   // Create the base specifier.
2317   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2318                                         Class->getTagKind() == TTK_Class,
2319                                         Access, TInfo, EllipsisLoc);
2320 }
2321 
2322 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2323 /// one entry in the base class list of a class specifier, for
2324 /// example:
2325 ///    class foo : public bar, virtual private baz {
2326 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2327 BaseResult
2328 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2329                          ParsedAttributes &Attributes,
2330                          bool Virtual, AccessSpecifier Access,
2331                          ParsedType basetype, SourceLocation BaseLoc,
2332                          SourceLocation EllipsisLoc) {
2333   if (!classdecl)
2334     return true;
2335 
2336   AdjustDeclIfTemplate(classdecl);
2337   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2338   if (!Class)
2339     return true;
2340 
2341   // We haven't yet attached the base specifiers.
2342   Class->setIsParsingBaseSpecifiers();
2343 
2344   // We do not support any C++11 attributes on base-specifiers yet.
2345   // Diagnose any attributes we see.
2346   for (const ParsedAttr &AL : Attributes) {
2347     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2348       continue;
2349     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2350                           ? diag::warn_unknown_attribute_ignored
2351                           : diag::err_base_specifier_attribute)
2352         << AL.getName();
2353   }
2354 
2355   TypeSourceInfo *TInfo = nullptr;
2356   GetTypeFromParser(basetype, &TInfo);
2357 
2358   if (EllipsisLoc.isInvalid() &&
2359       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2360                                       UPPC_BaseType))
2361     return true;
2362 
2363   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2364                                                       Virtual, Access, TInfo,
2365                                                       EllipsisLoc))
2366     return BaseSpec;
2367   else
2368     Class->setInvalidDecl();
2369 
2370   return true;
2371 }
2372 
2373 /// Use small set to collect indirect bases.  As this is only used
2374 /// locally, there's no need to abstract the small size parameter.
2375 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2376 
2377 /// Recursively add the bases of Type.  Don't add Type itself.
2378 static void
2379 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2380                   const QualType &Type)
2381 {
2382   // Even though the incoming type is a base, it might not be
2383   // a class -- it could be a template parm, for instance.
2384   if (auto Rec = Type->getAs<RecordType>()) {
2385     auto Decl = Rec->getAsCXXRecordDecl();
2386 
2387     // Iterate over its bases.
2388     for (const auto &BaseSpec : Decl->bases()) {
2389       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2390         .getUnqualifiedType();
2391       if (Set.insert(Base).second)
2392         // If we've not already seen it, recurse.
2393         NoteIndirectBases(Context, Set, Base);
2394     }
2395   }
2396 }
2397 
2398 /// Performs the actual work of attaching the given base class
2399 /// specifiers to a C++ class.
2400 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2401                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2402  if (Bases.empty())
2403     return false;
2404 
2405   // Used to keep track of which base types we have already seen, so
2406   // that we can properly diagnose redundant direct base types. Note
2407   // that the key is always the unqualified canonical type of the base
2408   // class.
2409   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2410 
2411   // Used to track indirect bases so we can see if a direct base is
2412   // ambiguous.
2413   IndirectBaseSet IndirectBaseTypes;
2414 
2415   // Copy non-redundant base specifiers into permanent storage.
2416   unsigned NumGoodBases = 0;
2417   bool Invalid = false;
2418   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2419     QualType NewBaseType
2420       = Context.getCanonicalType(Bases[idx]->getType());
2421     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2422 
2423     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2424     if (KnownBase) {
2425       // C++ [class.mi]p3:
2426       //   A class shall not be specified as a direct base class of a
2427       //   derived class more than once.
2428       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2429           << KnownBase->getType() << Bases[idx]->getSourceRange();
2430 
2431       // Delete the duplicate base class specifier; we're going to
2432       // overwrite its pointer later.
2433       Context.Deallocate(Bases[idx]);
2434 
2435       Invalid = true;
2436     } else {
2437       // Okay, add this new base class.
2438       KnownBase = Bases[idx];
2439       Bases[NumGoodBases++] = Bases[idx];
2440 
2441       // Note this base's direct & indirect bases, if there could be ambiguity.
2442       if (Bases.size() > 1)
2443         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2444 
2445       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2446         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2447         if (Class->isInterface() &&
2448               (!RD->isInterfaceLike() ||
2449                KnownBase->getAccessSpecifier() != AS_public)) {
2450           // The Microsoft extension __interface does not permit bases that
2451           // are not themselves public interfaces.
2452           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2453               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2454               << RD->getSourceRange();
2455           Invalid = true;
2456         }
2457         if (RD->hasAttr<WeakAttr>())
2458           Class->addAttr(WeakAttr::CreateImplicit(Context));
2459       }
2460     }
2461   }
2462 
2463   // Attach the remaining base class specifiers to the derived class.
2464   Class->setBases(Bases.data(), NumGoodBases);
2465 
2466   // Check that the only base classes that are duplicate are virtual.
2467   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2468     // Check whether this direct base is inaccessible due to ambiguity.
2469     QualType BaseType = Bases[idx]->getType();
2470 
2471     // Skip all dependent types in templates being used as base specifiers.
2472     // Checks below assume that the base specifier is a CXXRecord.
2473     if (BaseType->isDependentType())
2474       continue;
2475 
2476     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2477       .getUnqualifiedType();
2478 
2479     if (IndirectBaseTypes.count(CanonicalBase)) {
2480       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2481                          /*DetectVirtual=*/true);
2482       bool found
2483         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2484       assert(found);
2485       (void)found;
2486 
2487       if (Paths.isAmbiguous(CanonicalBase))
2488         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2489             << BaseType << getAmbiguousPathsDisplayString(Paths)
2490             << Bases[idx]->getSourceRange();
2491       else
2492         assert(Bases[idx]->isVirtual());
2493     }
2494 
2495     // Delete the base class specifier, since its data has been copied
2496     // into the CXXRecordDecl.
2497     Context.Deallocate(Bases[idx]);
2498   }
2499 
2500   return Invalid;
2501 }
2502 
2503 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2504 /// class, after checking whether there are any duplicate base
2505 /// classes.
2506 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2507                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2508   if (!ClassDecl || Bases.empty())
2509     return;
2510 
2511   AdjustDeclIfTemplate(ClassDecl);
2512   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2513 }
2514 
2515 /// Determine whether the type \p Derived is a C++ class that is
2516 /// derived from the type \p Base.
2517 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2518   if (!getLangOpts().CPlusPlus)
2519     return false;
2520 
2521   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2522   if (!DerivedRD)
2523     return false;
2524 
2525   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2526   if (!BaseRD)
2527     return false;
2528 
2529   // If either the base or the derived type is invalid, don't try to
2530   // check whether one is derived from the other.
2531   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2532     return false;
2533 
2534   // FIXME: In a modules build, do we need the entire path to be visible for us
2535   // to be able to use the inheritance relationship?
2536   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2537     return false;
2538 
2539   return DerivedRD->isDerivedFrom(BaseRD);
2540 }
2541 
2542 /// Determine whether the type \p Derived is a C++ class that is
2543 /// derived from the type \p Base.
2544 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2545                          CXXBasePaths &Paths) {
2546   if (!getLangOpts().CPlusPlus)
2547     return false;
2548 
2549   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2550   if (!DerivedRD)
2551     return false;
2552 
2553   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2554   if (!BaseRD)
2555     return false;
2556 
2557   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2558     return false;
2559 
2560   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2561 }
2562 
2563 static void BuildBasePathArray(const CXXBasePath &Path,
2564                                CXXCastPath &BasePathArray) {
2565   // We first go backward and check if we have a virtual base.
2566   // FIXME: It would be better if CXXBasePath had the base specifier for
2567   // the nearest virtual base.
2568   unsigned Start = 0;
2569   for (unsigned I = Path.size(); I != 0; --I) {
2570     if (Path[I - 1].Base->isVirtual()) {
2571       Start = I - 1;
2572       break;
2573     }
2574   }
2575 
2576   // Now add all bases.
2577   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2578     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2579 }
2580 
2581 
2582 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2583                               CXXCastPath &BasePathArray) {
2584   assert(BasePathArray.empty() && "Base path array must be empty!");
2585   assert(Paths.isRecordingPaths() && "Must record paths!");
2586   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2587 }
2588 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2589 /// conversion (where Derived and Base are class types) is
2590 /// well-formed, meaning that the conversion is unambiguous (and
2591 /// that all of the base classes are accessible). Returns true
2592 /// and emits a diagnostic if the code is ill-formed, returns false
2593 /// otherwise. Loc is the location where this routine should point to
2594 /// if there is an error, and Range is the source range to highlight
2595 /// if there is an error.
2596 ///
2597 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2598 /// diagnostic for the respective type of error will be suppressed, but the
2599 /// check for ill-formed code will still be performed.
2600 bool
2601 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2602                                    unsigned InaccessibleBaseID,
2603                                    unsigned AmbigiousBaseConvID,
2604                                    SourceLocation Loc, SourceRange Range,
2605                                    DeclarationName Name,
2606                                    CXXCastPath *BasePath,
2607                                    bool IgnoreAccess) {
2608   // First, determine whether the path from Derived to Base is
2609   // ambiguous. This is slightly more expensive than checking whether
2610   // the Derived to Base conversion exists, because here we need to
2611   // explore multiple paths to determine if there is an ambiguity.
2612   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2613                      /*DetectVirtual=*/false);
2614   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2615   if (!DerivationOkay)
2616     return true;
2617 
2618   const CXXBasePath *Path = nullptr;
2619   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2620     Path = &Paths.front();
2621 
2622   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2623   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2624   // user to access such bases.
2625   if (!Path && getLangOpts().MSVCCompat) {
2626     for (const CXXBasePath &PossiblePath : Paths) {
2627       if (PossiblePath.size() == 1) {
2628         Path = &PossiblePath;
2629         if (AmbigiousBaseConvID)
2630           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2631               << Base << Derived << Range;
2632         break;
2633       }
2634     }
2635   }
2636 
2637   if (Path) {
2638     if (!IgnoreAccess) {
2639       // Check that the base class can be accessed.
2640       switch (
2641           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2642       case AR_inaccessible:
2643         return true;
2644       case AR_accessible:
2645       case AR_dependent:
2646       case AR_delayed:
2647         break;
2648       }
2649     }
2650 
2651     // Build a base path if necessary.
2652     if (BasePath)
2653       ::BuildBasePathArray(*Path, *BasePath);
2654     return false;
2655   }
2656 
2657   if (AmbigiousBaseConvID) {
2658     // We know that the derived-to-base conversion is ambiguous, and
2659     // we're going to produce a diagnostic. Perform the derived-to-base
2660     // search just one more time to compute all of the possible paths so
2661     // that we can print them out. This is more expensive than any of
2662     // the previous derived-to-base checks we've done, but at this point
2663     // performance isn't as much of an issue.
2664     Paths.clear();
2665     Paths.setRecordingPaths(true);
2666     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2667     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2668     (void)StillOkay;
2669 
2670     // Build up a textual representation of the ambiguous paths, e.g.,
2671     // D -> B -> A, that will be used to illustrate the ambiguous
2672     // conversions in the diagnostic. We only print one of the paths
2673     // to each base class subobject.
2674     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2675 
2676     Diag(Loc, AmbigiousBaseConvID)
2677     << Derived << Base << PathDisplayStr << Range << Name;
2678   }
2679   return true;
2680 }
2681 
2682 bool
2683 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2684                                    SourceLocation Loc, SourceRange Range,
2685                                    CXXCastPath *BasePath,
2686                                    bool IgnoreAccess) {
2687   return CheckDerivedToBaseConversion(
2688       Derived, Base, diag::err_upcast_to_inaccessible_base,
2689       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2690       BasePath, IgnoreAccess);
2691 }
2692 
2693 
2694 /// Builds a string representing ambiguous paths from a
2695 /// specific derived class to different subobjects of the same base
2696 /// class.
2697 ///
2698 /// This function builds a string that can be used in error messages
2699 /// to show the different paths that one can take through the
2700 /// inheritance hierarchy to go from the derived class to different
2701 /// subobjects of a base class. The result looks something like this:
2702 /// @code
2703 /// struct D -> struct B -> struct A
2704 /// struct D -> struct C -> struct A
2705 /// @endcode
2706 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2707   std::string PathDisplayStr;
2708   std::set<unsigned> DisplayedPaths;
2709   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2710        Path != Paths.end(); ++Path) {
2711     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2712       // We haven't displayed a path to this particular base
2713       // class subobject yet.
2714       PathDisplayStr += "\n    ";
2715       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2716       for (CXXBasePath::const_iterator Element = Path->begin();
2717            Element != Path->end(); ++Element)
2718         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2719     }
2720   }
2721 
2722   return PathDisplayStr;
2723 }
2724 
2725 //===----------------------------------------------------------------------===//
2726 // C++ class member Handling
2727 //===----------------------------------------------------------------------===//
2728 
2729 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2730 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2731                                 SourceLocation ColonLoc,
2732                                 const ParsedAttributesView &Attrs) {
2733   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2734   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2735                                                   ASLoc, ColonLoc);
2736   CurContext->addHiddenDecl(ASDecl);
2737   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2738 }
2739 
2740 /// CheckOverrideControl - Check C++11 override control semantics.
2741 void Sema::CheckOverrideControl(NamedDecl *D) {
2742   if (D->isInvalidDecl())
2743     return;
2744 
2745   // We only care about "override" and "final" declarations.
2746   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2747     return;
2748 
2749   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2750 
2751   // We can't check dependent instance methods.
2752   if (MD && MD->isInstance() &&
2753       (MD->getParent()->hasAnyDependentBases() ||
2754        MD->getType()->isDependentType()))
2755     return;
2756 
2757   if (MD && !MD->isVirtual()) {
2758     // If we have a non-virtual method, check if if hides a virtual method.
2759     // (In that case, it's most likely the method has the wrong type.)
2760     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2761     FindHiddenVirtualMethods(MD, OverloadedMethods);
2762 
2763     if (!OverloadedMethods.empty()) {
2764       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2765         Diag(OA->getLocation(),
2766              diag::override_keyword_hides_virtual_member_function)
2767           << "override" << (OverloadedMethods.size() > 1);
2768       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2769         Diag(FA->getLocation(),
2770              diag::override_keyword_hides_virtual_member_function)
2771           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2772           << (OverloadedMethods.size() > 1);
2773       }
2774       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2775       MD->setInvalidDecl();
2776       return;
2777     }
2778     // Fall through into the general case diagnostic.
2779     // FIXME: We might want to attempt typo correction here.
2780   }
2781 
2782   if (!MD || !MD->isVirtual()) {
2783     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2784       Diag(OA->getLocation(),
2785            diag::override_keyword_only_allowed_on_virtual_member_functions)
2786         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2787       D->dropAttr<OverrideAttr>();
2788     }
2789     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2790       Diag(FA->getLocation(),
2791            diag::override_keyword_only_allowed_on_virtual_member_functions)
2792         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2793         << FixItHint::CreateRemoval(FA->getLocation());
2794       D->dropAttr<FinalAttr>();
2795     }
2796     return;
2797   }
2798 
2799   // C++11 [class.virtual]p5:
2800   //   If a function is marked with the virt-specifier override and
2801   //   does not override a member function of a base class, the program is
2802   //   ill-formed.
2803   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2804   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2805     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2806       << MD->getDeclName();
2807 }
2808 
2809 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2810   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2811     return;
2812   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2813   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2814     return;
2815 
2816   SourceLocation Loc = MD->getLocation();
2817   SourceLocation SpellingLoc = Loc;
2818   if (getSourceManager().isMacroArgExpansion(Loc))
2819     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2820   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2821   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2822       return;
2823 
2824   if (MD->size_overridden_methods() > 0) {
2825     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2826                           ? diag::warn_destructor_marked_not_override_overriding
2827                           : diag::warn_function_marked_not_override_overriding;
2828     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2829     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2830     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2831   }
2832 }
2833 
2834 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2835 /// function overrides a virtual member function marked 'final', according to
2836 /// C++11 [class.virtual]p4.
2837 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2838                                                   const CXXMethodDecl *Old) {
2839   FinalAttr *FA = Old->getAttr<FinalAttr>();
2840   if (!FA)
2841     return false;
2842 
2843   Diag(New->getLocation(), diag::err_final_function_overridden)
2844     << New->getDeclName()
2845     << FA->isSpelledAsSealed();
2846   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2847   return true;
2848 }
2849 
2850 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2851   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2852   // FIXME: Destruction of ObjC lifetime types has side-effects.
2853   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2854     return !RD->isCompleteDefinition() ||
2855            !RD->hasTrivialDefaultConstructor() ||
2856            !RD->hasTrivialDestructor();
2857   return false;
2858 }
2859 
2860 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2861   ParsedAttributesView::const_iterator Itr =
2862       llvm::find_if(list, [](const ParsedAttr &AL) {
2863         return AL.isDeclspecPropertyAttribute();
2864       });
2865   if (Itr != list.end())
2866     return &*Itr;
2867   return nullptr;
2868 }
2869 
2870 // Check if there is a field shadowing.
2871 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2872                                       DeclarationName FieldName,
2873                                       const CXXRecordDecl *RD,
2874                                       bool DeclIsField) {
2875   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2876     return;
2877 
2878   // To record a shadowed field in a base
2879   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2880   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2881                            CXXBasePath &Path) {
2882     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2883     // Record an ambiguous path directly
2884     if (Bases.find(Base) != Bases.end())
2885       return true;
2886     for (const auto Field : Base->lookup(FieldName)) {
2887       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2888           Field->getAccess() != AS_private) {
2889         assert(Field->getAccess() != AS_none);
2890         assert(Bases.find(Base) == Bases.end());
2891         Bases[Base] = Field;
2892         return true;
2893       }
2894     }
2895     return false;
2896   };
2897 
2898   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2899                      /*DetectVirtual=*/true);
2900   if (!RD->lookupInBases(FieldShadowed, Paths))
2901     return;
2902 
2903   for (const auto &P : Paths) {
2904     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2905     auto It = Bases.find(Base);
2906     // Skip duplicated bases
2907     if (It == Bases.end())
2908       continue;
2909     auto BaseField = It->second;
2910     assert(BaseField->getAccess() != AS_private);
2911     if (AS_none !=
2912         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2913       Diag(Loc, diag::warn_shadow_field)
2914         << FieldName << RD << Base << DeclIsField;
2915       Diag(BaseField->getLocation(), diag::note_shadow_field);
2916       Bases.erase(It);
2917     }
2918   }
2919 }
2920 
2921 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2922 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2923 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2924 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2925 /// present (but parsing it has been deferred).
2926 NamedDecl *
2927 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2928                                MultiTemplateParamsArg TemplateParameterLists,
2929                                Expr *BW, const VirtSpecifiers &VS,
2930                                InClassInitStyle InitStyle) {
2931   const DeclSpec &DS = D.getDeclSpec();
2932   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2933   DeclarationName Name = NameInfo.getName();
2934   SourceLocation Loc = NameInfo.getLoc();
2935 
2936   // For anonymous bitfields, the location should point to the type.
2937   if (Loc.isInvalid())
2938     Loc = D.getBeginLoc();
2939 
2940   Expr *BitWidth = static_cast<Expr*>(BW);
2941 
2942   assert(isa<CXXRecordDecl>(CurContext));
2943   assert(!DS.isFriendSpecified());
2944 
2945   bool isFunc = D.isDeclarationOfFunction();
2946   const ParsedAttr *MSPropertyAttr =
2947       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2948 
2949   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2950     // The Microsoft extension __interface only permits public member functions
2951     // and prohibits constructors, destructors, operators, non-public member
2952     // functions, static methods and data members.
2953     unsigned InvalidDecl;
2954     bool ShowDeclName = true;
2955     if (!isFunc &&
2956         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2957       InvalidDecl = 0;
2958     else if (!isFunc)
2959       InvalidDecl = 1;
2960     else if (AS != AS_public)
2961       InvalidDecl = 2;
2962     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2963       InvalidDecl = 3;
2964     else switch (Name.getNameKind()) {
2965       case DeclarationName::CXXConstructorName:
2966         InvalidDecl = 4;
2967         ShowDeclName = false;
2968         break;
2969 
2970       case DeclarationName::CXXDestructorName:
2971         InvalidDecl = 5;
2972         ShowDeclName = false;
2973         break;
2974 
2975       case DeclarationName::CXXOperatorName:
2976       case DeclarationName::CXXConversionFunctionName:
2977         InvalidDecl = 6;
2978         break;
2979 
2980       default:
2981         InvalidDecl = 0;
2982         break;
2983     }
2984 
2985     if (InvalidDecl) {
2986       if (ShowDeclName)
2987         Diag(Loc, diag::err_invalid_member_in_interface)
2988           << (InvalidDecl-1) << Name;
2989       else
2990         Diag(Loc, diag::err_invalid_member_in_interface)
2991           << (InvalidDecl-1) << "";
2992       return nullptr;
2993     }
2994   }
2995 
2996   // C++ 9.2p6: A member shall not be declared to have automatic storage
2997   // duration (auto, register) or with the extern storage-class-specifier.
2998   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2999   // data members and cannot be applied to names declared const or static,
3000   // and cannot be applied to reference members.
3001   switch (DS.getStorageClassSpec()) {
3002   case DeclSpec::SCS_unspecified:
3003   case DeclSpec::SCS_typedef:
3004   case DeclSpec::SCS_static:
3005     break;
3006   case DeclSpec::SCS_mutable:
3007     if (isFunc) {
3008       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3009 
3010       // FIXME: It would be nicer if the keyword was ignored only for this
3011       // declarator. Otherwise we could get follow-up errors.
3012       D.getMutableDeclSpec().ClearStorageClassSpecs();
3013     }
3014     break;
3015   default:
3016     Diag(DS.getStorageClassSpecLoc(),
3017          diag::err_storageclass_invalid_for_member);
3018     D.getMutableDeclSpec().ClearStorageClassSpecs();
3019     break;
3020   }
3021 
3022   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3023                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3024                       !isFunc);
3025 
3026   if (DS.isConstexprSpecified() && isInstField) {
3027     SemaDiagnosticBuilder B =
3028         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3029     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3030     if (InitStyle == ICIS_NoInit) {
3031       B << 0 << 0;
3032       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3033         B << FixItHint::CreateRemoval(ConstexprLoc);
3034       else {
3035         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3036         D.getMutableDeclSpec().ClearConstexprSpec();
3037         const char *PrevSpec;
3038         unsigned DiagID;
3039         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3040             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3041         (void)Failed;
3042         assert(!Failed && "Making a constexpr member const shouldn't fail");
3043       }
3044     } else {
3045       B << 1;
3046       const char *PrevSpec;
3047       unsigned DiagID;
3048       if (D.getMutableDeclSpec().SetStorageClassSpec(
3049           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3050           Context.getPrintingPolicy())) {
3051         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3052                "This is the only DeclSpec that should fail to be applied");
3053         B << 1;
3054       } else {
3055         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3056         isInstField = false;
3057       }
3058     }
3059   }
3060 
3061   NamedDecl *Member;
3062   if (isInstField) {
3063     CXXScopeSpec &SS = D.getCXXScopeSpec();
3064 
3065     // Data members must have identifiers for names.
3066     if (!Name.isIdentifier()) {
3067       Diag(Loc, diag::err_bad_variable_name)
3068         << Name;
3069       return nullptr;
3070     }
3071 
3072     IdentifierInfo *II = Name.getAsIdentifierInfo();
3073 
3074     // Member field could not be with "template" keyword.
3075     // So TemplateParameterLists should be empty in this case.
3076     if (TemplateParameterLists.size()) {
3077       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3078       if (TemplateParams->size()) {
3079         // There is no such thing as a member field template.
3080         Diag(D.getIdentifierLoc(), diag::err_template_member)
3081             << II
3082             << SourceRange(TemplateParams->getTemplateLoc(),
3083                 TemplateParams->getRAngleLoc());
3084       } else {
3085         // There is an extraneous 'template<>' for this member.
3086         Diag(TemplateParams->getTemplateLoc(),
3087             diag::err_template_member_noparams)
3088             << II
3089             << SourceRange(TemplateParams->getTemplateLoc(),
3090                 TemplateParams->getRAngleLoc());
3091       }
3092       return nullptr;
3093     }
3094 
3095     if (SS.isSet() && !SS.isInvalid()) {
3096       // The user provided a superfluous scope specifier inside a class
3097       // definition:
3098       //
3099       // class X {
3100       //   int X::member;
3101       // };
3102       if (DeclContext *DC = computeDeclContext(SS, false))
3103         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3104                                      D.getName().getKind() ==
3105                                          UnqualifiedIdKind::IK_TemplateId);
3106       else
3107         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3108           << Name << SS.getRange();
3109 
3110       SS.clear();
3111     }
3112 
3113     if (MSPropertyAttr) {
3114       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3115                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3116       if (!Member)
3117         return nullptr;
3118       isInstField = false;
3119     } else {
3120       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3121                                 BitWidth, InitStyle, AS);
3122       if (!Member)
3123         return nullptr;
3124     }
3125 
3126     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3127   } else {
3128     Member = HandleDeclarator(S, D, TemplateParameterLists);
3129     if (!Member)
3130       return nullptr;
3131 
3132     // Non-instance-fields can't have a bitfield.
3133     if (BitWidth) {
3134       if (Member->isInvalidDecl()) {
3135         // don't emit another diagnostic.
3136       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3137         // C++ 9.6p3: A bit-field shall not be a static member.
3138         // "static member 'A' cannot be a bit-field"
3139         Diag(Loc, diag::err_static_not_bitfield)
3140           << Name << BitWidth->getSourceRange();
3141       } else if (isa<TypedefDecl>(Member)) {
3142         // "typedef member 'x' cannot be a bit-field"
3143         Diag(Loc, diag::err_typedef_not_bitfield)
3144           << Name << BitWidth->getSourceRange();
3145       } else {
3146         // A function typedef ("typedef int f(); f a;").
3147         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3148         Diag(Loc, diag::err_not_integral_type_bitfield)
3149           << Name << cast<ValueDecl>(Member)->getType()
3150           << BitWidth->getSourceRange();
3151       }
3152 
3153       BitWidth = nullptr;
3154       Member->setInvalidDecl();
3155     }
3156 
3157     NamedDecl *NonTemplateMember = Member;
3158     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3159       NonTemplateMember = FunTmpl->getTemplatedDecl();
3160     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3161       NonTemplateMember = VarTmpl->getTemplatedDecl();
3162 
3163     Member->setAccess(AS);
3164 
3165     // If we have declared a member function template or static data member
3166     // template, set the access of the templated declaration as well.
3167     if (NonTemplateMember != Member)
3168       NonTemplateMember->setAccess(AS);
3169 
3170     // C++ [temp.deduct.guide]p3:
3171     //   A deduction guide [...] for a member class template [shall be
3172     //   declared] with the same access [as the template].
3173     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3174       auto *TD = DG->getDeducedTemplate();
3175       if (AS != TD->getAccess()) {
3176         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3177         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3178             << TD->getAccess();
3179         const AccessSpecDecl *LastAccessSpec = nullptr;
3180         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3181           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3182             LastAccessSpec = AccessSpec;
3183         }
3184         assert(LastAccessSpec && "differing access with no access specifier");
3185         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3186             << AS;
3187       }
3188     }
3189   }
3190 
3191   if (VS.isOverrideSpecified())
3192     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3193   if (VS.isFinalSpecified())
3194     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3195                                             VS.isFinalSpelledSealed()));
3196 
3197   if (VS.getLastLocation().isValid()) {
3198     // Update the end location of a method that has a virt-specifiers.
3199     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3200       MD->setRangeEnd(VS.getLastLocation());
3201   }
3202 
3203   CheckOverrideControl(Member);
3204 
3205   assert((Name || isInstField) && "No identifier for non-field ?");
3206 
3207   if (isInstField) {
3208     FieldDecl *FD = cast<FieldDecl>(Member);
3209     FieldCollector->Add(FD);
3210 
3211     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3212       // Remember all explicit private FieldDecls that have a name, no side
3213       // effects and are not part of a dependent type declaration.
3214       if (!FD->isImplicit() && FD->getDeclName() &&
3215           FD->getAccess() == AS_private &&
3216           !FD->hasAttr<UnusedAttr>() &&
3217           !FD->getParent()->isDependentContext() &&
3218           !InitializationHasSideEffects(*FD))
3219         UnusedPrivateFields.insert(FD);
3220     }
3221   }
3222 
3223   return Member;
3224 }
3225 
3226 namespace {
3227   class UninitializedFieldVisitor
3228       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3229     Sema &S;
3230     // List of Decls to generate a warning on.  Also remove Decls that become
3231     // initialized.
3232     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3233     // List of base classes of the record.  Classes are removed after their
3234     // initializers.
3235     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3236     // Vector of decls to be removed from the Decl set prior to visiting the
3237     // nodes.  These Decls may have been initialized in the prior initializer.
3238     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3239     // If non-null, add a note to the warning pointing back to the constructor.
3240     const CXXConstructorDecl *Constructor;
3241     // Variables to hold state when processing an initializer list.  When
3242     // InitList is true, special case initialization of FieldDecls matching
3243     // InitListFieldDecl.
3244     bool InitList;
3245     FieldDecl *InitListFieldDecl;
3246     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3247 
3248   public:
3249     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3250     UninitializedFieldVisitor(Sema &S,
3251                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3252                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3253       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3254         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3255 
3256     // Returns true if the use of ME is not an uninitialized use.
3257     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3258                                          bool CheckReferenceOnly) {
3259       llvm::SmallVector<FieldDecl*, 4> Fields;
3260       bool ReferenceField = false;
3261       while (ME) {
3262         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3263         if (!FD)
3264           return false;
3265         Fields.push_back(FD);
3266         if (FD->getType()->isReferenceType())
3267           ReferenceField = true;
3268         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3269       }
3270 
3271       // Binding a reference to an uninitialized field is not an
3272       // uninitialized use.
3273       if (CheckReferenceOnly && !ReferenceField)
3274         return true;
3275 
3276       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3277       // Discard the first field since it is the field decl that is being
3278       // initialized.
3279       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3280         UsedFieldIndex.push_back((*I)->getFieldIndex());
3281       }
3282 
3283       for (auto UsedIter = UsedFieldIndex.begin(),
3284                 UsedEnd = UsedFieldIndex.end(),
3285                 OrigIter = InitFieldIndex.begin(),
3286                 OrigEnd = InitFieldIndex.end();
3287            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3288         if (*UsedIter < *OrigIter)
3289           return true;
3290         if (*UsedIter > *OrigIter)
3291           break;
3292       }
3293 
3294       return false;
3295     }
3296 
3297     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3298                           bool AddressOf) {
3299       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3300         return;
3301 
3302       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3303       // or union.
3304       MemberExpr *FieldME = ME;
3305 
3306       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3307 
3308       Expr *Base = ME;
3309       while (MemberExpr *SubME =
3310                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3311 
3312         if (isa<VarDecl>(SubME->getMemberDecl()))
3313           return;
3314 
3315         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3316           if (!FD->isAnonymousStructOrUnion())
3317             FieldME = SubME;
3318 
3319         if (!FieldME->getType().isPODType(S.Context))
3320           AllPODFields = false;
3321 
3322         Base = SubME->getBase();
3323       }
3324 
3325       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3326         return;
3327 
3328       if (AddressOf && AllPODFields)
3329         return;
3330 
3331       ValueDecl* FoundVD = FieldME->getMemberDecl();
3332 
3333       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3334         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3335           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3336         }
3337 
3338         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3339           QualType T = BaseCast->getType();
3340           if (T->isPointerType() &&
3341               BaseClasses.count(T->getPointeeType())) {
3342             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3343                 << T->getPointeeType() << FoundVD;
3344           }
3345         }
3346       }
3347 
3348       if (!Decls.count(FoundVD))
3349         return;
3350 
3351       const bool IsReference = FoundVD->getType()->isReferenceType();
3352 
3353       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3354         // Special checking for initializer lists.
3355         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3356           return;
3357         }
3358       } else {
3359         // Prevent double warnings on use of unbounded references.
3360         if (CheckReferenceOnly && !IsReference)
3361           return;
3362       }
3363 
3364       unsigned diag = IsReference
3365           ? diag::warn_reference_field_is_uninit
3366           : diag::warn_field_is_uninit;
3367       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3368       if (Constructor)
3369         S.Diag(Constructor->getLocation(),
3370                diag::note_uninit_in_this_constructor)
3371           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3372 
3373     }
3374 
3375     void HandleValue(Expr *E, bool AddressOf) {
3376       E = E->IgnoreParens();
3377 
3378       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3379         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3380                          AddressOf /*AddressOf*/);
3381         return;
3382       }
3383 
3384       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3385         Visit(CO->getCond());
3386         HandleValue(CO->getTrueExpr(), AddressOf);
3387         HandleValue(CO->getFalseExpr(), AddressOf);
3388         return;
3389       }
3390 
3391       if (BinaryConditionalOperator *BCO =
3392               dyn_cast<BinaryConditionalOperator>(E)) {
3393         Visit(BCO->getCond());
3394         HandleValue(BCO->getFalseExpr(), AddressOf);
3395         return;
3396       }
3397 
3398       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3399         HandleValue(OVE->getSourceExpr(), AddressOf);
3400         return;
3401       }
3402 
3403       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3404         switch (BO->getOpcode()) {
3405         default:
3406           break;
3407         case(BO_PtrMemD):
3408         case(BO_PtrMemI):
3409           HandleValue(BO->getLHS(), AddressOf);
3410           Visit(BO->getRHS());
3411           return;
3412         case(BO_Comma):
3413           Visit(BO->getLHS());
3414           HandleValue(BO->getRHS(), AddressOf);
3415           return;
3416         }
3417       }
3418 
3419       Visit(E);
3420     }
3421 
3422     void CheckInitListExpr(InitListExpr *ILE) {
3423       InitFieldIndex.push_back(0);
3424       for (auto Child : ILE->children()) {
3425         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3426           CheckInitListExpr(SubList);
3427         } else {
3428           Visit(Child);
3429         }
3430         ++InitFieldIndex.back();
3431       }
3432       InitFieldIndex.pop_back();
3433     }
3434 
3435     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3436                           FieldDecl *Field, const Type *BaseClass) {
3437       // Remove Decls that may have been initialized in the previous
3438       // initializer.
3439       for (ValueDecl* VD : DeclsToRemove)
3440         Decls.erase(VD);
3441       DeclsToRemove.clear();
3442 
3443       Constructor = FieldConstructor;
3444       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3445 
3446       if (ILE && Field) {
3447         InitList = true;
3448         InitListFieldDecl = Field;
3449         InitFieldIndex.clear();
3450         CheckInitListExpr(ILE);
3451       } else {
3452         InitList = false;
3453         Visit(E);
3454       }
3455 
3456       if (Field)
3457         Decls.erase(Field);
3458       if (BaseClass)
3459         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3460     }
3461 
3462     void VisitMemberExpr(MemberExpr *ME) {
3463       // All uses of unbounded reference fields will warn.
3464       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3465     }
3466 
3467     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3468       if (E->getCastKind() == CK_LValueToRValue) {
3469         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3470         return;
3471       }
3472 
3473       Inherited::VisitImplicitCastExpr(E);
3474     }
3475 
3476     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3477       if (E->getConstructor()->isCopyConstructor()) {
3478         Expr *ArgExpr = E->getArg(0);
3479         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3480           if (ILE->getNumInits() == 1)
3481             ArgExpr = ILE->getInit(0);
3482         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3483           if (ICE->getCastKind() == CK_NoOp)
3484             ArgExpr = ICE->getSubExpr();
3485         HandleValue(ArgExpr, false /*AddressOf*/);
3486         return;
3487       }
3488       Inherited::VisitCXXConstructExpr(E);
3489     }
3490 
3491     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3492       Expr *Callee = E->getCallee();
3493       if (isa<MemberExpr>(Callee)) {
3494         HandleValue(Callee, false /*AddressOf*/);
3495         for (auto Arg : E->arguments())
3496           Visit(Arg);
3497         return;
3498       }
3499 
3500       Inherited::VisitCXXMemberCallExpr(E);
3501     }
3502 
3503     void VisitCallExpr(CallExpr *E) {
3504       // Treat std::move as a use.
3505       if (E->isCallToStdMove()) {
3506         HandleValue(E->getArg(0), /*AddressOf=*/false);
3507         return;
3508       }
3509 
3510       Inherited::VisitCallExpr(E);
3511     }
3512 
3513     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3514       Expr *Callee = E->getCallee();
3515 
3516       if (isa<UnresolvedLookupExpr>(Callee))
3517         return Inherited::VisitCXXOperatorCallExpr(E);
3518 
3519       Visit(Callee);
3520       for (auto Arg : E->arguments())
3521         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3522     }
3523 
3524     void VisitBinaryOperator(BinaryOperator *E) {
3525       // If a field assignment is detected, remove the field from the
3526       // uninitiailized field set.
3527       if (E->getOpcode() == BO_Assign)
3528         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3529           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3530             if (!FD->getType()->isReferenceType())
3531               DeclsToRemove.push_back(FD);
3532 
3533       if (E->isCompoundAssignmentOp()) {
3534         HandleValue(E->getLHS(), false /*AddressOf*/);
3535         Visit(E->getRHS());
3536         return;
3537       }
3538 
3539       Inherited::VisitBinaryOperator(E);
3540     }
3541 
3542     void VisitUnaryOperator(UnaryOperator *E) {
3543       if (E->isIncrementDecrementOp()) {
3544         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3545         return;
3546       }
3547       if (E->getOpcode() == UO_AddrOf) {
3548         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3549           HandleValue(ME->getBase(), true /*AddressOf*/);
3550           return;
3551         }
3552       }
3553 
3554       Inherited::VisitUnaryOperator(E);
3555     }
3556   };
3557 
3558   // Diagnose value-uses of fields to initialize themselves, e.g.
3559   //   foo(foo)
3560   // where foo is not also a parameter to the constructor.
3561   // Also diagnose across field uninitialized use such as
3562   //   x(y), y(x)
3563   // TODO: implement -Wuninitialized and fold this into that framework.
3564   static void DiagnoseUninitializedFields(
3565       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3566 
3567     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3568                                            Constructor->getLocation())) {
3569       return;
3570     }
3571 
3572     if (Constructor->isInvalidDecl())
3573       return;
3574 
3575     const CXXRecordDecl *RD = Constructor->getParent();
3576 
3577     if (RD->getDescribedClassTemplate())
3578       return;
3579 
3580     // Holds fields that are uninitialized.
3581     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3582 
3583     // At the beginning, all fields are uninitialized.
3584     for (auto *I : RD->decls()) {
3585       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3586         UninitializedFields.insert(FD);
3587       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3588         UninitializedFields.insert(IFD->getAnonField());
3589       }
3590     }
3591 
3592     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3593     for (auto I : RD->bases())
3594       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3595 
3596     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3597       return;
3598 
3599     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3600                                                    UninitializedFields,
3601                                                    UninitializedBaseClasses);
3602 
3603     for (const auto *FieldInit : Constructor->inits()) {
3604       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3605         break;
3606 
3607       Expr *InitExpr = FieldInit->getInit();
3608       if (!InitExpr)
3609         continue;
3610 
3611       if (CXXDefaultInitExpr *Default =
3612               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3613         InitExpr = Default->getExpr();
3614         if (!InitExpr)
3615           continue;
3616         // In class initializers will point to the constructor.
3617         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3618                                               FieldInit->getAnyMember(),
3619                                               FieldInit->getBaseClass());
3620       } else {
3621         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3622                                               FieldInit->getAnyMember(),
3623                                               FieldInit->getBaseClass());
3624       }
3625     }
3626   }
3627 } // namespace
3628 
3629 /// Enter a new C++ default initializer scope. After calling this, the
3630 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3631 /// parsing or instantiating the initializer failed.
3632 void Sema::ActOnStartCXXInClassMemberInitializer() {
3633   // Create a synthetic function scope to represent the call to the constructor
3634   // that notionally surrounds a use of this initializer.
3635   PushFunctionScope();
3636 }
3637 
3638 /// This is invoked after parsing an in-class initializer for a
3639 /// non-static C++ class member, and after instantiating an in-class initializer
3640 /// in a class template. Such actions are deferred until the class is complete.
3641 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3642                                                   SourceLocation InitLoc,
3643                                                   Expr *InitExpr) {
3644   // Pop the notional constructor scope we created earlier.
3645   PopFunctionScopeInfo(nullptr, D);
3646 
3647   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3648   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3649          "must set init style when field is created");
3650 
3651   if (!InitExpr) {
3652     D->setInvalidDecl();
3653     if (FD)
3654       FD->removeInClassInitializer();
3655     return;
3656   }
3657 
3658   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3659     FD->setInvalidDecl();
3660     FD->removeInClassInitializer();
3661     return;
3662   }
3663 
3664   ExprResult Init = InitExpr;
3665   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3666     InitializedEntity Entity =
3667         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3668     InitializationKind Kind =
3669         FD->getInClassInitStyle() == ICIS_ListInit
3670             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3671                                                    InitExpr->getBeginLoc(),
3672                                                    InitExpr->getEndLoc())
3673             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3674     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3675     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3676     if (Init.isInvalid()) {
3677       FD->setInvalidDecl();
3678       return;
3679     }
3680   }
3681 
3682   // C++11 [class.base.init]p7:
3683   //   The initialization of each base and member constitutes a
3684   //   full-expression.
3685   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3686   if (Init.isInvalid()) {
3687     FD->setInvalidDecl();
3688     return;
3689   }
3690 
3691   InitExpr = Init.get();
3692 
3693   FD->setInClassInitializer(InitExpr);
3694 }
3695 
3696 /// Find the direct and/or virtual base specifiers that
3697 /// correspond to the given base type, for use in base initialization
3698 /// within a constructor.
3699 static bool FindBaseInitializer(Sema &SemaRef,
3700                                 CXXRecordDecl *ClassDecl,
3701                                 QualType BaseType,
3702                                 const CXXBaseSpecifier *&DirectBaseSpec,
3703                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3704   // First, check for a direct base class.
3705   DirectBaseSpec = nullptr;
3706   for (const auto &Base : ClassDecl->bases()) {
3707     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3708       // We found a direct base of this type. That's what we're
3709       // initializing.
3710       DirectBaseSpec = &Base;
3711       break;
3712     }
3713   }
3714 
3715   // Check for a virtual base class.
3716   // FIXME: We might be able to short-circuit this if we know in advance that
3717   // there are no virtual bases.
3718   VirtualBaseSpec = nullptr;
3719   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3720     // We haven't found a base yet; search the class hierarchy for a
3721     // virtual base class.
3722     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3723                        /*DetectVirtual=*/false);
3724     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3725                               SemaRef.Context.getTypeDeclType(ClassDecl),
3726                               BaseType, Paths)) {
3727       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3728            Path != Paths.end(); ++Path) {
3729         if (Path->back().Base->isVirtual()) {
3730           VirtualBaseSpec = Path->back().Base;
3731           break;
3732         }
3733       }
3734     }
3735   }
3736 
3737   return DirectBaseSpec || VirtualBaseSpec;
3738 }
3739 
3740 /// Handle a C++ member initializer using braced-init-list syntax.
3741 MemInitResult
3742 Sema::ActOnMemInitializer(Decl *ConstructorD,
3743                           Scope *S,
3744                           CXXScopeSpec &SS,
3745                           IdentifierInfo *MemberOrBase,
3746                           ParsedType TemplateTypeTy,
3747                           const DeclSpec &DS,
3748                           SourceLocation IdLoc,
3749                           Expr *InitList,
3750                           SourceLocation EllipsisLoc) {
3751   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3752                              DS, IdLoc, InitList,
3753                              EllipsisLoc);
3754 }
3755 
3756 /// Handle a C++ member initializer using parentheses syntax.
3757 MemInitResult
3758 Sema::ActOnMemInitializer(Decl *ConstructorD,
3759                           Scope *S,
3760                           CXXScopeSpec &SS,
3761                           IdentifierInfo *MemberOrBase,
3762                           ParsedType TemplateTypeTy,
3763                           const DeclSpec &DS,
3764                           SourceLocation IdLoc,
3765                           SourceLocation LParenLoc,
3766                           ArrayRef<Expr *> Args,
3767                           SourceLocation RParenLoc,
3768                           SourceLocation EllipsisLoc) {
3769   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3770   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3771                              DS, IdLoc, List, EllipsisLoc);
3772 }
3773 
3774 namespace {
3775 
3776 // Callback to only accept typo corrections that can be a valid C++ member
3777 // intializer: either a non-static field member or a base class.
3778 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3779 public:
3780   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3781       : ClassDecl(ClassDecl) {}
3782 
3783   bool ValidateCandidate(const TypoCorrection &candidate) override {
3784     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3785       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3786         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3787       return isa<TypeDecl>(ND);
3788     }
3789     return false;
3790   }
3791 
3792 private:
3793   CXXRecordDecl *ClassDecl;
3794 };
3795 
3796 }
3797 
3798 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3799                                              CXXScopeSpec &SS,
3800                                              ParsedType TemplateTypeTy,
3801                                              IdentifierInfo *MemberOrBase) {
3802   if (SS.getScopeRep() || TemplateTypeTy)
3803     return nullptr;
3804   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3805   if (Result.empty())
3806     return nullptr;
3807   ValueDecl *Member;
3808   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3809       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3810     return Member;
3811   return nullptr;
3812 }
3813 
3814 /// Handle a C++ member initializer.
3815 MemInitResult
3816 Sema::BuildMemInitializer(Decl *ConstructorD,
3817                           Scope *S,
3818                           CXXScopeSpec &SS,
3819                           IdentifierInfo *MemberOrBase,
3820                           ParsedType TemplateTypeTy,
3821                           const DeclSpec &DS,
3822                           SourceLocation IdLoc,
3823                           Expr *Init,
3824                           SourceLocation EllipsisLoc) {
3825   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3826   if (!Res.isUsable())
3827     return true;
3828   Init = Res.get();
3829 
3830   if (!ConstructorD)
3831     return true;
3832 
3833   AdjustDeclIfTemplate(ConstructorD);
3834 
3835   CXXConstructorDecl *Constructor
3836     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3837   if (!Constructor) {
3838     // The user wrote a constructor initializer on a function that is
3839     // not a C++ constructor. Ignore the error for now, because we may
3840     // have more member initializers coming; we'll diagnose it just
3841     // once in ActOnMemInitializers.
3842     return true;
3843   }
3844 
3845   CXXRecordDecl *ClassDecl = Constructor->getParent();
3846 
3847   // C++ [class.base.init]p2:
3848   //   Names in a mem-initializer-id are looked up in the scope of the
3849   //   constructor's class and, if not found in that scope, are looked
3850   //   up in the scope containing the constructor's definition.
3851   //   [Note: if the constructor's class contains a member with the
3852   //   same name as a direct or virtual base class of the class, a
3853   //   mem-initializer-id naming the member or base class and composed
3854   //   of a single identifier refers to the class member. A
3855   //   mem-initializer-id for the hidden base class may be specified
3856   //   using a qualified name. ]
3857 
3858   // Look for a member, first.
3859   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3860           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3861     if (EllipsisLoc.isValid())
3862       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3863           << MemberOrBase
3864           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3865 
3866     return BuildMemberInitializer(Member, Init, IdLoc);
3867   }
3868   // It didn't name a member, so see if it names a class.
3869   QualType BaseType;
3870   TypeSourceInfo *TInfo = nullptr;
3871 
3872   if (TemplateTypeTy) {
3873     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3874   } else if (DS.getTypeSpecType() == TST_decltype) {
3875     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3876   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3877     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3878     return true;
3879   } else {
3880     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3881     LookupParsedName(R, S, &SS);
3882 
3883     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3884     if (!TyD) {
3885       if (R.isAmbiguous()) return true;
3886 
3887       // We don't want access-control diagnostics here.
3888       R.suppressDiagnostics();
3889 
3890       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3891         bool NotUnknownSpecialization = false;
3892         DeclContext *DC = computeDeclContext(SS, false);
3893         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3894           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3895 
3896         if (!NotUnknownSpecialization) {
3897           // When the scope specifier can refer to a member of an unknown
3898           // specialization, we take it as a type name.
3899           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3900                                        SS.getWithLocInContext(Context),
3901                                        *MemberOrBase, IdLoc);
3902           if (BaseType.isNull())
3903             return true;
3904 
3905           TInfo = Context.CreateTypeSourceInfo(BaseType);
3906           DependentNameTypeLoc TL =
3907               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3908           if (!TL.isNull()) {
3909             TL.setNameLoc(IdLoc);
3910             TL.setElaboratedKeywordLoc(SourceLocation());
3911             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3912           }
3913 
3914           R.clear();
3915           R.setLookupName(MemberOrBase);
3916         }
3917       }
3918 
3919       // If no results were found, try to correct typos.
3920       TypoCorrection Corr;
3921       if (R.empty() && BaseType.isNull() &&
3922           (Corr = CorrectTypo(
3923                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3924                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3925                CTK_ErrorRecovery, ClassDecl))) {
3926         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3927           // We have found a non-static data member with a similar
3928           // name to what was typed; complain and initialize that
3929           // member.
3930           diagnoseTypo(Corr,
3931                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3932                          << MemberOrBase << true);
3933           return BuildMemberInitializer(Member, Init, IdLoc);
3934         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3935           const CXXBaseSpecifier *DirectBaseSpec;
3936           const CXXBaseSpecifier *VirtualBaseSpec;
3937           if (FindBaseInitializer(*this, ClassDecl,
3938                                   Context.getTypeDeclType(Type),
3939                                   DirectBaseSpec, VirtualBaseSpec)) {
3940             // We have found a direct or virtual base class with a
3941             // similar name to what was typed; complain and initialize
3942             // that base class.
3943             diagnoseTypo(Corr,
3944                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3945                            << MemberOrBase << false,
3946                          PDiag() /*Suppress note, we provide our own.*/);
3947 
3948             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3949                                                               : VirtualBaseSpec;
3950             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3951                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3952 
3953             TyD = Type;
3954           }
3955         }
3956       }
3957 
3958       if (!TyD && BaseType.isNull()) {
3959         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3960           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3961         return true;
3962       }
3963     }
3964 
3965     if (BaseType.isNull()) {
3966       BaseType = Context.getTypeDeclType(TyD);
3967       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3968       if (SS.isSet()) {
3969         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3970                                              BaseType);
3971         TInfo = Context.CreateTypeSourceInfo(BaseType);
3972         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3973         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3974         TL.setElaboratedKeywordLoc(SourceLocation());
3975         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3976       }
3977     }
3978   }
3979 
3980   if (!TInfo)
3981     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3982 
3983   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3984 }
3985 
3986 MemInitResult
3987 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3988                              SourceLocation IdLoc) {
3989   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3990   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3991   assert((DirectMember || IndirectMember) &&
3992          "Member must be a FieldDecl or IndirectFieldDecl");
3993 
3994   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3995     return true;
3996 
3997   if (Member->isInvalidDecl())
3998     return true;
3999 
4000   MultiExprArg Args;
4001   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4002     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4003   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4004     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4005   } else {
4006     // Template instantiation doesn't reconstruct ParenListExprs for us.
4007     Args = Init;
4008   }
4009 
4010   SourceRange InitRange = Init->getSourceRange();
4011 
4012   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4013     // Can't check initialization for a member of dependent type or when
4014     // any of the arguments are type-dependent expressions.
4015     DiscardCleanupsInEvaluationContext();
4016   } else {
4017     bool InitList = false;
4018     if (isa<InitListExpr>(Init)) {
4019       InitList = true;
4020       Args = Init;
4021     }
4022 
4023     // Initialize the member.
4024     InitializedEntity MemberEntity =
4025       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4026                    : InitializedEntity::InitializeMember(IndirectMember,
4027                                                          nullptr);
4028     InitializationKind Kind =
4029         InitList ? InitializationKind::CreateDirectList(
4030                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4031                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4032                                                     InitRange.getEnd());
4033 
4034     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4035     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4036                                             nullptr);
4037     if (MemberInit.isInvalid())
4038       return true;
4039 
4040     // C++11 [class.base.init]p7:
4041     //   The initialization of each base and member constitutes a
4042     //   full-expression.
4043     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4044     if (MemberInit.isInvalid())
4045       return true;
4046 
4047     Init = MemberInit.get();
4048   }
4049 
4050   if (DirectMember) {
4051     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4052                                             InitRange.getBegin(), Init,
4053                                             InitRange.getEnd());
4054   } else {
4055     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4056                                             InitRange.getBegin(), Init,
4057                                             InitRange.getEnd());
4058   }
4059 }
4060 
4061 MemInitResult
4062 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4063                                  CXXRecordDecl *ClassDecl) {
4064   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4065   if (!LangOpts.CPlusPlus11)
4066     return Diag(NameLoc, diag::err_delegating_ctor)
4067       << TInfo->getTypeLoc().getLocalSourceRange();
4068   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4069 
4070   bool InitList = true;
4071   MultiExprArg Args = Init;
4072   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4073     InitList = false;
4074     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4075   }
4076 
4077   SourceRange InitRange = Init->getSourceRange();
4078   // Initialize the object.
4079   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4080                                      QualType(ClassDecl->getTypeForDecl(), 0));
4081   InitializationKind Kind =
4082       InitList ? InitializationKind::CreateDirectList(
4083                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4084                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4085                                                   InitRange.getEnd());
4086   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4087   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4088                                               Args, nullptr);
4089   if (DelegationInit.isInvalid())
4090     return true;
4091 
4092   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4093          "Delegating constructor with no target?");
4094 
4095   // C++11 [class.base.init]p7:
4096   //   The initialization of each base and member constitutes a
4097   //   full-expression.
4098   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4099                                        InitRange.getBegin());
4100   if (DelegationInit.isInvalid())
4101     return true;
4102 
4103   // If we are in a dependent context, template instantiation will
4104   // perform this type-checking again. Just save the arguments that we
4105   // received in a ParenListExpr.
4106   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4107   // of the information that we have about the base
4108   // initializer. However, deconstructing the ASTs is a dicey process,
4109   // and this approach is far more likely to get the corner cases right.
4110   if (CurContext->isDependentContext())
4111     DelegationInit = Init;
4112 
4113   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4114                                           DelegationInit.getAs<Expr>(),
4115                                           InitRange.getEnd());
4116 }
4117 
4118 MemInitResult
4119 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4120                            Expr *Init, CXXRecordDecl *ClassDecl,
4121                            SourceLocation EllipsisLoc) {
4122   SourceLocation BaseLoc
4123     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4124 
4125   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4126     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4127              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4128 
4129   // C++ [class.base.init]p2:
4130   //   [...] Unless the mem-initializer-id names a nonstatic data
4131   //   member of the constructor's class or a direct or virtual base
4132   //   of that class, the mem-initializer is ill-formed. A
4133   //   mem-initializer-list can initialize a base class using any
4134   //   name that denotes that base class type.
4135   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4136 
4137   SourceRange InitRange = Init->getSourceRange();
4138   if (EllipsisLoc.isValid()) {
4139     // This is a pack expansion.
4140     if (!BaseType->containsUnexpandedParameterPack())  {
4141       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4142         << SourceRange(BaseLoc, InitRange.getEnd());
4143 
4144       EllipsisLoc = SourceLocation();
4145     }
4146   } else {
4147     // Check for any unexpanded parameter packs.
4148     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4149       return true;
4150 
4151     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4152       return true;
4153   }
4154 
4155   // Check for direct and virtual base classes.
4156   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4157   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4158   if (!Dependent) {
4159     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4160                                        BaseType))
4161       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4162 
4163     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4164                         VirtualBaseSpec);
4165 
4166     // C++ [base.class.init]p2:
4167     // Unless the mem-initializer-id names a nonstatic data member of the
4168     // constructor's class or a direct or virtual base of that class, the
4169     // mem-initializer is ill-formed.
4170     if (!DirectBaseSpec && !VirtualBaseSpec) {
4171       // If the class has any dependent bases, then it's possible that
4172       // one of those types will resolve to the same type as
4173       // BaseType. Therefore, just treat this as a dependent base
4174       // class initialization.  FIXME: Should we try to check the
4175       // initialization anyway? It seems odd.
4176       if (ClassDecl->hasAnyDependentBases())
4177         Dependent = true;
4178       else
4179         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4180           << BaseType << Context.getTypeDeclType(ClassDecl)
4181           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4182     }
4183   }
4184 
4185   if (Dependent) {
4186     DiscardCleanupsInEvaluationContext();
4187 
4188     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4189                                             /*IsVirtual=*/false,
4190                                             InitRange.getBegin(), Init,
4191                                             InitRange.getEnd(), EllipsisLoc);
4192   }
4193 
4194   // C++ [base.class.init]p2:
4195   //   If a mem-initializer-id is ambiguous because it designates both
4196   //   a direct non-virtual base class and an inherited virtual base
4197   //   class, the mem-initializer is ill-formed.
4198   if (DirectBaseSpec && VirtualBaseSpec)
4199     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4200       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4201 
4202   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4203   if (!BaseSpec)
4204     BaseSpec = VirtualBaseSpec;
4205 
4206   // Initialize the base.
4207   bool InitList = true;
4208   MultiExprArg Args = Init;
4209   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4210     InitList = false;
4211     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4212   }
4213 
4214   InitializedEntity BaseEntity =
4215     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4216   InitializationKind Kind =
4217       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4218                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4219                                                   InitRange.getEnd());
4220   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4221   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4222   if (BaseInit.isInvalid())
4223     return true;
4224 
4225   // C++11 [class.base.init]p7:
4226   //   The initialization of each base and member constitutes a
4227   //   full-expression.
4228   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4229   if (BaseInit.isInvalid())
4230     return true;
4231 
4232   // If we are in a dependent context, template instantiation will
4233   // perform this type-checking again. Just save the arguments that we
4234   // received in a ParenListExpr.
4235   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4236   // of the information that we have about the base
4237   // initializer. However, deconstructing the ASTs is a dicey process,
4238   // and this approach is far more likely to get the corner cases right.
4239   if (CurContext->isDependentContext())
4240     BaseInit = Init;
4241 
4242   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4243                                           BaseSpec->isVirtual(),
4244                                           InitRange.getBegin(),
4245                                           BaseInit.getAs<Expr>(),
4246                                           InitRange.getEnd(), EllipsisLoc);
4247 }
4248 
4249 // Create a static_cast\<T&&>(expr).
4250 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4251   if (T.isNull()) T = E->getType();
4252   QualType TargetType = SemaRef.BuildReferenceType(
4253       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4254   SourceLocation ExprLoc = E->getBeginLoc();
4255   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4256       TargetType, ExprLoc);
4257 
4258   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4259                                    SourceRange(ExprLoc, ExprLoc),
4260                                    E->getSourceRange()).get();
4261 }
4262 
4263 /// ImplicitInitializerKind - How an implicit base or member initializer should
4264 /// initialize its base or member.
4265 enum ImplicitInitializerKind {
4266   IIK_Default,
4267   IIK_Copy,
4268   IIK_Move,
4269   IIK_Inherit
4270 };
4271 
4272 static bool
4273 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4274                              ImplicitInitializerKind ImplicitInitKind,
4275                              CXXBaseSpecifier *BaseSpec,
4276                              bool IsInheritedVirtualBase,
4277                              CXXCtorInitializer *&CXXBaseInit) {
4278   InitializedEntity InitEntity
4279     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4280                                         IsInheritedVirtualBase);
4281 
4282   ExprResult BaseInit;
4283 
4284   switch (ImplicitInitKind) {
4285   case IIK_Inherit:
4286   case IIK_Default: {
4287     InitializationKind InitKind
4288       = InitializationKind::CreateDefault(Constructor->getLocation());
4289     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4290     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4291     break;
4292   }
4293 
4294   case IIK_Move:
4295   case IIK_Copy: {
4296     bool Moving = ImplicitInitKind == IIK_Move;
4297     ParmVarDecl *Param = Constructor->getParamDecl(0);
4298     QualType ParamType = Param->getType().getNonReferenceType();
4299 
4300     Expr *CopyCtorArg =
4301       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4302                           SourceLocation(), Param, false,
4303                           Constructor->getLocation(), ParamType,
4304                           VK_LValue, nullptr);
4305 
4306     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4307 
4308     // Cast to the base class to avoid ambiguities.
4309     QualType ArgTy =
4310       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4311                                        ParamType.getQualifiers());
4312 
4313     if (Moving) {
4314       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4315     }
4316 
4317     CXXCastPath BasePath;
4318     BasePath.push_back(BaseSpec);
4319     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4320                                             CK_UncheckedDerivedToBase,
4321                                             Moving ? VK_XValue : VK_LValue,
4322                                             &BasePath).get();
4323 
4324     InitializationKind InitKind
4325       = InitializationKind::CreateDirect(Constructor->getLocation(),
4326                                          SourceLocation(), SourceLocation());
4327     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4328     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4329     break;
4330   }
4331   }
4332 
4333   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4334   if (BaseInit.isInvalid())
4335     return true;
4336 
4337   CXXBaseInit =
4338     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4339                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4340                                                         SourceLocation()),
4341                                              BaseSpec->isVirtual(),
4342                                              SourceLocation(),
4343                                              BaseInit.getAs<Expr>(),
4344                                              SourceLocation(),
4345                                              SourceLocation());
4346 
4347   return false;
4348 }
4349 
4350 static bool RefersToRValueRef(Expr *MemRef) {
4351   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4352   return Referenced->getType()->isRValueReferenceType();
4353 }
4354 
4355 static bool
4356 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4357                                ImplicitInitializerKind ImplicitInitKind,
4358                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4359                                CXXCtorInitializer *&CXXMemberInit) {
4360   if (Field->isInvalidDecl())
4361     return true;
4362 
4363   SourceLocation Loc = Constructor->getLocation();
4364 
4365   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4366     bool Moving = ImplicitInitKind == IIK_Move;
4367     ParmVarDecl *Param = Constructor->getParamDecl(0);
4368     QualType ParamType = Param->getType().getNonReferenceType();
4369 
4370     // Suppress copying zero-width bitfields.
4371     if (Field->isZeroLengthBitField(SemaRef.Context))
4372       return false;
4373 
4374     Expr *MemberExprBase =
4375       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4376                           SourceLocation(), Param, false,
4377                           Loc, ParamType, VK_LValue, nullptr);
4378 
4379     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4380 
4381     if (Moving) {
4382       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4383     }
4384 
4385     // Build a reference to this field within the parameter.
4386     CXXScopeSpec SS;
4387     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4388                               Sema::LookupMemberName);
4389     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4390                                   : cast<ValueDecl>(Field), AS_public);
4391     MemberLookup.resolveKind();
4392     ExprResult CtorArg
4393       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4394                                          ParamType, Loc,
4395                                          /*IsArrow=*/false,
4396                                          SS,
4397                                          /*TemplateKWLoc=*/SourceLocation(),
4398                                          /*FirstQualifierInScope=*/nullptr,
4399                                          MemberLookup,
4400                                          /*TemplateArgs=*/nullptr,
4401                                          /*S*/nullptr);
4402     if (CtorArg.isInvalid())
4403       return true;
4404 
4405     // C++11 [class.copy]p15:
4406     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4407     //     with static_cast<T&&>(x.m);
4408     if (RefersToRValueRef(CtorArg.get())) {
4409       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4410     }
4411 
4412     InitializedEntity Entity =
4413         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4414                                                        /*Implicit*/ true)
4415                  : InitializedEntity::InitializeMember(Field, nullptr,
4416                                                        /*Implicit*/ true);
4417 
4418     // Direct-initialize to use the copy constructor.
4419     InitializationKind InitKind =
4420       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4421 
4422     Expr *CtorArgE = CtorArg.getAs<Expr>();
4423     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4424     ExprResult MemberInit =
4425         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4426     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4427     if (MemberInit.isInvalid())
4428       return true;
4429 
4430     if (Indirect)
4431       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4432           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4433     else
4434       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4435           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4436     return false;
4437   }
4438 
4439   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4440          "Unhandled implicit init kind!");
4441 
4442   QualType FieldBaseElementType =
4443     SemaRef.Context.getBaseElementType(Field->getType());
4444 
4445   if (FieldBaseElementType->isRecordType()) {
4446     InitializedEntity InitEntity =
4447         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4448                                                        /*Implicit*/ true)
4449                  : InitializedEntity::InitializeMember(Field, nullptr,
4450                                                        /*Implicit*/ true);
4451     InitializationKind InitKind =
4452       InitializationKind::CreateDefault(Loc);
4453 
4454     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4455     ExprResult MemberInit =
4456       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4457 
4458     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4459     if (MemberInit.isInvalid())
4460       return true;
4461 
4462     if (Indirect)
4463       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4464                                                                Indirect, Loc,
4465                                                                Loc,
4466                                                                MemberInit.get(),
4467                                                                Loc);
4468     else
4469       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4470                                                                Field, Loc, Loc,
4471                                                                MemberInit.get(),
4472                                                                Loc);
4473     return false;
4474   }
4475 
4476   if (!Field->getParent()->isUnion()) {
4477     if (FieldBaseElementType->isReferenceType()) {
4478       SemaRef.Diag(Constructor->getLocation(),
4479                    diag::err_uninitialized_member_in_ctor)
4480       << (int)Constructor->isImplicit()
4481       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4482       << 0 << Field->getDeclName();
4483       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4484       return true;
4485     }
4486 
4487     if (FieldBaseElementType.isConstQualified()) {
4488       SemaRef.Diag(Constructor->getLocation(),
4489                    diag::err_uninitialized_member_in_ctor)
4490       << (int)Constructor->isImplicit()
4491       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4492       << 1 << Field->getDeclName();
4493       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4494       return true;
4495     }
4496   }
4497 
4498   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4499     // ARC and Weak:
4500     //   Default-initialize Objective-C pointers to NULL.
4501     CXXMemberInit
4502       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4503                                                  Loc, Loc,
4504                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4505                                                  Loc);
4506     return false;
4507   }
4508 
4509   // Nothing to initialize.
4510   CXXMemberInit = nullptr;
4511   return false;
4512 }
4513 
4514 namespace {
4515 struct BaseAndFieldInfo {
4516   Sema &S;
4517   CXXConstructorDecl *Ctor;
4518   bool AnyErrorsInInits;
4519   ImplicitInitializerKind IIK;
4520   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4521   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4522   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4523 
4524   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4525     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4526     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4527     if (Ctor->getInheritedConstructor())
4528       IIK = IIK_Inherit;
4529     else if (Generated && Ctor->isCopyConstructor())
4530       IIK = IIK_Copy;
4531     else if (Generated && Ctor->isMoveConstructor())
4532       IIK = IIK_Move;
4533     else
4534       IIK = IIK_Default;
4535   }
4536 
4537   bool isImplicitCopyOrMove() const {
4538     switch (IIK) {
4539     case IIK_Copy:
4540     case IIK_Move:
4541       return true;
4542 
4543     case IIK_Default:
4544     case IIK_Inherit:
4545       return false;
4546     }
4547 
4548     llvm_unreachable("Invalid ImplicitInitializerKind!");
4549   }
4550 
4551   bool addFieldInitializer(CXXCtorInitializer *Init) {
4552     AllToInit.push_back(Init);
4553 
4554     // Check whether this initializer makes the field "used".
4555     if (Init->getInit()->HasSideEffects(S.Context))
4556       S.UnusedPrivateFields.remove(Init->getAnyMember());
4557 
4558     return false;
4559   }
4560 
4561   bool isInactiveUnionMember(FieldDecl *Field) {
4562     RecordDecl *Record = Field->getParent();
4563     if (!Record->isUnion())
4564       return false;
4565 
4566     if (FieldDecl *Active =
4567             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4568       return Active != Field->getCanonicalDecl();
4569 
4570     // In an implicit copy or move constructor, ignore any in-class initializer.
4571     if (isImplicitCopyOrMove())
4572       return true;
4573 
4574     // If there's no explicit initialization, the field is active only if it
4575     // has an in-class initializer...
4576     if (Field->hasInClassInitializer())
4577       return false;
4578     // ... or it's an anonymous struct or union whose class has an in-class
4579     // initializer.
4580     if (!Field->isAnonymousStructOrUnion())
4581       return true;
4582     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4583     return !FieldRD->hasInClassInitializer();
4584   }
4585 
4586   /// Determine whether the given field is, or is within, a union member
4587   /// that is inactive (because there was an initializer given for a different
4588   /// member of the union, or because the union was not initialized at all).
4589   bool isWithinInactiveUnionMember(FieldDecl *Field,
4590                                    IndirectFieldDecl *Indirect) {
4591     if (!Indirect)
4592       return isInactiveUnionMember(Field);
4593 
4594     for (auto *C : Indirect->chain()) {
4595       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4596       if (Field && isInactiveUnionMember(Field))
4597         return true;
4598     }
4599     return false;
4600   }
4601 };
4602 }
4603 
4604 /// Determine whether the given type is an incomplete or zero-lenfgth
4605 /// array type.
4606 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4607   if (T->isIncompleteArrayType())
4608     return true;
4609 
4610   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4611     if (!ArrayT->getSize())
4612       return true;
4613 
4614     T = ArrayT->getElementType();
4615   }
4616 
4617   return false;
4618 }
4619 
4620 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4621                                     FieldDecl *Field,
4622                                     IndirectFieldDecl *Indirect = nullptr) {
4623   if (Field->isInvalidDecl())
4624     return false;
4625 
4626   // Overwhelmingly common case: we have a direct initializer for this field.
4627   if (CXXCtorInitializer *Init =
4628           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4629     return Info.addFieldInitializer(Init);
4630 
4631   // C++11 [class.base.init]p8:
4632   //   if the entity is a non-static data member that has a
4633   //   brace-or-equal-initializer and either
4634   //   -- the constructor's class is a union and no other variant member of that
4635   //      union is designated by a mem-initializer-id or
4636   //   -- the constructor's class is not a union, and, if the entity is a member
4637   //      of an anonymous union, no other member of that union is designated by
4638   //      a mem-initializer-id,
4639   //   the entity is initialized as specified in [dcl.init].
4640   //
4641   // We also apply the same rules to handle anonymous structs within anonymous
4642   // unions.
4643   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4644     return false;
4645 
4646   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4647     ExprResult DIE =
4648         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4649     if (DIE.isInvalid())
4650       return true;
4651 
4652     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4653     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4654 
4655     CXXCtorInitializer *Init;
4656     if (Indirect)
4657       Init = new (SemaRef.Context)
4658           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4659                              SourceLocation(), DIE.get(), SourceLocation());
4660     else
4661       Init = new (SemaRef.Context)
4662           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4663                              SourceLocation(), DIE.get(), SourceLocation());
4664     return Info.addFieldInitializer(Init);
4665   }
4666 
4667   // Don't initialize incomplete or zero-length arrays.
4668   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4669     return false;
4670 
4671   // Don't try to build an implicit initializer if there were semantic
4672   // errors in any of the initializers (and therefore we might be
4673   // missing some that the user actually wrote).
4674   if (Info.AnyErrorsInInits)
4675     return false;
4676 
4677   CXXCtorInitializer *Init = nullptr;
4678   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4679                                      Indirect, Init))
4680     return true;
4681 
4682   if (!Init)
4683     return false;
4684 
4685   return Info.addFieldInitializer(Init);
4686 }
4687 
4688 bool
4689 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4690                                CXXCtorInitializer *Initializer) {
4691   assert(Initializer->isDelegatingInitializer());
4692   Constructor->setNumCtorInitializers(1);
4693   CXXCtorInitializer **initializer =
4694     new (Context) CXXCtorInitializer*[1];
4695   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4696   Constructor->setCtorInitializers(initializer);
4697 
4698   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4699     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4700     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4701   }
4702 
4703   DelegatingCtorDecls.push_back(Constructor);
4704 
4705   DiagnoseUninitializedFields(*this, Constructor);
4706 
4707   return false;
4708 }
4709 
4710 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4711                                ArrayRef<CXXCtorInitializer *> Initializers) {
4712   if (Constructor->isDependentContext()) {
4713     // Just store the initializers as written, they will be checked during
4714     // instantiation.
4715     if (!Initializers.empty()) {
4716       Constructor->setNumCtorInitializers(Initializers.size());
4717       CXXCtorInitializer **baseOrMemberInitializers =
4718         new (Context) CXXCtorInitializer*[Initializers.size()];
4719       memcpy(baseOrMemberInitializers, Initializers.data(),
4720              Initializers.size() * sizeof(CXXCtorInitializer*));
4721       Constructor->setCtorInitializers(baseOrMemberInitializers);
4722     }
4723 
4724     // Let template instantiation know whether we had errors.
4725     if (AnyErrors)
4726       Constructor->setInvalidDecl();
4727 
4728     return false;
4729   }
4730 
4731   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4732 
4733   // We need to build the initializer AST according to order of construction
4734   // and not what user specified in the Initializers list.
4735   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4736   if (!ClassDecl)
4737     return true;
4738 
4739   bool HadError = false;
4740 
4741   for (unsigned i = 0; i < Initializers.size(); i++) {
4742     CXXCtorInitializer *Member = Initializers[i];
4743 
4744     if (Member->isBaseInitializer())
4745       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4746     else {
4747       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4748 
4749       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4750         for (auto *C : F->chain()) {
4751           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4752           if (FD && FD->getParent()->isUnion())
4753             Info.ActiveUnionMember.insert(std::make_pair(
4754                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4755         }
4756       } else if (FieldDecl *FD = Member->getMember()) {
4757         if (FD->getParent()->isUnion())
4758           Info.ActiveUnionMember.insert(std::make_pair(
4759               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4760       }
4761     }
4762   }
4763 
4764   // Keep track of the direct virtual bases.
4765   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4766   for (auto &I : ClassDecl->bases()) {
4767     if (I.isVirtual())
4768       DirectVBases.insert(&I);
4769   }
4770 
4771   // Push virtual bases before others.
4772   for (auto &VBase : ClassDecl->vbases()) {
4773     if (CXXCtorInitializer *Value
4774         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4775       // [class.base.init]p7, per DR257:
4776       //   A mem-initializer where the mem-initializer-id names a virtual base
4777       //   class is ignored during execution of a constructor of any class that
4778       //   is not the most derived class.
4779       if (ClassDecl->isAbstract()) {
4780         // FIXME: Provide a fixit to remove the base specifier. This requires
4781         // tracking the location of the associated comma for a base specifier.
4782         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4783           << VBase.getType() << ClassDecl;
4784         DiagnoseAbstractType(ClassDecl);
4785       }
4786 
4787       Info.AllToInit.push_back(Value);
4788     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4789       // [class.base.init]p8, per DR257:
4790       //   If a given [...] base class is not named by a mem-initializer-id
4791       //   [...] and the entity is not a virtual base class of an abstract
4792       //   class, then [...] the entity is default-initialized.
4793       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4794       CXXCtorInitializer *CXXBaseInit;
4795       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4796                                        &VBase, IsInheritedVirtualBase,
4797                                        CXXBaseInit)) {
4798         HadError = true;
4799         continue;
4800       }
4801 
4802       Info.AllToInit.push_back(CXXBaseInit);
4803     }
4804   }
4805 
4806   // Non-virtual bases.
4807   for (auto &Base : ClassDecl->bases()) {
4808     // Virtuals are in the virtual base list and already constructed.
4809     if (Base.isVirtual())
4810       continue;
4811 
4812     if (CXXCtorInitializer *Value
4813           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4814       Info.AllToInit.push_back(Value);
4815     } else if (!AnyErrors) {
4816       CXXCtorInitializer *CXXBaseInit;
4817       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4818                                        &Base, /*IsInheritedVirtualBase=*/false,
4819                                        CXXBaseInit)) {
4820         HadError = true;
4821         continue;
4822       }
4823 
4824       Info.AllToInit.push_back(CXXBaseInit);
4825     }
4826   }
4827 
4828   // Fields.
4829   for (auto *Mem : ClassDecl->decls()) {
4830     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4831       // C++ [class.bit]p2:
4832       //   A declaration for a bit-field that omits the identifier declares an
4833       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4834       //   initialized.
4835       if (F->isUnnamedBitfield())
4836         continue;
4837 
4838       // If we're not generating the implicit copy/move constructor, then we'll
4839       // handle anonymous struct/union fields based on their individual
4840       // indirect fields.
4841       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4842         continue;
4843 
4844       if (CollectFieldInitializer(*this, Info, F))
4845         HadError = true;
4846       continue;
4847     }
4848 
4849     // Beyond this point, we only consider default initialization.
4850     if (Info.isImplicitCopyOrMove())
4851       continue;
4852 
4853     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4854       if (F->getType()->isIncompleteArrayType()) {
4855         assert(ClassDecl->hasFlexibleArrayMember() &&
4856                "Incomplete array type is not valid");
4857         continue;
4858       }
4859 
4860       // Initialize each field of an anonymous struct individually.
4861       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4862         HadError = true;
4863 
4864       continue;
4865     }
4866   }
4867 
4868   unsigned NumInitializers = Info.AllToInit.size();
4869   if (NumInitializers > 0) {
4870     Constructor->setNumCtorInitializers(NumInitializers);
4871     CXXCtorInitializer **baseOrMemberInitializers =
4872       new (Context) CXXCtorInitializer*[NumInitializers];
4873     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4874            NumInitializers * sizeof(CXXCtorInitializer*));
4875     Constructor->setCtorInitializers(baseOrMemberInitializers);
4876 
4877     // Constructors implicitly reference the base and member
4878     // destructors.
4879     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4880                                            Constructor->getParent());
4881   }
4882 
4883   return HadError;
4884 }
4885 
4886 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4887   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4888     const RecordDecl *RD = RT->getDecl();
4889     if (RD->isAnonymousStructOrUnion()) {
4890       for (auto *Field : RD->fields())
4891         PopulateKeysForFields(Field, IdealInits);
4892       return;
4893     }
4894   }
4895   IdealInits.push_back(Field->getCanonicalDecl());
4896 }
4897 
4898 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4899   return Context.getCanonicalType(BaseType).getTypePtr();
4900 }
4901 
4902 static const void *GetKeyForMember(ASTContext &Context,
4903                                    CXXCtorInitializer *Member) {
4904   if (!Member->isAnyMemberInitializer())
4905     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4906 
4907   return Member->getAnyMember()->getCanonicalDecl();
4908 }
4909 
4910 static void DiagnoseBaseOrMemInitializerOrder(
4911     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4912     ArrayRef<CXXCtorInitializer *> Inits) {
4913   if (Constructor->getDeclContext()->isDependentContext())
4914     return;
4915 
4916   // Don't check initializers order unless the warning is enabled at the
4917   // location of at least one initializer.
4918   bool ShouldCheckOrder = false;
4919   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4920     CXXCtorInitializer *Init = Inits[InitIndex];
4921     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4922                                  Init->getSourceLocation())) {
4923       ShouldCheckOrder = true;
4924       break;
4925     }
4926   }
4927   if (!ShouldCheckOrder)
4928     return;
4929 
4930   // Build the list of bases and members in the order that they'll
4931   // actually be initialized.  The explicit initializers should be in
4932   // this same order but may be missing things.
4933   SmallVector<const void*, 32> IdealInitKeys;
4934 
4935   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4936 
4937   // 1. Virtual bases.
4938   for (const auto &VBase : ClassDecl->vbases())
4939     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4940 
4941   // 2. Non-virtual bases.
4942   for (const auto &Base : ClassDecl->bases()) {
4943     if (Base.isVirtual())
4944       continue;
4945     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4946   }
4947 
4948   // 3. Direct fields.
4949   for (auto *Field : ClassDecl->fields()) {
4950     if (Field->isUnnamedBitfield())
4951       continue;
4952 
4953     PopulateKeysForFields(Field, IdealInitKeys);
4954   }
4955 
4956   unsigned NumIdealInits = IdealInitKeys.size();
4957   unsigned IdealIndex = 0;
4958 
4959   CXXCtorInitializer *PrevInit = nullptr;
4960   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4961     CXXCtorInitializer *Init = Inits[InitIndex];
4962     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4963 
4964     // Scan forward to try to find this initializer in the idealized
4965     // initializers list.
4966     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4967       if (InitKey == IdealInitKeys[IdealIndex])
4968         break;
4969 
4970     // If we didn't find this initializer, it must be because we
4971     // scanned past it on a previous iteration.  That can only
4972     // happen if we're out of order;  emit a warning.
4973     if (IdealIndex == NumIdealInits && PrevInit) {
4974       Sema::SemaDiagnosticBuilder D =
4975         SemaRef.Diag(PrevInit->getSourceLocation(),
4976                      diag::warn_initializer_out_of_order);
4977 
4978       if (PrevInit->isAnyMemberInitializer())
4979         D << 0 << PrevInit->getAnyMember()->getDeclName();
4980       else
4981         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4982 
4983       if (Init->isAnyMemberInitializer())
4984         D << 0 << Init->getAnyMember()->getDeclName();
4985       else
4986         D << 1 << Init->getTypeSourceInfo()->getType();
4987 
4988       // Move back to the initializer's location in the ideal list.
4989       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4990         if (InitKey == IdealInitKeys[IdealIndex])
4991           break;
4992 
4993       assert(IdealIndex < NumIdealInits &&
4994              "initializer not found in initializer list");
4995     }
4996 
4997     PrevInit = Init;
4998   }
4999 }
5000 
5001 namespace {
5002 bool CheckRedundantInit(Sema &S,
5003                         CXXCtorInitializer *Init,
5004                         CXXCtorInitializer *&PrevInit) {
5005   if (!PrevInit) {
5006     PrevInit = Init;
5007     return false;
5008   }
5009 
5010   if (FieldDecl *Field = Init->getAnyMember())
5011     S.Diag(Init->getSourceLocation(),
5012            diag::err_multiple_mem_initialization)
5013       << Field->getDeclName()
5014       << Init->getSourceRange();
5015   else {
5016     const Type *BaseClass = Init->getBaseClass();
5017     assert(BaseClass && "neither field nor base");
5018     S.Diag(Init->getSourceLocation(),
5019            diag::err_multiple_base_initialization)
5020       << QualType(BaseClass, 0)
5021       << Init->getSourceRange();
5022   }
5023   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5024     << 0 << PrevInit->getSourceRange();
5025 
5026   return true;
5027 }
5028 
5029 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5030 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5031 
5032 bool CheckRedundantUnionInit(Sema &S,
5033                              CXXCtorInitializer *Init,
5034                              RedundantUnionMap &Unions) {
5035   FieldDecl *Field = Init->getAnyMember();
5036   RecordDecl *Parent = Field->getParent();
5037   NamedDecl *Child = Field;
5038 
5039   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5040     if (Parent->isUnion()) {
5041       UnionEntry &En = Unions[Parent];
5042       if (En.first && En.first != Child) {
5043         S.Diag(Init->getSourceLocation(),
5044                diag::err_multiple_mem_union_initialization)
5045           << Field->getDeclName()
5046           << Init->getSourceRange();
5047         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5048           << 0 << En.second->getSourceRange();
5049         return true;
5050       }
5051       if (!En.first) {
5052         En.first = Child;
5053         En.second = Init;
5054       }
5055       if (!Parent->isAnonymousStructOrUnion())
5056         return false;
5057     }
5058 
5059     Child = Parent;
5060     Parent = cast<RecordDecl>(Parent->getDeclContext());
5061   }
5062 
5063   return false;
5064 }
5065 }
5066 
5067 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5068 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5069                                 SourceLocation ColonLoc,
5070                                 ArrayRef<CXXCtorInitializer*> MemInits,
5071                                 bool AnyErrors) {
5072   if (!ConstructorDecl)
5073     return;
5074 
5075   AdjustDeclIfTemplate(ConstructorDecl);
5076 
5077   CXXConstructorDecl *Constructor
5078     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5079 
5080   if (!Constructor) {
5081     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5082     return;
5083   }
5084 
5085   // Mapping for the duplicate initializers check.
5086   // For member initializers, this is keyed with a FieldDecl*.
5087   // For base initializers, this is keyed with a Type*.
5088   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5089 
5090   // Mapping for the inconsistent anonymous-union initializers check.
5091   RedundantUnionMap MemberUnions;
5092 
5093   bool HadError = false;
5094   for (unsigned i = 0; i < MemInits.size(); i++) {
5095     CXXCtorInitializer *Init = MemInits[i];
5096 
5097     // Set the source order index.
5098     Init->setSourceOrder(i);
5099 
5100     if (Init->isAnyMemberInitializer()) {
5101       const void *Key = GetKeyForMember(Context, Init);
5102       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5103           CheckRedundantUnionInit(*this, Init, MemberUnions))
5104         HadError = true;
5105     } else if (Init->isBaseInitializer()) {
5106       const void *Key = GetKeyForMember(Context, Init);
5107       if (CheckRedundantInit(*this, Init, Members[Key]))
5108         HadError = true;
5109     } else {
5110       assert(Init->isDelegatingInitializer());
5111       // This must be the only initializer
5112       if (MemInits.size() != 1) {
5113         Diag(Init->getSourceLocation(),
5114              diag::err_delegating_initializer_alone)
5115           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5116         // We will treat this as being the only initializer.
5117       }
5118       SetDelegatingInitializer(Constructor, MemInits[i]);
5119       // Return immediately as the initializer is set.
5120       return;
5121     }
5122   }
5123 
5124   if (HadError)
5125     return;
5126 
5127   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5128 
5129   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5130 
5131   DiagnoseUninitializedFields(*this, Constructor);
5132 }
5133 
5134 void
5135 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5136                                              CXXRecordDecl *ClassDecl) {
5137   // Ignore dependent contexts. Also ignore unions, since their members never
5138   // have destructors implicitly called.
5139   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5140     return;
5141 
5142   // FIXME: all the access-control diagnostics are positioned on the
5143   // field/base declaration.  That's probably good; that said, the
5144   // user might reasonably want to know why the destructor is being
5145   // emitted, and we currently don't say.
5146 
5147   // Non-static data members.
5148   for (auto *Field : ClassDecl->fields()) {
5149     if (Field->isInvalidDecl())
5150       continue;
5151 
5152     // Don't destroy incomplete or zero-length arrays.
5153     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5154       continue;
5155 
5156     QualType FieldType = Context.getBaseElementType(Field->getType());
5157 
5158     const RecordType* RT = FieldType->getAs<RecordType>();
5159     if (!RT)
5160       continue;
5161 
5162     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5163     if (FieldClassDecl->isInvalidDecl())
5164       continue;
5165     if (FieldClassDecl->hasIrrelevantDestructor())
5166       continue;
5167     // The destructor for an implicit anonymous union member is never invoked.
5168     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5169       continue;
5170 
5171     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5172     assert(Dtor && "No dtor found for FieldClassDecl!");
5173     CheckDestructorAccess(Field->getLocation(), Dtor,
5174                           PDiag(diag::err_access_dtor_field)
5175                             << Field->getDeclName()
5176                             << FieldType);
5177 
5178     MarkFunctionReferenced(Location, Dtor);
5179     DiagnoseUseOfDecl(Dtor, Location);
5180   }
5181 
5182   // We only potentially invoke the destructors of potentially constructed
5183   // subobjects.
5184   bool VisitVirtualBases = !ClassDecl->isAbstract();
5185 
5186   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5187 
5188   // Bases.
5189   for (const auto &Base : ClassDecl->bases()) {
5190     // Bases are always records in a well-formed non-dependent class.
5191     const RecordType *RT = Base.getType()->getAs<RecordType>();
5192 
5193     // Remember direct virtual bases.
5194     if (Base.isVirtual()) {
5195       if (!VisitVirtualBases)
5196         continue;
5197       DirectVirtualBases.insert(RT);
5198     }
5199 
5200     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5201     // If our base class is invalid, we probably can't get its dtor anyway.
5202     if (BaseClassDecl->isInvalidDecl())
5203       continue;
5204     if (BaseClassDecl->hasIrrelevantDestructor())
5205       continue;
5206 
5207     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5208     assert(Dtor && "No dtor found for BaseClassDecl!");
5209 
5210     // FIXME: caret should be on the start of the class name
5211     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5212                           PDiag(diag::err_access_dtor_base)
5213                               << Base.getType() << Base.getSourceRange(),
5214                           Context.getTypeDeclType(ClassDecl));
5215 
5216     MarkFunctionReferenced(Location, Dtor);
5217     DiagnoseUseOfDecl(Dtor, Location);
5218   }
5219 
5220   if (!VisitVirtualBases)
5221     return;
5222 
5223   // Virtual bases.
5224   for (const auto &VBase : ClassDecl->vbases()) {
5225     // Bases are always records in a well-formed non-dependent class.
5226     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5227 
5228     // Ignore direct virtual bases.
5229     if (DirectVirtualBases.count(RT))
5230       continue;
5231 
5232     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5233     // If our base class is invalid, we probably can't get its dtor anyway.
5234     if (BaseClassDecl->isInvalidDecl())
5235       continue;
5236     if (BaseClassDecl->hasIrrelevantDestructor())
5237       continue;
5238 
5239     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5240     assert(Dtor && "No dtor found for BaseClassDecl!");
5241     if (CheckDestructorAccess(
5242             ClassDecl->getLocation(), Dtor,
5243             PDiag(diag::err_access_dtor_vbase)
5244                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5245             Context.getTypeDeclType(ClassDecl)) ==
5246         AR_accessible) {
5247       CheckDerivedToBaseConversion(
5248           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5249           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5250           SourceRange(), DeclarationName(), nullptr);
5251     }
5252 
5253     MarkFunctionReferenced(Location, Dtor);
5254     DiagnoseUseOfDecl(Dtor, Location);
5255   }
5256 }
5257 
5258 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5259   if (!CDtorDecl)
5260     return;
5261 
5262   if (CXXConstructorDecl *Constructor
5263       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5264     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5265     DiagnoseUninitializedFields(*this, Constructor);
5266   }
5267 }
5268 
5269 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5270   if (!getLangOpts().CPlusPlus)
5271     return false;
5272 
5273   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5274   if (!RD)
5275     return false;
5276 
5277   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5278   // class template specialization here, but doing so breaks a lot of code.
5279 
5280   // We can't answer whether something is abstract until it has a
5281   // definition. If it's currently being defined, we'll walk back
5282   // over all the declarations when we have a full definition.
5283   const CXXRecordDecl *Def = RD->getDefinition();
5284   if (!Def || Def->isBeingDefined())
5285     return false;
5286 
5287   return RD->isAbstract();
5288 }
5289 
5290 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5291                                   TypeDiagnoser &Diagnoser) {
5292   if (!isAbstractType(Loc, T))
5293     return false;
5294 
5295   T = Context.getBaseElementType(T);
5296   Diagnoser.diagnose(*this, Loc, T);
5297   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5298   return true;
5299 }
5300 
5301 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5302   // Check if we've already emitted the list of pure virtual functions
5303   // for this class.
5304   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5305     return;
5306 
5307   // If the diagnostic is suppressed, don't emit the notes. We're only
5308   // going to emit them once, so try to attach them to a diagnostic we're
5309   // actually going to show.
5310   if (Diags.isLastDiagnosticIgnored())
5311     return;
5312 
5313   CXXFinalOverriderMap FinalOverriders;
5314   RD->getFinalOverriders(FinalOverriders);
5315 
5316   // Keep a set of seen pure methods so we won't diagnose the same method
5317   // more than once.
5318   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5319 
5320   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5321                                    MEnd = FinalOverriders.end();
5322        M != MEnd;
5323        ++M) {
5324     for (OverridingMethods::iterator SO = M->second.begin(),
5325                                   SOEnd = M->second.end();
5326          SO != SOEnd; ++SO) {
5327       // C++ [class.abstract]p4:
5328       //   A class is abstract if it contains or inherits at least one
5329       //   pure virtual function for which the final overrider is pure
5330       //   virtual.
5331 
5332       //
5333       if (SO->second.size() != 1)
5334         continue;
5335 
5336       if (!SO->second.front().Method->isPure())
5337         continue;
5338 
5339       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5340         continue;
5341 
5342       Diag(SO->second.front().Method->getLocation(),
5343            diag::note_pure_virtual_function)
5344         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5345     }
5346   }
5347 
5348   if (!PureVirtualClassDiagSet)
5349     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5350   PureVirtualClassDiagSet->insert(RD);
5351 }
5352 
5353 namespace {
5354 struct AbstractUsageInfo {
5355   Sema &S;
5356   CXXRecordDecl *Record;
5357   CanQualType AbstractType;
5358   bool Invalid;
5359 
5360   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5361     : S(S), Record(Record),
5362       AbstractType(S.Context.getCanonicalType(
5363                    S.Context.getTypeDeclType(Record))),
5364       Invalid(false) {}
5365 
5366   void DiagnoseAbstractType() {
5367     if (Invalid) return;
5368     S.DiagnoseAbstractType(Record);
5369     Invalid = true;
5370   }
5371 
5372   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5373 };
5374 
5375 struct CheckAbstractUsage {
5376   AbstractUsageInfo &Info;
5377   const NamedDecl *Ctx;
5378 
5379   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5380     : Info(Info), Ctx(Ctx) {}
5381 
5382   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5383     switch (TL.getTypeLocClass()) {
5384 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5385 #define TYPELOC(CLASS, PARENT) \
5386     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5387 #include "clang/AST/TypeLocNodes.def"
5388     }
5389   }
5390 
5391   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5392     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5393     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5394       if (!TL.getParam(I))
5395         continue;
5396 
5397       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5398       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5399     }
5400   }
5401 
5402   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5403     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5404   }
5405 
5406   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5407     // Visit the type parameters from a permissive context.
5408     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5409       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5410       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5411         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5412           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5413       // TODO: other template argument types?
5414     }
5415   }
5416 
5417   // Visit pointee types from a permissive context.
5418 #define CheckPolymorphic(Type) \
5419   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5420     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5421   }
5422   CheckPolymorphic(PointerTypeLoc)
5423   CheckPolymorphic(ReferenceTypeLoc)
5424   CheckPolymorphic(MemberPointerTypeLoc)
5425   CheckPolymorphic(BlockPointerTypeLoc)
5426   CheckPolymorphic(AtomicTypeLoc)
5427 
5428   /// Handle all the types we haven't given a more specific
5429   /// implementation for above.
5430   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5431     // Every other kind of type that we haven't called out already
5432     // that has an inner type is either (1) sugar or (2) contains that
5433     // inner type in some way as a subobject.
5434     if (TypeLoc Next = TL.getNextTypeLoc())
5435       return Visit(Next, Sel);
5436 
5437     // If there's no inner type and we're in a permissive context,
5438     // don't diagnose.
5439     if (Sel == Sema::AbstractNone) return;
5440 
5441     // Check whether the type matches the abstract type.
5442     QualType T = TL.getType();
5443     if (T->isArrayType()) {
5444       Sel = Sema::AbstractArrayType;
5445       T = Info.S.Context.getBaseElementType(T);
5446     }
5447     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5448     if (CT != Info.AbstractType) return;
5449 
5450     // It matched; do some magic.
5451     if (Sel == Sema::AbstractArrayType) {
5452       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5453         << T << TL.getSourceRange();
5454     } else {
5455       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5456         << Sel << T << TL.getSourceRange();
5457     }
5458     Info.DiagnoseAbstractType();
5459   }
5460 };
5461 
5462 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5463                                   Sema::AbstractDiagSelID Sel) {
5464   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5465 }
5466 
5467 }
5468 
5469 /// Check for invalid uses of an abstract type in a method declaration.
5470 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5471                                     CXXMethodDecl *MD) {
5472   // No need to do the check on definitions, which require that
5473   // the return/param types be complete.
5474   if (MD->doesThisDeclarationHaveABody())
5475     return;
5476 
5477   // For safety's sake, just ignore it if we don't have type source
5478   // information.  This should never happen for non-implicit methods,
5479   // but...
5480   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5481     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5482 }
5483 
5484 /// Check for invalid uses of an abstract type within a class definition.
5485 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5486                                     CXXRecordDecl *RD) {
5487   for (auto *D : RD->decls()) {
5488     if (D->isImplicit()) continue;
5489 
5490     // Methods and method templates.
5491     if (isa<CXXMethodDecl>(D)) {
5492       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5493     } else if (isa<FunctionTemplateDecl>(D)) {
5494       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5495       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5496 
5497     // Fields and static variables.
5498     } else if (isa<FieldDecl>(D)) {
5499       FieldDecl *FD = cast<FieldDecl>(D);
5500       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5501         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5502     } else if (isa<VarDecl>(D)) {
5503       VarDecl *VD = cast<VarDecl>(D);
5504       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5505         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5506 
5507     // Nested classes and class templates.
5508     } else if (isa<CXXRecordDecl>(D)) {
5509       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5510     } else if (isa<ClassTemplateDecl>(D)) {
5511       CheckAbstractClassUsage(Info,
5512                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5513     }
5514   }
5515 }
5516 
5517 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5518   Attr *ClassAttr = getDLLAttr(Class);
5519   if (!ClassAttr)
5520     return;
5521 
5522   assert(ClassAttr->getKind() == attr::DLLExport);
5523 
5524   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5525 
5526   if (TSK == TSK_ExplicitInstantiationDeclaration)
5527     // Don't go any further if this is just an explicit instantiation
5528     // declaration.
5529     return;
5530 
5531   for (Decl *Member : Class->decls()) {
5532     // Defined static variables that are members of an exported base
5533     // class must be marked export too.
5534     auto *VD = dyn_cast<VarDecl>(Member);
5535     if (VD && Member->getAttr<DLLExportAttr>() &&
5536         VD->getStorageClass() == SC_Static &&
5537         TSK == TSK_ImplicitInstantiation)
5538       S.MarkVariableReferenced(VD->getLocation(), VD);
5539 
5540     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5541     if (!MD)
5542       continue;
5543 
5544     if (Member->getAttr<DLLExportAttr>()) {
5545       if (MD->isUserProvided()) {
5546         // Instantiate non-default class member functions ...
5547 
5548         // .. except for certain kinds of template specializations.
5549         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5550           continue;
5551 
5552         S.MarkFunctionReferenced(Class->getLocation(), MD);
5553 
5554         // The function will be passed to the consumer when its definition is
5555         // encountered.
5556       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5557                  MD->isCopyAssignmentOperator() ||
5558                  MD->isMoveAssignmentOperator()) {
5559         // Synthesize and instantiate non-trivial implicit methods, explicitly
5560         // defaulted methods, and the copy and move assignment operators. The
5561         // latter are exported even if they are trivial, because the address of
5562         // an operator can be taken and should compare equal across libraries.
5563         DiagnosticErrorTrap Trap(S.Diags);
5564         S.MarkFunctionReferenced(Class->getLocation(), MD);
5565         if (Trap.hasErrorOccurred()) {
5566           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5567               << Class << !S.getLangOpts().CPlusPlus11;
5568           break;
5569         }
5570 
5571         // There is no later point when we will see the definition of this
5572         // function, so pass it to the consumer now.
5573         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5574       }
5575     }
5576   }
5577 }
5578 
5579 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5580                                                         CXXRecordDecl *Class) {
5581   // Only the MS ABI has default constructor closures, so we don't need to do
5582   // this semantic checking anywhere else.
5583   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5584     return;
5585 
5586   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5587   for (Decl *Member : Class->decls()) {
5588     // Look for exported default constructors.
5589     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5590     if (!CD || !CD->isDefaultConstructor())
5591       continue;
5592     auto *Attr = CD->getAttr<DLLExportAttr>();
5593     if (!Attr)
5594       continue;
5595 
5596     // If the class is non-dependent, mark the default arguments as ODR-used so
5597     // that we can properly codegen the constructor closure.
5598     if (!Class->isDependentContext()) {
5599       for (ParmVarDecl *PD : CD->parameters()) {
5600         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5601         S.DiscardCleanupsInEvaluationContext();
5602       }
5603     }
5604 
5605     if (LastExportedDefaultCtor) {
5606       S.Diag(LastExportedDefaultCtor->getLocation(),
5607              diag::err_attribute_dll_ambiguous_default_ctor)
5608           << Class;
5609       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5610           << CD->getDeclName();
5611       return;
5612     }
5613     LastExportedDefaultCtor = CD;
5614   }
5615 }
5616 
5617 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5618   // Mark any compiler-generated routines with the implicit code_seg attribute.
5619   for (auto *Method : Class->methods()) {
5620     if (Method->isUserProvided())
5621       continue;
5622     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5623       Method->addAttr(A);
5624   }
5625 }
5626 
5627 /// Check class-level dllimport/dllexport attribute.
5628 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5629   Attr *ClassAttr = getDLLAttr(Class);
5630 
5631   // MSVC inherits DLL attributes to partial class template specializations.
5632   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5633     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5634       if (Attr *TemplateAttr =
5635               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5636         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5637         A->setInherited(true);
5638         ClassAttr = A;
5639       }
5640     }
5641   }
5642 
5643   if (!ClassAttr)
5644     return;
5645 
5646   if (!Class->isExternallyVisible()) {
5647     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5648         << Class << ClassAttr;
5649     return;
5650   }
5651 
5652   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5653       !ClassAttr->isInherited()) {
5654     // Diagnose dll attributes on members of class with dll attribute.
5655     for (Decl *Member : Class->decls()) {
5656       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5657         continue;
5658       InheritableAttr *MemberAttr = getDLLAttr(Member);
5659       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5660         continue;
5661 
5662       Diag(MemberAttr->getLocation(),
5663              diag::err_attribute_dll_member_of_dll_class)
5664           << MemberAttr << ClassAttr;
5665       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5666       Member->setInvalidDecl();
5667     }
5668   }
5669 
5670   if (Class->getDescribedClassTemplate())
5671     // Don't inherit dll attribute until the template is instantiated.
5672     return;
5673 
5674   // The class is either imported or exported.
5675   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5676 
5677   // Check if this was a dllimport attribute propagated from a derived class to
5678   // a base class template specialization. We don't apply these attributes to
5679   // static data members.
5680   const bool PropagatedImport =
5681       !ClassExported &&
5682       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5683 
5684   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5685 
5686   // Ignore explicit dllexport on explicit class template instantiation declarations.
5687   if (ClassExported && !ClassAttr->isInherited() &&
5688       TSK == TSK_ExplicitInstantiationDeclaration) {
5689     Class->dropAttr<DLLExportAttr>();
5690     return;
5691   }
5692 
5693   // Force declaration of implicit members so they can inherit the attribute.
5694   ForceDeclarationOfImplicitMembers(Class);
5695 
5696   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5697   // seem to be true in practice?
5698 
5699   for (Decl *Member : Class->decls()) {
5700     VarDecl *VD = dyn_cast<VarDecl>(Member);
5701     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5702 
5703     // Only methods and static fields inherit the attributes.
5704     if (!VD && !MD)
5705       continue;
5706 
5707     if (MD) {
5708       // Don't process deleted methods.
5709       if (MD->isDeleted())
5710         continue;
5711 
5712       if (MD->isInlined()) {
5713         // MinGW does not import or export inline methods.
5714         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5715             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5716           continue;
5717 
5718         // MSVC versions before 2015 don't export the move assignment operators
5719         // and move constructor, so don't attempt to import/export them if
5720         // we have a definition.
5721         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5722         if ((MD->isMoveAssignmentOperator() ||
5723              (Ctor && Ctor->isMoveConstructor())) &&
5724             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5725           continue;
5726 
5727         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5728         // operator is exported anyway.
5729         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5730             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5731           continue;
5732       }
5733     }
5734 
5735     // Don't apply dllimport attributes to static data members of class template
5736     // instantiations when the attribute is propagated from a derived class.
5737     if (VD && PropagatedImport)
5738       continue;
5739 
5740     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5741       continue;
5742 
5743     if (!getDLLAttr(Member)) {
5744       InheritableAttr *NewAttr = nullptr;
5745 
5746       // Do not export/import inline function when -fno-dllexport-inlines is
5747       // passed. But add attribute for later local static var check.
5748       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5749           TSK != TSK_ExplicitInstantiationDeclaration &&
5750           TSK != TSK_ExplicitInstantiationDefinition) {
5751         if (ClassExported) {
5752           NewAttr = ::new (getASTContext())
5753             DLLExportStaticLocalAttr(ClassAttr->getRange(),
5754                                      getASTContext(),
5755                                      ClassAttr->getSpellingListIndex());
5756         } else {
5757           NewAttr = ::new (getASTContext())
5758             DLLImportStaticLocalAttr(ClassAttr->getRange(),
5759                                      getASTContext(),
5760                                      ClassAttr->getSpellingListIndex());
5761         }
5762       } else {
5763         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5764       }
5765 
5766       NewAttr->setInherited(true);
5767       Member->addAttr(NewAttr);
5768 
5769       if (MD) {
5770         // Propagate DLLAttr to friend re-declarations of MD that have already
5771         // been constructed.
5772         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5773              FD = FD->getPreviousDecl()) {
5774           if (FD->getFriendObjectKind() == Decl::FOK_None)
5775             continue;
5776           assert(!getDLLAttr(FD) &&
5777                  "friend re-decl should not already have a DLLAttr");
5778           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5779           NewAttr->setInherited(true);
5780           FD->addAttr(NewAttr);
5781         }
5782       }
5783     }
5784   }
5785 
5786   if (ClassExported)
5787     DelayedDllExportClasses.push_back(Class);
5788 }
5789 
5790 /// Perform propagation of DLL attributes from a derived class to a
5791 /// templated base class for MS compatibility.
5792 void Sema::propagateDLLAttrToBaseClassTemplate(
5793     CXXRecordDecl *Class, Attr *ClassAttr,
5794     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5795   if (getDLLAttr(
5796           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5797     // If the base class template has a DLL attribute, don't try to change it.
5798     return;
5799   }
5800 
5801   auto TSK = BaseTemplateSpec->getSpecializationKind();
5802   if (!getDLLAttr(BaseTemplateSpec) &&
5803       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5804        TSK == TSK_ImplicitInstantiation)) {
5805     // The template hasn't been instantiated yet (or it has, but only as an
5806     // explicit instantiation declaration or implicit instantiation, which means
5807     // we haven't codegenned any members yet), so propagate the attribute.
5808     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5809     NewAttr->setInherited(true);
5810     BaseTemplateSpec->addAttr(NewAttr);
5811 
5812     // If this was an import, mark that we propagated it from a derived class to
5813     // a base class template specialization.
5814     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5815       ImportAttr->setPropagatedToBaseTemplate();
5816 
5817     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5818     // needs to be run again to work see the new attribute. Otherwise this will
5819     // get run whenever the template is instantiated.
5820     if (TSK != TSK_Undeclared)
5821       checkClassLevelDLLAttribute(BaseTemplateSpec);
5822 
5823     return;
5824   }
5825 
5826   if (getDLLAttr(BaseTemplateSpec)) {
5827     // The template has already been specialized or instantiated with an
5828     // attribute, explicitly or through propagation. We should not try to change
5829     // it.
5830     return;
5831   }
5832 
5833   // The template was previously instantiated or explicitly specialized without
5834   // a dll attribute, It's too late for us to add an attribute, so warn that
5835   // this is unsupported.
5836   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5837       << BaseTemplateSpec->isExplicitSpecialization();
5838   Diag(ClassAttr->getLocation(), diag::note_attribute);
5839   if (BaseTemplateSpec->isExplicitSpecialization()) {
5840     Diag(BaseTemplateSpec->getLocation(),
5841            diag::note_template_class_explicit_specialization_was_here)
5842         << BaseTemplateSpec;
5843   } else {
5844     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5845            diag::note_template_class_instantiation_was_here)
5846         << BaseTemplateSpec;
5847   }
5848 }
5849 
5850 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5851                                         SourceLocation DefaultLoc) {
5852   switch (S.getSpecialMember(MD)) {
5853   case Sema::CXXDefaultConstructor:
5854     S.DefineImplicitDefaultConstructor(DefaultLoc,
5855                                        cast<CXXConstructorDecl>(MD));
5856     break;
5857   case Sema::CXXCopyConstructor:
5858     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5859     break;
5860   case Sema::CXXCopyAssignment:
5861     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5862     break;
5863   case Sema::CXXDestructor:
5864     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5865     break;
5866   case Sema::CXXMoveConstructor:
5867     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5868     break;
5869   case Sema::CXXMoveAssignment:
5870     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5871     break;
5872   case Sema::CXXInvalid:
5873     llvm_unreachable("Invalid special member.");
5874   }
5875 }
5876 
5877 /// Determine whether a type is permitted to be passed or returned in
5878 /// registers, per C++ [class.temporary]p3.
5879 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5880                                TargetInfo::CallingConvKind CCK) {
5881   if (D->isDependentType() || D->isInvalidDecl())
5882     return false;
5883 
5884   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5885   // The PS4 platform ABI follows the behavior of Clang 3.2.
5886   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5887     return !D->hasNonTrivialDestructorForCall() &&
5888            !D->hasNonTrivialCopyConstructorForCall();
5889 
5890   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5891     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5892     bool DtorIsTrivialForCall = false;
5893 
5894     // If a class has at least one non-deleted, trivial copy constructor, it
5895     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5896     //
5897     // Note: This permits classes with non-trivial copy or move ctors to be
5898     // passed in registers, so long as they *also* have a trivial copy ctor,
5899     // which is non-conforming.
5900     if (D->needsImplicitCopyConstructor()) {
5901       if (!D->defaultedCopyConstructorIsDeleted()) {
5902         if (D->hasTrivialCopyConstructor())
5903           CopyCtorIsTrivial = true;
5904         if (D->hasTrivialCopyConstructorForCall())
5905           CopyCtorIsTrivialForCall = true;
5906       }
5907     } else {
5908       for (const CXXConstructorDecl *CD : D->ctors()) {
5909         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5910           if (CD->isTrivial())
5911             CopyCtorIsTrivial = true;
5912           if (CD->isTrivialForCall())
5913             CopyCtorIsTrivialForCall = true;
5914         }
5915       }
5916     }
5917 
5918     if (D->needsImplicitDestructor()) {
5919       if (!D->defaultedDestructorIsDeleted() &&
5920           D->hasTrivialDestructorForCall())
5921         DtorIsTrivialForCall = true;
5922     } else if (const auto *DD = D->getDestructor()) {
5923       if (!DD->isDeleted() && DD->isTrivialForCall())
5924         DtorIsTrivialForCall = true;
5925     }
5926 
5927     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5928     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5929       return true;
5930 
5931     // If a class has a destructor, we'd really like to pass it indirectly
5932     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5933     // impossible for small types, which it will pass in a single register or
5934     // stack slot. Most objects with dtors are large-ish, so handle that early.
5935     // We can't call out all large objects as being indirect because there are
5936     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5937     // how we pass large POD types.
5938 
5939     // Note: This permits small classes with nontrivial destructors to be
5940     // passed in registers, which is non-conforming.
5941     if (CopyCtorIsTrivial &&
5942         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5943       return true;
5944     return false;
5945   }
5946 
5947   // Per C++ [class.temporary]p3, the relevant condition is:
5948   //   each copy constructor, move constructor, and destructor of X is
5949   //   either trivial or deleted, and X has at least one non-deleted copy
5950   //   or move constructor
5951   bool HasNonDeletedCopyOrMove = false;
5952 
5953   if (D->needsImplicitCopyConstructor() &&
5954       !D->defaultedCopyConstructorIsDeleted()) {
5955     if (!D->hasTrivialCopyConstructorForCall())
5956       return false;
5957     HasNonDeletedCopyOrMove = true;
5958   }
5959 
5960   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5961       !D->defaultedMoveConstructorIsDeleted()) {
5962     if (!D->hasTrivialMoveConstructorForCall())
5963       return false;
5964     HasNonDeletedCopyOrMove = true;
5965   }
5966 
5967   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5968       !D->hasTrivialDestructorForCall())
5969     return false;
5970 
5971   for (const CXXMethodDecl *MD : D->methods()) {
5972     if (MD->isDeleted())
5973       continue;
5974 
5975     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5976     if (CD && CD->isCopyOrMoveConstructor())
5977       HasNonDeletedCopyOrMove = true;
5978     else if (!isa<CXXDestructorDecl>(MD))
5979       continue;
5980 
5981     if (!MD->isTrivialForCall())
5982       return false;
5983   }
5984 
5985   return HasNonDeletedCopyOrMove;
5986 }
5987 
5988 /// Perform semantic checks on a class definition that has been
5989 /// completing, introducing implicitly-declared members, checking for
5990 /// abstract types, etc.
5991 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5992   if (!Record)
5993     return;
5994 
5995   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5996     AbstractUsageInfo Info(*this, Record);
5997     CheckAbstractClassUsage(Info, Record);
5998   }
5999 
6000   // If this is not an aggregate type and has no user-declared constructor,
6001   // complain about any non-static data members of reference or const scalar
6002   // type, since they will never get initializers.
6003   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6004       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6005       !Record->isLambda()) {
6006     bool Complained = false;
6007     for (const auto *F : Record->fields()) {
6008       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6009         continue;
6010 
6011       if (F->getType()->isReferenceType() ||
6012           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6013         if (!Complained) {
6014           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6015             << Record->getTagKind() << Record;
6016           Complained = true;
6017         }
6018 
6019         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6020           << F->getType()->isReferenceType()
6021           << F->getDeclName();
6022       }
6023     }
6024   }
6025 
6026   if (Record->getIdentifier()) {
6027     // C++ [class.mem]p13:
6028     //   If T is the name of a class, then each of the following shall have a
6029     //   name different from T:
6030     //     - every member of every anonymous union that is a member of class T.
6031     //
6032     // C++ [class.mem]p14:
6033     //   In addition, if class T has a user-declared constructor (12.1), every
6034     //   non-static data member of class T shall have a name different from T.
6035     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6036     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6037          ++I) {
6038       NamedDecl *D = (*I)->getUnderlyingDecl();
6039       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6040            Record->hasUserDeclaredConstructor()) ||
6041           isa<IndirectFieldDecl>(D)) {
6042         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6043           << D->getDeclName();
6044         break;
6045       }
6046     }
6047   }
6048 
6049   // Warn if the class has virtual methods but non-virtual public destructor.
6050   if (Record->isPolymorphic() && !Record->isDependentType()) {
6051     CXXDestructorDecl *dtor = Record->getDestructor();
6052     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6053         !Record->hasAttr<FinalAttr>())
6054       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6055            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6056   }
6057 
6058   if (Record->isAbstract()) {
6059     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6060       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6061         << FA->isSpelledAsSealed();
6062       DiagnoseAbstractType(Record);
6063     }
6064   }
6065 
6066   // See if trivial_abi has to be dropped.
6067   if (Record->hasAttr<TrivialABIAttr>())
6068     checkIllFormedTrivialABIStruct(*Record);
6069 
6070   // Set HasTrivialSpecialMemberForCall if the record has attribute
6071   // "trivial_abi".
6072   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6073 
6074   if (HasTrivialABI)
6075     Record->setHasTrivialSpecialMemberForCall();
6076 
6077   bool HasMethodWithOverrideControl = false,
6078        HasOverridingMethodWithoutOverrideControl = false;
6079   if (!Record->isDependentType()) {
6080     for (auto *M : Record->methods()) {
6081       // See if a method overloads virtual methods in a base
6082       // class without overriding any.
6083       if (!M->isStatic())
6084         DiagnoseHiddenVirtualMethods(M);
6085       if (M->hasAttr<OverrideAttr>())
6086         HasMethodWithOverrideControl = true;
6087       else if (M->size_overridden_methods() > 0)
6088         HasOverridingMethodWithoutOverrideControl = true;
6089       // Check whether the explicitly-defaulted special members are valid.
6090       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6091         CheckExplicitlyDefaultedSpecialMember(M);
6092 
6093       // For an explicitly defaulted or deleted special member, we defer
6094       // determining triviality until the class is complete. That time is now!
6095       CXXSpecialMember CSM = getSpecialMember(M);
6096       if (!M->isImplicit() && !M->isUserProvided()) {
6097         if (CSM != CXXInvalid) {
6098           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6099           // Inform the class that we've finished declaring this member.
6100           Record->finishedDefaultedOrDeletedMember(M);
6101           M->setTrivialForCall(
6102               HasTrivialABI ||
6103               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6104           Record->setTrivialForCallFlags(M);
6105         }
6106       }
6107 
6108       // Set triviality for the purpose of calls if this is a user-provided
6109       // copy/move constructor or destructor.
6110       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6111            CSM == CXXDestructor) && M->isUserProvided()) {
6112         M->setTrivialForCall(HasTrivialABI);
6113         Record->setTrivialForCallFlags(M);
6114       }
6115 
6116       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6117           M->hasAttr<DLLExportAttr>()) {
6118         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6119             M->isTrivial() &&
6120             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6121              CSM == CXXDestructor))
6122           M->dropAttr<DLLExportAttr>();
6123 
6124         if (M->hasAttr<DLLExportAttr>()) {
6125           DefineImplicitSpecialMember(*this, M, M->getLocation());
6126           ActOnFinishInlineFunctionDef(M);
6127         }
6128       }
6129     }
6130   }
6131 
6132   if (HasMethodWithOverrideControl &&
6133       HasOverridingMethodWithoutOverrideControl) {
6134     // At least one method has the 'override' control declared.
6135     // Diagnose all other overridden methods which do not have 'override' specified on them.
6136     for (auto *M : Record->methods())
6137       DiagnoseAbsenceOfOverrideControl(M);
6138   }
6139 
6140   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6141   // whether this class uses any C++ features that are implemented
6142   // completely differently in MSVC, and if so, emit a diagnostic.
6143   // That diagnostic defaults to an error, but we allow projects to
6144   // map it down to a warning (or ignore it).  It's a fairly common
6145   // practice among users of the ms_struct pragma to mass-annotate
6146   // headers, sweeping up a bunch of types that the project doesn't
6147   // really rely on MSVC-compatible layout for.  We must therefore
6148   // support "ms_struct except for C++ stuff" as a secondary ABI.
6149   if (Record->isMsStruct(Context) &&
6150       (Record->isPolymorphic() || Record->getNumBases())) {
6151     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6152   }
6153 
6154   checkClassLevelDLLAttribute(Record);
6155   checkClassLevelCodeSegAttribute(Record);
6156 
6157   bool ClangABICompat4 =
6158       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6159   TargetInfo::CallingConvKind CCK =
6160       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6161   bool CanPass = canPassInRegisters(*this, Record, CCK);
6162 
6163   // Do not change ArgPassingRestrictions if it has already been set to
6164   // APK_CanNeverPassInRegs.
6165   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6166     Record->setArgPassingRestrictions(CanPass
6167                                           ? RecordDecl::APK_CanPassInRegs
6168                                           : RecordDecl::APK_CannotPassInRegs);
6169 
6170   // If canPassInRegisters returns true despite the record having a non-trivial
6171   // destructor, the record is destructed in the callee. This happens only when
6172   // the record or one of its subobjects has a field annotated with trivial_abi
6173   // or a field qualified with ObjC __strong/__weak.
6174   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6175     Record->setParamDestroyedInCallee(true);
6176   else if (Record->hasNonTrivialDestructor())
6177     Record->setParamDestroyedInCallee(CanPass);
6178 
6179   if (getLangOpts().ForceEmitVTables) {
6180     // If we want to emit all the vtables, we need to mark it as used.  This
6181     // is especially required for cases like vtable assumption loads.
6182     MarkVTableUsed(Record->getInnerLocStart(), Record);
6183   }
6184 }
6185 
6186 /// Look up the special member function that would be called by a special
6187 /// member function for a subobject of class type.
6188 ///
6189 /// \param Class The class type of the subobject.
6190 /// \param CSM The kind of special member function.
6191 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6192 /// \param ConstRHS True if this is a copy operation with a const object
6193 ///        on its RHS, that is, if the argument to the outer special member
6194 ///        function is 'const' and this is not a field marked 'mutable'.
6195 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6196     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6197     unsigned FieldQuals, bool ConstRHS) {
6198   unsigned LHSQuals = 0;
6199   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6200     LHSQuals = FieldQuals;
6201 
6202   unsigned RHSQuals = FieldQuals;
6203   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6204     RHSQuals = 0;
6205   else if (ConstRHS)
6206     RHSQuals |= Qualifiers::Const;
6207 
6208   return S.LookupSpecialMember(Class, CSM,
6209                                RHSQuals & Qualifiers::Const,
6210                                RHSQuals & Qualifiers::Volatile,
6211                                false,
6212                                LHSQuals & Qualifiers::Const,
6213                                LHSQuals & Qualifiers::Volatile);
6214 }
6215 
6216 class Sema::InheritedConstructorInfo {
6217   Sema &S;
6218   SourceLocation UseLoc;
6219 
6220   /// A mapping from the base classes through which the constructor was
6221   /// inherited to the using shadow declaration in that base class (or a null
6222   /// pointer if the constructor was declared in that base class).
6223   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6224       InheritedFromBases;
6225 
6226 public:
6227   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6228                            ConstructorUsingShadowDecl *Shadow)
6229       : S(S), UseLoc(UseLoc) {
6230     bool DiagnosedMultipleConstructedBases = false;
6231     CXXRecordDecl *ConstructedBase = nullptr;
6232     UsingDecl *ConstructedBaseUsing = nullptr;
6233 
6234     // Find the set of such base class subobjects and check that there's a
6235     // unique constructed subobject.
6236     for (auto *D : Shadow->redecls()) {
6237       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6238       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6239       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6240 
6241       InheritedFromBases.insert(
6242           std::make_pair(DNominatedBase->getCanonicalDecl(),
6243                          DShadow->getNominatedBaseClassShadowDecl()));
6244       if (DShadow->constructsVirtualBase())
6245         InheritedFromBases.insert(
6246             std::make_pair(DConstructedBase->getCanonicalDecl(),
6247                            DShadow->getConstructedBaseClassShadowDecl()));
6248       else
6249         assert(DNominatedBase == DConstructedBase);
6250 
6251       // [class.inhctor.init]p2:
6252       //   If the constructor was inherited from multiple base class subobjects
6253       //   of type B, the program is ill-formed.
6254       if (!ConstructedBase) {
6255         ConstructedBase = DConstructedBase;
6256         ConstructedBaseUsing = D->getUsingDecl();
6257       } else if (ConstructedBase != DConstructedBase &&
6258                  !Shadow->isInvalidDecl()) {
6259         if (!DiagnosedMultipleConstructedBases) {
6260           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6261               << Shadow->getTargetDecl();
6262           S.Diag(ConstructedBaseUsing->getLocation(),
6263                diag::note_ambiguous_inherited_constructor_using)
6264               << ConstructedBase;
6265           DiagnosedMultipleConstructedBases = true;
6266         }
6267         S.Diag(D->getUsingDecl()->getLocation(),
6268                diag::note_ambiguous_inherited_constructor_using)
6269             << DConstructedBase;
6270       }
6271     }
6272 
6273     if (DiagnosedMultipleConstructedBases)
6274       Shadow->setInvalidDecl();
6275   }
6276 
6277   /// Find the constructor to use for inherited construction of a base class,
6278   /// and whether that base class constructor inherits the constructor from a
6279   /// virtual base class (in which case it won't actually invoke it).
6280   std::pair<CXXConstructorDecl *, bool>
6281   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6282     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6283     if (It == InheritedFromBases.end())
6284       return std::make_pair(nullptr, false);
6285 
6286     // This is an intermediary class.
6287     if (It->second)
6288       return std::make_pair(
6289           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6290           It->second->constructsVirtualBase());
6291 
6292     // This is the base class from which the constructor was inherited.
6293     return std::make_pair(Ctor, false);
6294   }
6295 };
6296 
6297 /// Is the special member function which would be selected to perform the
6298 /// specified operation on the specified class type a constexpr constructor?
6299 static bool
6300 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6301                          Sema::CXXSpecialMember CSM, unsigned Quals,
6302                          bool ConstRHS,
6303                          CXXConstructorDecl *InheritedCtor = nullptr,
6304                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6305   // If we're inheriting a constructor, see if we need to call it for this base
6306   // class.
6307   if (InheritedCtor) {
6308     assert(CSM == Sema::CXXDefaultConstructor);
6309     auto BaseCtor =
6310         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6311     if (BaseCtor)
6312       return BaseCtor->isConstexpr();
6313   }
6314 
6315   if (CSM == Sema::CXXDefaultConstructor)
6316     return ClassDecl->hasConstexprDefaultConstructor();
6317 
6318   Sema::SpecialMemberOverloadResult SMOR =
6319       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6320   if (!SMOR.getMethod())
6321     // A constructor we wouldn't select can't be "involved in initializing"
6322     // anything.
6323     return true;
6324   return SMOR.getMethod()->isConstexpr();
6325 }
6326 
6327 /// Determine whether the specified special member function would be constexpr
6328 /// if it were implicitly defined.
6329 static bool defaultedSpecialMemberIsConstexpr(
6330     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6331     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6332     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6333   if (!S.getLangOpts().CPlusPlus11)
6334     return false;
6335 
6336   // C++11 [dcl.constexpr]p4:
6337   // In the definition of a constexpr constructor [...]
6338   bool Ctor = true;
6339   switch (CSM) {
6340   case Sema::CXXDefaultConstructor:
6341     if (Inherited)
6342       break;
6343     // Since default constructor lookup is essentially trivial (and cannot
6344     // involve, for instance, template instantiation), we compute whether a
6345     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6346     //
6347     // This is important for performance; we need to know whether the default
6348     // constructor is constexpr to determine whether the type is a literal type.
6349     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6350 
6351   case Sema::CXXCopyConstructor:
6352   case Sema::CXXMoveConstructor:
6353     // For copy or move constructors, we need to perform overload resolution.
6354     break;
6355 
6356   case Sema::CXXCopyAssignment:
6357   case Sema::CXXMoveAssignment:
6358     if (!S.getLangOpts().CPlusPlus14)
6359       return false;
6360     // In C++1y, we need to perform overload resolution.
6361     Ctor = false;
6362     break;
6363 
6364   case Sema::CXXDestructor:
6365   case Sema::CXXInvalid:
6366     return false;
6367   }
6368 
6369   //   -- if the class is a non-empty union, or for each non-empty anonymous
6370   //      union member of a non-union class, exactly one non-static data member
6371   //      shall be initialized; [DR1359]
6372   //
6373   // If we squint, this is guaranteed, since exactly one non-static data member
6374   // will be initialized (if the constructor isn't deleted), we just don't know
6375   // which one.
6376   if (Ctor && ClassDecl->isUnion())
6377     return CSM == Sema::CXXDefaultConstructor
6378                ? ClassDecl->hasInClassInitializer() ||
6379                      !ClassDecl->hasVariantMembers()
6380                : true;
6381 
6382   //   -- the class shall not have any virtual base classes;
6383   if (Ctor && ClassDecl->getNumVBases())
6384     return false;
6385 
6386   // C++1y [class.copy]p26:
6387   //   -- [the class] is a literal type, and
6388   if (!Ctor && !ClassDecl->isLiteral())
6389     return false;
6390 
6391   //   -- every constructor involved in initializing [...] base class
6392   //      sub-objects shall be a constexpr constructor;
6393   //   -- the assignment operator selected to copy/move each direct base
6394   //      class is a constexpr function, and
6395   for (const auto &B : ClassDecl->bases()) {
6396     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6397     if (!BaseType) continue;
6398 
6399     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6400     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6401                                   InheritedCtor, Inherited))
6402       return false;
6403   }
6404 
6405   //   -- every constructor involved in initializing non-static data members
6406   //      [...] shall be a constexpr constructor;
6407   //   -- every non-static data member and base class sub-object shall be
6408   //      initialized
6409   //   -- for each non-static data member of X that is of class type (or array
6410   //      thereof), the assignment operator selected to copy/move that member is
6411   //      a constexpr function
6412   for (const auto *F : ClassDecl->fields()) {
6413     if (F->isInvalidDecl())
6414       continue;
6415     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6416       continue;
6417     QualType BaseType = S.Context.getBaseElementType(F->getType());
6418     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6419       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6420       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6421                                     BaseType.getCVRQualifiers(),
6422                                     ConstArg && !F->isMutable()))
6423         return false;
6424     } else if (CSM == Sema::CXXDefaultConstructor) {
6425       return false;
6426     }
6427   }
6428 
6429   // All OK, it's constexpr!
6430   return true;
6431 }
6432 
6433 static Sema::ImplicitExceptionSpecification
6434 ComputeDefaultedSpecialMemberExceptionSpec(
6435     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6436     Sema::InheritedConstructorInfo *ICI);
6437 
6438 static Sema::ImplicitExceptionSpecification
6439 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6440   auto CSM = S.getSpecialMember(MD);
6441   if (CSM != Sema::CXXInvalid)
6442     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6443 
6444   auto *CD = cast<CXXConstructorDecl>(MD);
6445   assert(CD->getInheritedConstructor() &&
6446          "only special members have implicit exception specs");
6447   Sema::InheritedConstructorInfo ICI(
6448       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6449   return ComputeDefaultedSpecialMemberExceptionSpec(
6450       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6451 }
6452 
6453 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6454                                                             CXXMethodDecl *MD) {
6455   FunctionProtoType::ExtProtoInfo EPI;
6456 
6457   // Build an exception specification pointing back at this member.
6458   EPI.ExceptionSpec.Type = EST_Unevaluated;
6459   EPI.ExceptionSpec.SourceDecl = MD;
6460 
6461   // Set the calling convention to the default for C++ instance methods.
6462   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6463       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6464                                             /*IsCXXMethod=*/true));
6465   return EPI;
6466 }
6467 
6468 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6469   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6470   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6471     return;
6472 
6473   // Evaluate the exception specification.
6474   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6475   auto ESI = IES.getExceptionSpec();
6476 
6477   // Update the type of the special member to use it.
6478   UpdateExceptionSpec(MD, ESI);
6479 
6480   // A user-provided destructor can be defined outside the class. When that
6481   // happens, be sure to update the exception specification on both
6482   // declarations.
6483   const FunctionProtoType *CanonicalFPT =
6484     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6485   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6486     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6487 }
6488 
6489 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6490   CXXRecordDecl *RD = MD->getParent();
6491   CXXSpecialMember CSM = getSpecialMember(MD);
6492 
6493   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6494          "not an explicitly-defaulted special member");
6495 
6496   // Whether this was the first-declared instance of the constructor.
6497   // This affects whether we implicitly add an exception spec and constexpr.
6498   bool First = MD == MD->getCanonicalDecl();
6499 
6500   bool HadError = false;
6501 
6502   // C++11 [dcl.fct.def.default]p1:
6503   //   A function that is explicitly defaulted shall
6504   //     -- be a special member function (checked elsewhere),
6505   //     -- have the same type (except for ref-qualifiers, and except that a
6506   //        copy operation can take a non-const reference) as an implicit
6507   //        declaration, and
6508   //     -- not have default arguments.
6509   // C++2a changes the second bullet to instead delete the function if it's
6510   // defaulted on its first declaration, unless it's "an assignment operator,
6511   // and its return type differs or its parameter type is not a reference".
6512   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6513   bool ShouldDeleteForTypeMismatch = false;
6514   unsigned ExpectedParams = 1;
6515   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6516     ExpectedParams = 0;
6517   if (MD->getNumParams() != ExpectedParams) {
6518     // This checks for default arguments: a copy or move constructor with a
6519     // default argument is classified as a default constructor, and assignment
6520     // operations and destructors can't have default arguments.
6521     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6522       << CSM << MD->getSourceRange();
6523     HadError = true;
6524   } else if (MD->isVariadic()) {
6525     if (DeleteOnTypeMismatch)
6526       ShouldDeleteForTypeMismatch = true;
6527     else {
6528       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6529         << CSM << MD->getSourceRange();
6530       HadError = true;
6531     }
6532   }
6533 
6534   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6535 
6536   bool CanHaveConstParam = false;
6537   if (CSM == CXXCopyConstructor)
6538     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6539   else if (CSM == CXXCopyAssignment)
6540     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6541 
6542   QualType ReturnType = Context.VoidTy;
6543   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6544     // Check for return type matching.
6545     ReturnType = Type->getReturnType();
6546     QualType ExpectedReturnType =
6547         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6548     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6549       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6550         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6551       HadError = true;
6552     }
6553 
6554     // A defaulted special member cannot have cv-qualifiers.
6555     if (Type->getTypeQuals()) {
6556       if (DeleteOnTypeMismatch)
6557         ShouldDeleteForTypeMismatch = true;
6558       else {
6559         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6560           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6561         HadError = true;
6562       }
6563     }
6564   }
6565 
6566   // Check for parameter type matching.
6567   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6568   bool HasConstParam = false;
6569   if (ExpectedParams && ArgType->isReferenceType()) {
6570     // Argument must be reference to possibly-const T.
6571     QualType ReferentType = ArgType->getPointeeType();
6572     HasConstParam = ReferentType.isConstQualified();
6573 
6574     if (ReferentType.isVolatileQualified()) {
6575       if (DeleteOnTypeMismatch)
6576         ShouldDeleteForTypeMismatch = true;
6577       else {
6578         Diag(MD->getLocation(),
6579              diag::err_defaulted_special_member_volatile_param) << CSM;
6580         HadError = true;
6581       }
6582     }
6583 
6584     if (HasConstParam && !CanHaveConstParam) {
6585       if (DeleteOnTypeMismatch)
6586         ShouldDeleteForTypeMismatch = true;
6587       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6588         Diag(MD->getLocation(),
6589              diag::err_defaulted_special_member_copy_const_param)
6590           << (CSM == CXXCopyAssignment);
6591         // FIXME: Explain why this special member can't be const.
6592         HadError = true;
6593       } else {
6594         Diag(MD->getLocation(),
6595              diag::err_defaulted_special_member_move_const_param)
6596           << (CSM == CXXMoveAssignment);
6597         HadError = true;
6598       }
6599     }
6600   } else if (ExpectedParams) {
6601     // A copy assignment operator can take its argument by value, but a
6602     // defaulted one cannot.
6603     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6604     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6605     HadError = true;
6606   }
6607 
6608   // C++11 [dcl.fct.def.default]p2:
6609   //   An explicitly-defaulted function may be declared constexpr only if it
6610   //   would have been implicitly declared as constexpr,
6611   // Do not apply this rule to members of class templates, since core issue 1358
6612   // makes such functions always instantiate to constexpr functions. For
6613   // functions which cannot be constexpr (for non-constructors in C++11 and for
6614   // destructors in C++1y), this is checked elsewhere.
6615   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6616                                                      HasConstParam);
6617   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6618                                  : isa<CXXConstructorDecl>(MD)) &&
6619       MD->isConstexpr() && !Constexpr &&
6620       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6621     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6622     // FIXME: Explain why the special member can't be constexpr.
6623     HadError = true;
6624   }
6625 
6626   //   and may have an explicit exception-specification only if it is compatible
6627   //   with the exception-specification on the implicit declaration.
6628   if (Type->hasExceptionSpec()) {
6629     // Delay the check if this is the first declaration of the special member,
6630     // since we may not have parsed some necessary in-class initializers yet.
6631     if (First) {
6632       // If the exception specification needs to be instantiated, do so now,
6633       // before we clobber it with an EST_Unevaluated specification below.
6634       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6635         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6636         Type = MD->getType()->getAs<FunctionProtoType>();
6637       }
6638       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6639     } else
6640       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6641   }
6642 
6643   //   If a function is explicitly defaulted on its first declaration,
6644   if (First) {
6645     //  -- it is implicitly considered to be constexpr if the implicit
6646     //     definition would be,
6647     MD->setConstexpr(Constexpr);
6648 
6649     //  -- it is implicitly considered to have the same exception-specification
6650     //     as if it had been implicitly declared,
6651     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6652     EPI.ExceptionSpec.Type = EST_Unevaluated;
6653     EPI.ExceptionSpec.SourceDecl = MD;
6654     MD->setType(Context.getFunctionType(ReturnType,
6655                                         llvm::makeArrayRef(&ArgType,
6656                                                            ExpectedParams),
6657                                         EPI));
6658   }
6659 
6660   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6661     if (First) {
6662       SetDeclDeleted(MD, MD->getLocation());
6663       if (!inTemplateInstantiation() && !HadError) {
6664         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6665         if (ShouldDeleteForTypeMismatch) {
6666           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6667         } else {
6668           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6669         }
6670       }
6671       if (ShouldDeleteForTypeMismatch && !HadError) {
6672         Diag(MD->getLocation(),
6673              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6674       }
6675     } else {
6676       // C++11 [dcl.fct.def.default]p4:
6677       //   [For a] user-provided explicitly-defaulted function [...] if such a
6678       //   function is implicitly defined as deleted, the program is ill-formed.
6679       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6680       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6681       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6682       HadError = true;
6683     }
6684   }
6685 
6686   if (HadError)
6687     MD->setInvalidDecl();
6688 }
6689 
6690 /// Check whether the exception specification provided for an
6691 /// explicitly-defaulted special member matches the exception specification
6692 /// that would have been generated for an implicit special member, per
6693 /// C++11 [dcl.fct.def.default]p2.
6694 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6695     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6696   // If the exception specification was explicitly specified but hadn't been
6697   // parsed when the method was defaulted, grab it now.
6698   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6699     SpecifiedType =
6700         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6701 
6702   // Compute the implicit exception specification.
6703   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6704                                                        /*IsCXXMethod=*/true);
6705   FunctionProtoType::ExtProtoInfo EPI(CC);
6706   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6707   EPI.ExceptionSpec = IES.getExceptionSpec();
6708   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6709     Context.getFunctionType(Context.VoidTy, None, EPI));
6710 
6711   // Ensure that it matches.
6712   CheckEquivalentExceptionSpec(
6713     PDiag(diag::err_incorrect_defaulted_exception_spec)
6714       << getSpecialMember(MD), PDiag(),
6715     ImplicitType, SourceLocation(),
6716     SpecifiedType, MD->getLocation());
6717 }
6718 
6719 void Sema::CheckDelayedMemberExceptionSpecs() {
6720   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6721   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6722   decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6723 
6724   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6725   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6726   std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6727 
6728   // Perform any deferred checking of exception specifications for virtual
6729   // destructors.
6730   for (auto &Check : Overriding)
6731     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6732 
6733   // Perform any deferred checking of exception specifications for befriended
6734   // special members.
6735   for (auto &Check : Equivalent)
6736     CheckEquivalentExceptionSpec(Check.second, Check.first);
6737 
6738   // Check that any explicitly-defaulted methods have exception specifications
6739   // compatible with their implicit exception specifications.
6740   for (auto &Spec : Defaulted)
6741     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6742 }
6743 
6744 namespace {
6745 /// CRTP base class for visiting operations performed by a special member
6746 /// function (or inherited constructor).
6747 template<typename Derived>
6748 struct SpecialMemberVisitor {
6749   Sema &S;
6750   CXXMethodDecl *MD;
6751   Sema::CXXSpecialMember CSM;
6752   Sema::InheritedConstructorInfo *ICI;
6753 
6754   // Properties of the special member, computed for convenience.
6755   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6756 
6757   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6758                        Sema::InheritedConstructorInfo *ICI)
6759       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6760     switch (CSM) {
6761     case Sema::CXXDefaultConstructor:
6762     case Sema::CXXCopyConstructor:
6763     case Sema::CXXMoveConstructor:
6764       IsConstructor = true;
6765       break;
6766     case Sema::CXXCopyAssignment:
6767     case Sema::CXXMoveAssignment:
6768       IsAssignment = true;
6769       break;
6770     case Sema::CXXDestructor:
6771       break;
6772     case Sema::CXXInvalid:
6773       llvm_unreachable("invalid special member kind");
6774     }
6775 
6776     if (MD->getNumParams()) {
6777       if (const ReferenceType *RT =
6778               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6779         ConstArg = RT->getPointeeType().isConstQualified();
6780     }
6781   }
6782 
6783   Derived &getDerived() { return static_cast<Derived&>(*this); }
6784 
6785   /// Is this a "move" special member?
6786   bool isMove() const {
6787     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6788   }
6789 
6790   /// Look up the corresponding special member in the given class.
6791   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6792                                              unsigned Quals, bool IsMutable) {
6793     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6794                                        ConstArg && !IsMutable);
6795   }
6796 
6797   /// Look up the constructor for the specified base class to see if it's
6798   /// overridden due to this being an inherited constructor.
6799   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6800     if (!ICI)
6801       return {};
6802     assert(CSM == Sema::CXXDefaultConstructor);
6803     auto *BaseCtor =
6804       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6805     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6806       return MD;
6807     return {};
6808   }
6809 
6810   /// A base or member subobject.
6811   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6812 
6813   /// Get the location to use for a subobject in diagnostics.
6814   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6815     // FIXME: For an indirect virtual base, the direct base leading to
6816     // the indirect virtual base would be a more useful choice.
6817     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6818       return B->getBaseTypeLoc();
6819     else
6820       return Subobj.get<FieldDecl*>()->getLocation();
6821   }
6822 
6823   enum BasesToVisit {
6824     /// Visit all non-virtual (direct) bases.
6825     VisitNonVirtualBases,
6826     /// Visit all direct bases, virtual or not.
6827     VisitDirectBases,
6828     /// Visit all non-virtual bases, and all virtual bases if the class
6829     /// is not abstract.
6830     VisitPotentiallyConstructedBases,
6831     /// Visit all direct or virtual bases.
6832     VisitAllBases
6833   };
6834 
6835   // Visit the bases and members of the class.
6836   bool visit(BasesToVisit Bases) {
6837     CXXRecordDecl *RD = MD->getParent();
6838 
6839     if (Bases == VisitPotentiallyConstructedBases)
6840       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6841 
6842     for (auto &B : RD->bases())
6843       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6844           getDerived().visitBase(&B))
6845         return true;
6846 
6847     if (Bases == VisitAllBases)
6848       for (auto &B : RD->vbases())
6849         if (getDerived().visitBase(&B))
6850           return true;
6851 
6852     for (auto *F : RD->fields())
6853       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6854           getDerived().visitField(F))
6855         return true;
6856 
6857     return false;
6858   }
6859 };
6860 }
6861 
6862 namespace {
6863 struct SpecialMemberDeletionInfo
6864     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6865   bool Diagnose;
6866 
6867   SourceLocation Loc;
6868 
6869   bool AllFieldsAreConst;
6870 
6871   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6872                             Sema::CXXSpecialMember CSM,
6873                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6874       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6875         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6876 
6877   bool inUnion() const { return MD->getParent()->isUnion(); }
6878 
6879   Sema::CXXSpecialMember getEffectiveCSM() {
6880     return ICI ? Sema::CXXInvalid : CSM;
6881   }
6882 
6883   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6884   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6885 
6886   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6887   bool shouldDeleteForField(FieldDecl *FD);
6888   bool shouldDeleteForAllConstMembers();
6889 
6890   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6891                                      unsigned Quals);
6892   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6893                                     Sema::SpecialMemberOverloadResult SMOR,
6894                                     bool IsDtorCallInCtor);
6895 
6896   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6897 };
6898 }
6899 
6900 /// Is the given special member inaccessible when used on the given
6901 /// sub-object.
6902 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6903                                              CXXMethodDecl *target) {
6904   /// If we're operating on a base class, the object type is the
6905   /// type of this special member.
6906   QualType objectTy;
6907   AccessSpecifier access = target->getAccess();
6908   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6909     objectTy = S.Context.getTypeDeclType(MD->getParent());
6910     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6911 
6912   // If we're operating on a field, the object type is the type of the field.
6913   } else {
6914     objectTy = S.Context.getTypeDeclType(target->getParent());
6915   }
6916 
6917   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6918 }
6919 
6920 /// Check whether we should delete a special member due to the implicit
6921 /// definition containing a call to a special member of a subobject.
6922 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6923     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6924     bool IsDtorCallInCtor) {
6925   CXXMethodDecl *Decl = SMOR.getMethod();
6926   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6927 
6928   int DiagKind = -1;
6929 
6930   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6931     DiagKind = !Decl ? 0 : 1;
6932   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6933     DiagKind = 2;
6934   else if (!isAccessible(Subobj, Decl))
6935     DiagKind = 3;
6936   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6937            !Decl->isTrivial()) {
6938     // A member of a union must have a trivial corresponding special member.
6939     // As a weird special case, a destructor call from a union's constructor
6940     // must be accessible and non-deleted, but need not be trivial. Such a
6941     // destructor is never actually called, but is semantically checked as
6942     // if it were.
6943     DiagKind = 4;
6944   }
6945 
6946   if (DiagKind == -1)
6947     return false;
6948 
6949   if (Diagnose) {
6950     if (Field) {
6951       S.Diag(Field->getLocation(),
6952              diag::note_deleted_special_member_class_subobject)
6953         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6954         << Field << DiagKind << IsDtorCallInCtor;
6955     } else {
6956       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6957       S.Diag(Base->getBeginLoc(),
6958              diag::note_deleted_special_member_class_subobject)
6959           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6960           << Base->getType() << DiagKind << IsDtorCallInCtor;
6961     }
6962 
6963     if (DiagKind == 1)
6964       S.NoteDeletedFunction(Decl);
6965     // FIXME: Explain inaccessibility if DiagKind == 3.
6966   }
6967 
6968   return true;
6969 }
6970 
6971 /// Check whether we should delete a special member function due to having a
6972 /// direct or virtual base class or non-static data member of class type M.
6973 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6974     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6975   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6976   bool IsMutable = Field && Field->isMutable();
6977 
6978   // C++11 [class.ctor]p5:
6979   // -- any direct or virtual base class, or non-static data member with no
6980   //    brace-or-equal-initializer, has class type M (or array thereof) and
6981   //    either M has no default constructor or overload resolution as applied
6982   //    to M's default constructor results in an ambiguity or in a function
6983   //    that is deleted or inaccessible
6984   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6985   // -- a direct or virtual base class B that cannot be copied/moved because
6986   //    overload resolution, as applied to B's corresponding special member,
6987   //    results in an ambiguity or a function that is deleted or inaccessible
6988   //    from the defaulted special member
6989   // C++11 [class.dtor]p5:
6990   // -- any direct or virtual base class [...] has a type with a destructor
6991   //    that is deleted or inaccessible
6992   if (!(CSM == Sema::CXXDefaultConstructor &&
6993         Field && Field->hasInClassInitializer()) &&
6994       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6995                                    false))
6996     return true;
6997 
6998   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6999   // -- any direct or virtual base class or non-static data member has a
7000   //    type with a destructor that is deleted or inaccessible
7001   if (IsConstructor) {
7002     Sema::SpecialMemberOverloadResult SMOR =
7003         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7004                               false, false, false, false, false);
7005     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7006       return true;
7007   }
7008 
7009   return false;
7010 }
7011 
7012 /// Check whether we should delete a special member function due to the class
7013 /// having a particular direct or virtual base class.
7014 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7015   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7016   // If program is correct, BaseClass cannot be null, but if it is, the error
7017   // must be reported elsewhere.
7018   if (!BaseClass)
7019     return false;
7020   // If we have an inheriting constructor, check whether we're calling an
7021   // inherited constructor instead of a default constructor.
7022   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7023   if (auto *BaseCtor = SMOR.getMethod()) {
7024     // Note that we do not check access along this path; other than that,
7025     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7026     // FIXME: Check that the base has a usable destructor! Sink this into
7027     // shouldDeleteForClassSubobject.
7028     if (BaseCtor->isDeleted() && Diagnose) {
7029       S.Diag(Base->getBeginLoc(),
7030              diag::note_deleted_special_member_class_subobject)
7031           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7032           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
7033       S.NoteDeletedFunction(BaseCtor);
7034     }
7035     return BaseCtor->isDeleted();
7036   }
7037   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7038 }
7039 
7040 /// Check whether we should delete a special member function due to the class
7041 /// having a particular non-static data member.
7042 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7043   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7044   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7045 
7046   if (CSM == Sema::CXXDefaultConstructor) {
7047     // For a default constructor, all references must be initialized in-class
7048     // and, if a union, it must have a non-const member.
7049     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7050       if (Diagnose)
7051         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7052           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7053       return true;
7054     }
7055     // C++11 [class.ctor]p5: any non-variant non-static data member of
7056     // const-qualified type (or array thereof) with no
7057     // brace-or-equal-initializer does not have a user-provided default
7058     // constructor.
7059     if (!inUnion() && FieldType.isConstQualified() &&
7060         !FD->hasInClassInitializer() &&
7061         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7062       if (Diagnose)
7063         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7064           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7065       return true;
7066     }
7067 
7068     if (inUnion() && !FieldType.isConstQualified())
7069       AllFieldsAreConst = false;
7070   } else if (CSM == Sema::CXXCopyConstructor) {
7071     // For a copy constructor, data members must not be of rvalue reference
7072     // type.
7073     if (FieldType->isRValueReferenceType()) {
7074       if (Diagnose)
7075         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7076           << MD->getParent() << FD << FieldType;
7077       return true;
7078     }
7079   } else if (IsAssignment) {
7080     // For an assignment operator, data members must not be of reference type.
7081     if (FieldType->isReferenceType()) {
7082       if (Diagnose)
7083         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7084           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7085       return true;
7086     }
7087     if (!FieldRecord && FieldType.isConstQualified()) {
7088       // C++11 [class.copy]p23:
7089       // -- a non-static data member of const non-class type (or array thereof)
7090       if (Diagnose)
7091         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7092           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7093       return true;
7094     }
7095   }
7096 
7097   if (FieldRecord) {
7098     // Some additional restrictions exist on the variant members.
7099     if (!inUnion() && FieldRecord->isUnion() &&
7100         FieldRecord->isAnonymousStructOrUnion()) {
7101       bool AllVariantFieldsAreConst = true;
7102 
7103       // FIXME: Handle anonymous unions declared within anonymous unions.
7104       for (auto *UI : FieldRecord->fields()) {
7105         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7106 
7107         if (!UnionFieldType.isConstQualified())
7108           AllVariantFieldsAreConst = false;
7109 
7110         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7111         if (UnionFieldRecord &&
7112             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7113                                           UnionFieldType.getCVRQualifiers()))
7114           return true;
7115       }
7116 
7117       // At least one member in each anonymous union must be non-const
7118       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7119           !FieldRecord->field_empty()) {
7120         if (Diagnose)
7121           S.Diag(FieldRecord->getLocation(),
7122                  diag::note_deleted_default_ctor_all_const)
7123             << !!ICI << MD->getParent() << /*anonymous union*/1;
7124         return true;
7125       }
7126 
7127       // Don't check the implicit member of the anonymous union type.
7128       // This is technically non-conformant, but sanity demands it.
7129       return false;
7130     }
7131 
7132     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7133                                       FieldType.getCVRQualifiers()))
7134       return true;
7135   }
7136 
7137   return false;
7138 }
7139 
7140 /// C++11 [class.ctor] p5:
7141 ///   A defaulted default constructor for a class X is defined as deleted if
7142 /// X is a union and all of its variant members are of const-qualified type.
7143 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7144   // This is a silly definition, because it gives an empty union a deleted
7145   // default constructor. Don't do that.
7146   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7147     bool AnyFields = false;
7148     for (auto *F : MD->getParent()->fields())
7149       if ((AnyFields = !F->isUnnamedBitfield()))
7150         break;
7151     if (!AnyFields)
7152       return false;
7153     if (Diagnose)
7154       S.Diag(MD->getParent()->getLocation(),
7155              diag::note_deleted_default_ctor_all_const)
7156         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7157     return true;
7158   }
7159   return false;
7160 }
7161 
7162 /// Determine whether a defaulted special member function should be defined as
7163 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7164 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7165 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7166                                      InheritedConstructorInfo *ICI,
7167                                      bool Diagnose) {
7168   if (MD->isInvalidDecl())
7169     return false;
7170   CXXRecordDecl *RD = MD->getParent();
7171   assert(!RD->isDependentType() && "do deletion after instantiation");
7172   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7173     return false;
7174 
7175   // C++11 [expr.lambda.prim]p19:
7176   //   The closure type associated with a lambda-expression has a
7177   //   deleted (8.4.3) default constructor and a deleted copy
7178   //   assignment operator.
7179   // C++2a adds back these operators if the lambda has no capture-default.
7180   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7181       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7182     if (Diagnose)
7183       Diag(RD->getLocation(), diag::note_lambda_decl);
7184     return true;
7185   }
7186 
7187   // For an anonymous struct or union, the copy and assignment special members
7188   // will never be used, so skip the check. For an anonymous union declared at
7189   // namespace scope, the constructor and destructor are used.
7190   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7191       RD->isAnonymousStructOrUnion())
7192     return false;
7193 
7194   // C++11 [class.copy]p7, p18:
7195   //   If the class definition declares a move constructor or move assignment
7196   //   operator, an implicitly declared copy constructor or copy assignment
7197   //   operator is defined as deleted.
7198   if (MD->isImplicit() &&
7199       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7200     CXXMethodDecl *UserDeclaredMove = nullptr;
7201 
7202     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7203     // deletion of the corresponding copy operation, not both copy operations.
7204     // MSVC 2015 has adopted the standards conforming behavior.
7205     bool DeletesOnlyMatchingCopy =
7206         getLangOpts().MSVCCompat &&
7207         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7208 
7209     if (RD->hasUserDeclaredMoveConstructor() &&
7210         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7211       if (!Diagnose) return true;
7212 
7213       // Find any user-declared move constructor.
7214       for (auto *I : RD->ctors()) {
7215         if (I->isMoveConstructor()) {
7216           UserDeclaredMove = I;
7217           break;
7218         }
7219       }
7220       assert(UserDeclaredMove);
7221     } else if (RD->hasUserDeclaredMoveAssignment() &&
7222                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7223       if (!Diagnose) return true;
7224 
7225       // Find any user-declared move assignment operator.
7226       for (auto *I : RD->methods()) {
7227         if (I->isMoveAssignmentOperator()) {
7228           UserDeclaredMove = I;
7229           break;
7230         }
7231       }
7232       assert(UserDeclaredMove);
7233     }
7234 
7235     if (UserDeclaredMove) {
7236       Diag(UserDeclaredMove->getLocation(),
7237            diag::note_deleted_copy_user_declared_move)
7238         << (CSM == CXXCopyAssignment) << RD
7239         << UserDeclaredMove->isMoveAssignmentOperator();
7240       return true;
7241     }
7242   }
7243 
7244   // Do access control from the special member function
7245   ContextRAII MethodContext(*this, MD);
7246 
7247   // C++11 [class.dtor]p5:
7248   // -- for a virtual destructor, lookup of the non-array deallocation function
7249   //    results in an ambiguity or in a function that is deleted or inaccessible
7250   if (CSM == CXXDestructor && MD->isVirtual()) {
7251     FunctionDecl *OperatorDelete = nullptr;
7252     DeclarationName Name =
7253       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7254     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7255                                  OperatorDelete, /*Diagnose*/false)) {
7256       if (Diagnose)
7257         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7258       return true;
7259     }
7260   }
7261 
7262   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7263 
7264   // Per DR1611, do not consider virtual bases of constructors of abstract
7265   // classes, since we are not going to construct them.
7266   // Per DR1658, do not consider virtual bases of destructors of abstract
7267   // classes either.
7268   // Per DR2180, for assignment operators we only assign (and thus only
7269   // consider) direct bases.
7270   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7271                                  : SMI.VisitPotentiallyConstructedBases))
7272     return true;
7273 
7274   if (SMI.shouldDeleteForAllConstMembers())
7275     return true;
7276 
7277   if (getLangOpts().CUDA) {
7278     // We should delete the special member in CUDA mode if target inference
7279     // failed.
7280     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7281     // is treated as certain special member, which may not reflect what special
7282     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7283     // expects CSM to match MD, therefore recalculate CSM.
7284     assert(ICI || CSM == getSpecialMember(MD));
7285     auto RealCSM = CSM;
7286     if (ICI)
7287       RealCSM = getSpecialMember(MD);
7288 
7289     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7290                                                    SMI.ConstArg, Diagnose);
7291   }
7292 
7293   return false;
7294 }
7295 
7296 /// Perform lookup for a special member of the specified kind, and determine
7297 /// whether it is trivial. If the triviality can be determined without the
7298 /// lookup, skip it. This is intended for use when determining whether a
7299 /// special member of a containing object is trivial, and thus does not ever
7300 /// perform overload resolution for default constructors.
7301 ///
7302 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7303 /// member that was most likely to be intended to be trivial, if any.
7304 ///
7305 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7306 /// determine whether the special member is trivial.
7307 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7308                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7309                                      bool ConstRHS,
7310                                      Sema::TrivialABIHandling TAH,
7311                                      CXXMethodDecl **Selected) {
7312   if (Selected)
7313     *Selected = nullptr;
7314 
7315   switch (CSM) {
7316   case Sema::CXXInvalid:
7317     llvm_unreachable("not a special member");
7318 
7319   case Sema::CXXDefaultConstructor:
7320     // C++11 [class.ctor]p5:
7321     //   A default constructor is trivial if:
7322     //    - all the [direct subobjects] have trivial default constructors
7323     //
7324     // Note, no overload resolution is performed in this case.
7325     if (RD->hasTrivialDefaultConstructor())
7326       return true;
7327 
7328     if (Selected) {
7329       // If there's a default constructor which could have been trivial, dig it
7330       // out. Otherwise, if there's any user-provided default constructor, point
7331       // to that as an example of why there's not a trivial one.
7332       CXXConstructorDecl *DefCtor = nullptr;
7333       if (RD->needsImplicitDefaultConstructor())
7334         S.DeclareImplicitDefaultConstructor(RD);
7335       for (auto *CI : RD->ctors()) {
7336         if (!CI->isDefaultConstructor())
7337           continue;
7338         DefCtor = CI;
7339         if (!DefCtor->isUserProvided())
7340           break;
7341       }
7342 
7343       *Selected = DefCtor;
7344     }
7345 
7346     return false;
7347 
7348   case Sema::CXXDestructor:
7349     // C++11 [class.dtor]p5:
7350     //   A destructor is trivial if:
7351     //    - all the direct [subobjects] have trivial destructors
7352     if (RD->hasTrivialDestructor() ||
7353         (TAH == Sema::TAH_ConsiderTrivialABI &&
7354          RD->hasTrivialDestructorForCall()))
7355       return true;
7356 
7357     if (Selected) {
7358       if (RD->needsImplicitDestructor())
7359         S.DeclareImplicitDestructor(RD);
7360       *Selected = RD->getDestructor();
7361     }
7362 
7363     return false;
7364 
7365   case Sema::CXXCopyConstructor:
7366     // C++11 [class.copy]p12:
7367     //   A copy constructor is trivial if:
7368     //    - the constructor selected to copy each direct [subobject] is trivial
7369     if (RD->hasTrivialCopyConstructor() ||
7370         (TAH == Sema::TAH_ConsiderTrivialABI &&
7371          RD->hasTrivialCopyConstructorForCall())) {
7372       if (Quals == Qualifiers::Const)
7373         // We must either select the trivial copy constructor or reach an
7374         // ambiguity; no need to actually perform overload resolution.
7375         return true;
7376     } else if (!Selected) {
7377       return false;
7378     }
7379     // In C++98, we are not supposed to perform overload resolution here, but we
7380     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7381     // cases like B as having a non-trivial copy constructor:
7382     //   struct A { template<typename T> A(T&); };
7383     //   struct B { mutable A a; };
7384     goto NeedOverloadResolution;
7385 
7386   case Sema::CXXCopyAssignment:
7387     // C++11 [class.copy]p25:
7388     //   A copy assignment operator is trivial if:
7389     //    - the assignment operator selected to copy each direct [subobject] is
7390     //      trivial
7391     if (RD->hasTrivialCopyAssignment()) {
7392       if (Quals == Qualifiers::Const)
7393         return true;
7394     } else if (!Selected) {
7395       return false;
7396     }
7397     // In C++98, we are not supposed to perform overload resolution here, but we
7398     // treat that as a language defect.
7399     goto NeedOverloadResolution;
7400 
7401   case Sema::CXXMoveConstructor:
7402   case Sema::CXXMoveAssignment:
7403   NeedOverloadResolution:
7404     Sema::SpecialMemberOverloadResult SMOR =
7405         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7406 
7407     // The standard doesn't describe how to behave if the lookup is ambiguous.
7408     // We treat it as not making the member non-trivial, just like the standard
7409     // mandates for the default constructor. This should rarely matter, because
7410     // the member will also be deleted.
7411     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7412       return true;
7413 
7414     if (!SMOR.getMethod()) {
7415       assert(SMOR.getKind() ==
7416              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7417       return false;
7418     }
7419 
7420     // We deliberately don't check if we found a deleted special member. We're
7421     // not supposed to!
7422     if (Selected)
7423       *Selected = SMOR.getMethod();
7424 
7425     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7426         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7427       return SMOR.getMethod()->isTrivialForCall();
7428     return SMOR.getMethod()->isTrivial();
7429   }
7430 
7431   llvm_unreachable("unknown special method kind");
7432 }
7433 
7434 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7435   for (auto *CI : RD->ctors())
7436     if (!CI->isImplicit())
7437       return CI;
7438 
7439   // Look for constructor templates.
7440   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7441   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7442     if (CXXConstructorDecl *CD =
7443           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7444       return CD;
7445   }
7446 
7447   return nullptr;
7448 }
7449 
7450 /// The kind of subobject we are checking for triviality. The values of this
7451 /// enumeration are used in diagnostics.
7452 enum TrivialSubobjectKind {
7453   /// The subobject is a base class.
7454   TSK_BaseClass,
7455   /// The subobject is a non-static data member.
7456   TSK_Field,
7457   /// The object is actually the complete object.
7458   TSK_CompleteObject
7459 };
7460 
7461 /// Check whether the special member selected for a given type would be trivial.
7462 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7463                                       QualType SubType, bool ConstRHS,
7464                                       Sema::CXXSpecialMember CSM,
7465                                       TrivialSubobjectKind Kind,
7466                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7467   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7468   if (!SubRD)
7469     return true;
7470 
7471   CXXMethodDecl *Selected;
7472   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7473                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7474     return true;
7475 
7476   if (Diagnose) {
7477     if (ConstRHS)
7478       SubType.addConst();
7479 
7480     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7481       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7482         << Kind << SubType.getUnqualifiedType();
7483       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7484         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7485     } else if (!Selected)
7486       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7487         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7488     else if (Selected->isUserProvided()) {
7489       if (Kind == TSK_CompleteObject)
7490         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7491           << Kind << SubType.getUnqualifiedType() << CSM;
7492       else {
7493         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7494           << Kind << SubType.getUnqualifiedType() << CSM;
7495         S.Diag(Selected->getLocation(), diag::note_declared_at);
7496       }
7497     } else {
7498       if (Kind != TSK_CompleteObject)
7499         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7500           << Kind << SubType.getUnqualifiedType() << CSM;
7501 
7502       // Explain why the defaulted or deleted special member isn't trivial.
7503       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7504                                Diagnose);
7505     }
7506   }
7507 
7508   return false;
7509 }
7510 
7511 /// Check whether the members of a class type allow a special member to be
7512 /// trivial.
7513 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7514                                      Sema::CXXSpecialMember CSM,
7515                                      bool ConstArg,
7516                                      Sema::TrivialABIHandling TAH,
7517                                      bool Diagnose) {
7518   for (const auto *FI : RD->fields()) {
7519     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7520       continue;
7521 
7522     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7523 
7524     // Pretend anonymous struct or union members are members of this class.
7525     if (FI->isAnonymousStructOrUnion()) {
7526       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7527                                     CSM, ConstArg, TAH, Diagnose))
7528         return false;
7529       continue;
7530     }
7531 
7532     // C++11 [class.ctor]p5:
7533     //   A default constructor is trivial if [...]
7534     //    -- no non-static data member of its class has a
7535     //       brace-or-equal-initializer
7536     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7537       if (Diagnose)
7538         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7539       return false;
7540     }
7541 
7542     // Objective C ARC 4.3.5:
7543     //   [...] nontrivally ownership-qualified types are [...] not trivially
7544     //   default constructible, copy constructible, move constructible, copy
7545     //   assignable, move assignable, or destructible [...]
7546     if (FieldType.hasNonTrivialObjCLifetime()) {
7547       if (Diagnose)
7548         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7549           << RD << FieldType.getObjCLifetime();
7550       return false;
7551     }
7552 
7553     bool ConstRHS = ConstArg && !FI->isMutable();
7554     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7555                                    CSM, TSK_Field, TAH, Diagnose))
7556       return false;
7557   }
7558 
7559   return true;
7560 }
7561 
7562 /// Diagnose why the specified class does not have a trivial special member of
7563 /// the given kind.
7564 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7565   QualType Ty = Context.getRecordType(RD);
7566 
7567   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7568   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7569                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7570                             /*Diagnose*/true);
7571 }
7572 
7573 /// Determine whether a defaulted or deleted special member function is trivial,
7574 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7575 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7576 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7577                                   TrivialABIHandling TAH, bool Diagnose) {
7578   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7579 
7580   CXXRecordDecl *RD = MD->getParent();
7581 
7582   bool ConstArg = false;
7583 
7584   // C++11 [class.copy]p12, p25: [DR1593]
7585   //   A [special member] is trivial if [...] its parameter-type-list is
7586   //   equivalent to the parameter-type-list of an implicit declaration [...]
7587   switch (CSM) {
7588   case CXXDefaultConstructor:
7589   case CXXDestructor:
7590     // Trivial default constructors and destructors cannot have parameters.
7591     break;
7592 
7593   case CXXCopyConstructor:
7594   case CXXCopyAssignment: {
7595     // Trivial copy operations always have const, non-volatile parameter types.
7596     ConstArg = true;
7597     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7598     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7599     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7600       if (Diagnose)
7601         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7602           << Param0->getSourceRange() << Param0->getType()
7603           << Context.getLValueReferenceType(
7604                Context.getRecordType(RD).withConst());
7605       return false;
7606     }
7607     break;
7608   }
7609 
7610   case CXXMoveConstructor:
7611   case CXXMoveAssignment: {
7612     // Trivial move operations always have non-cv-qualified parameters.
7613     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7614     const RValueReferenceType *RT =
7615       Param0->getType()->getAs<RValueReferenceType>();
7616     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7617       if (Diagnose)
7618         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7619           << Param0->getSourceRange() << Param0->getType()
7620           << Context.getRValueReferenceType(Context.getRecordType(RD));
7621       return false;
7622     }
7623     break;
7624   }
7625 
7626   case CXXInvalid:
7627     llvm_unreachable("not a special member");
7628   }
7629 
7630   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7631     if (Diagnose)
7632       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7633            diag::note_nontrivial_default_arg)
7634         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7635     return false;
7636   }
7637   if (MD->isVariadic()) {
7638     if (Diagnose)
7639       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7640     return false;
7641   }
7642 
7643   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7644   //   A copy/move [constructor or assignment operator] is trivial if
7645   //    -- the [member] selected to copy/move each direct base class subobject
7646   //       is trivial
7647   //
7648   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7649   //   A [default constructor or destructor] is trivial if
7650   //    -- all the direct base classes have trivial [default constructors or
7651   //       destructors]
7652   for (const auto &BI : RD->bases())
7653     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7654                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7655       return false;
7656 
7657   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7658   //   A copy/move [constructor or assignment operator] for a class X is
7659   //   trivial if
7660   //    -- for each non-static data member of X that is of class type (or array
7661   //       thereof), the constructor selected to copy/move that member is
7662   //       trivial
7663   //
7664   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7665   //   A [default constructor or destructor] is trivial if
7666   //    -- for all of the non-static data members of its class that are of class
7667   //       type (or array thereof), each such class has a trivial [default
7668   //       constructor or destructor]
7669   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7670     return false;
7671 
7672   // C++11 [class.dtor]p5:
7673   //   A destructor is trivial if [...]
7674   //    -- the destructor is not virtual
7675   if (CSM == CXXDestructor && MD->isVirtual()) {
7676     if (Diagnose)
7677       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7678     return false;
7679   }
7680 
7681   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7682   //   A [special member] for class X is trivial if [...]
7683   //    -- class X has no virtual functions and no virtual base classes
7684   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7685     if (!Diagnose)
7686       return false;
7687 
7688     if (RD->getNumVBases()) {
7689       // Check for virtual bases. We already know that the corresponding
7690       // member in all bases is trivial, so vbases must all be direct.
7691       CXXBaseSpecifier &BS = *RD->vbases_begin();
7692       assert(BS.isVirtual());
7693       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7694       return false;
7695     }
7696 
7697     // Must have a virtual method.
7698     for (const auto *MI : RD->methods()) {
7699       if (MI->isVirtual()) {
7700         SourceLocation MLoc = MI->getBeginLoc();
7701         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7702         return false;
7703       }
7704     }
7705 
7706     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7707   }
7708 
7709   // Looks like it's trivial!
7710   return true;
7711 }
7712 
7713 namespace {
7714 struct FindHiddenVirtualMethod {
7715   Sema *S;
7716   CXXMethodDecl *Method;
7717   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7718   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7719 
7720 private:
7721   /// Check whether any most overridden method from MD in Methods
7722   static bool CheckMostOverridenMethods(
7723       const CXXMethodDecl *MD,
7724       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7725     if (MD->size_overridden_methods() == 0)
7726       return Methods.count(MD->getCanonicalDecl());
7727     for (const CXXMethodDecl *O : MD->overridden_methods())
7728       if (CheckMostOverridenMethods(O, Methods))
7729         return true;
7730     return false;
7731   }
7732 
7733 public:
7734   /// Member lookup function that determines whether a given C++
7735   /// method overloads virtual methods in a base class without overriding any,
7736   /// to be used with CXXRecordDecl::lookupInBases().
7737   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7738     RecordDecl *BaseRecord =
7739         Specifier->getType()->getAs<RecordType>()->getDecl();
7740 
7741     DeclarationName Name = Method->getDeclName();
7742     assert(Name.getNameKind() == DeclarationName::Identifier);
7743 
7744     bool foundSameNameMethod = false;
7745     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7746     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7747          Path.Decls = Path.Decls.slice(1)) {
7748       NamedDecl *D = Path.Decls.front();
7749       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7750         MD = MD->getCanonicalDecl();
7751         foundSameNameMethod = true;
7752         // Interested only in hidden virtual methods.
7753         if (!MD->isVirtual())
7754           continue;
7755         // If the method we are checking overrides a method from its base
7756         // don't warn about the other overloaded methods. Clang deviates from
7757         // GCC by only diagnosing overloads of inherited virtual functions that
7758         // do not override any other virtual functions in the base. GCC's
7759         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7760         // function from a base class. These cases may be better served by a
7761         // warning (not specific to virtual functions) on call sites when the
7762         // call would select a different function from the base class, were it
7763         // visible.
7764         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7765         if (!S->IsOverload(Method, MD, false))
7766           return true;
7767         // Collect the overload only if its hidden.
7768         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7769           overloadedMethods.push_back(MD);
7770       }
7771     }
7772 
7773     if (foundSameNameMethod)
7774       OverloadedMethods.append(overloadedMethods.begin(),
7775                                overloadedMethods.end());
7776     return foundSameNameMethod;
7777   }
7778 };
7779 } // end anonymous namespace
7780 
7781 /// Add the most overriden methods from MD to Methods
7782 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7783                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7784   if (MD->size_overridden_methods() == 0)
7785     Methods.insert(MD->getCanonicalDecl());
7786   else
7787     for (const CXXMethodDecl *O : MD->overridden_methods())
7788       AddMostOverridenMethods(O, Methods);
7789 }
7790 
7791 /// Check if a method overloads virtual methods in a base class without
7792 /// overriding any.
7793 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7794                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7795   if (!MD->getDeclName().isIdentifier())
7796     return;
7797 
7798   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7799                      /*bool RecordPaths=*/false,
7800                      /*bool DetectVirtual=*/false);
7801   FindHiddenVirtualMethod FHVM;
7802   FHVM.Method = MD;
7803   FHVM.S = this;
7804 
7805   // Keep the base methods that were overridden or introduced in the subclass
7806   // by 'using' in a set. A base method not in this set is hidden.
7807   CXXRecordDecl *DC = MD->getParent();
7808   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7809   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7810     NamedDecl *ND = *I;
7811     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7812       ND = shad->getTargetDecl();
7813     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7814       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7815   }
7816 
7817   if (DC->lookupInBases(FHVM, Paths))
7818     OverloadedMethods = FHVM.OverloadedMethods;
7819 }
7820 
7821 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7822                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7823   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7824     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7825     PartialDiagnostic PD = PDiag(
7826          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7827     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7828     Diag(overloadedMD->getLocation(), PD);
7829   }
7830 }
7831 
7832 /// Diagnose methods which overload virtual methods in a base class
7833 /// without overriding any.
7834 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7835   if (MD->isInvalidDecl())
7836     return;
7837 
7838   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7839     return;
7840 
7841   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7842   FindHiddenVirtualMethods(MD, OverloadedMethods);
7843   if (!OverloadedMethods.empty()) {
7844     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7845       << MD << (OverloadedMethods.size() > 1);
7846 
7847     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7848   }
7849 }
7850 
7851 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7852   auto PrintDiagAndRemoveAttr = [&]() {
7853     // No diagnostics if this is a template instantiation.
7854     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7855       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7856            diag::ext_cannot_use_trivial_abi) << &RD;
7857     RD.dropAttr<TrivialABIAttr>();
7858   };
7859 
7860   // Ill-formed if the struct has virtual functions.
7861   if (RD.isPolymorphic()) {
7862     PrintDiagAndRemoveAttr();
7863     return;
7864   }
7865 
7866   for (const auto &B : RD.bases()) {
7867     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7868     // virtual base.
7869     if ((!B.getType()->isDependentType() &&
7870          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7871         B.isVirtual()) {
7872       PrintDiagAndRemoveAttr();
7873       return;
7874     }
7875   }
7876 
7877   for (const auto *FD : RD.fields()) {
7878     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7879     // non-trivial for the purpose of calls.
7880     QualType FT = FD->getType();
7881     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7882       PrintDiagAndRemoveAttr();
7883       return;
7884     }
7885 
7886     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7887       if (!RT->isDependentType() &&
7888           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7889         PrintDiagAndRemoveAttr();
7890         return;
7891       }
7892   }
7893 }
7894 
7895 void Sema::ActOnFinishCXXMemberSpecification(
7896     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7897     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7898   if (!TagDecl)
7899     return;
7900 
7901   AdjustDeclIfTemplate(TagDecl);
7902 
7903   for (const ParsedAttr &AL : AttrList) {
7904     if (AL.getKind() != ParsedAttr::AT_Visibility)
7905       continue;
7906     AL.setInvalid();
7907     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7908         << AL.getName();
7909   }
7910 
7911   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7912               // strict aliasing violation!
7913               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7914               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7915 
7916   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7917 }
7918 
7919 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7920 /// special functions, such as the default constructor, copy
7921 /// constructor, or destructor, to the given C++ class (C++
7922 /// [special]p1).  This routine can only be executed just before the
7923 /// definition of the class is complete.
7924 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7925   if (ClassDecl->needsImplicitDefaultConstructor()) {
7926     ++ASTContext::NumImplicitDefaultConstructors;
7927 
7928     if (ClassDecl->hasInheritedConstructor())
7929       DeclareImplicitDefaultConstructor(ClassDecl);
7930   }
7931 
7932   if (ClassDecl->needsImplicitCopyConstructor()) {
7933     ++ASTContext::NumImplicitCopyConstructors;
7934 
7935     // If the properties or semantics of the copy constructor couldn't be
7936     // determined while the class was being declared, force a declaration
7937     // of it now.
7938     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7939         ClassDecl->hasInheritedConstructor())
7940       DeclareImplicitCopyConstructor(ClassDecl);
7941     // For the MS ABI we need to know whether the copy ctor is deleted. A
7942     // prerequisite for deleting the implicit copy ctor is that the class has a
7943     // move ctor or move assignment that is either user-declared or whose
7944     // semantics are inherited from a subobject. FIXME: We should provide a more
7945     // direct way for CodeGen to ask whether the constructor was deleted.
7946     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7947              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7948               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7949               ClassDecl->hasUserDeclaredMoveAssignment() ||
7950               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7951       DeclareImplicitCopyConstructor(ClassDecl);
7952   }
7953 
7954   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7955     ++ASTContext::NumImplicitMoveConstructors;
7956 
7957     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7958         ClassDecl->hasInheritedConstructor())
7959       DeclareImplicitMoveConstructor(ClassDecl);
7960   }
7961 
7962   if (ClassDecl->needsImplicitCopyAssignment()) {
7963     ++ASTContext::NumImplicitCopyAssignmentOperators;
7964 
7965     // If we have a dynamic class, then the copy assignment operator may be
7966     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7967     // it shows up in the right place in the vtable and that we diagnose
7968     // problems with the implicit exception specification.
7969     if (ClassDecl->isDynamicClass() ||
7970         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7971         ClassDecl->hasInheritedAssignment())
7972       DeclareImplicitCopyAssignment(ClassDecl);
7973   }
7974 
7975   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7976     ++ASTContext::NumImplicitMoveAssignmentOperators;
7977 
7978     // Likewise for the move assignment operator.
7979     if (ClassDecl->isDynamicClass() ||
7980         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7981         ClassDecl->hasInheritedAssignment())
7982       DeclareImplicitMoveAssignment(ClassDecl);
7983   }
7984 
7985   if (ClassDecl->needsImplicitDestructor()) {
7986     ++ASTContext::NumImplicitDestructors;
7987 
7988     // If we have a dynamic class, then the destructor may be virtual, so we
7989     // have to declare the destructor immediately. This ensures that, e.g., it
7990     // shows up in the right place in the vtable and that we diagnose problems
7991     // with the implicit exception specification.
7992     if (ClassDecl->isDynamicClass() ||
7993         ClassDecl->needsOverloadResolutionForDestructor())
7994       DeclareImplicitDestructor(ClassDecl);
7995   }
7996 }
7997 
7998 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7999   if (!D)
8000     return 0;
8001 
8002   // The order of template parameters is not important here. All names
8003   // get added to the same scope.
8004   SmallVector<TemplateParameterList *, 4> ParameterLists;
8005 
8006   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8007     D = TD->getTemplatedDecl();
8008 
8009   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8010     ParameterLists.push_back(PSD->getTemplateParameters());
8011 
8012   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8013     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8014       ParameterLists.push_back(DD->getTemplateParameterList(i));
8015 
8016     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8017       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8018         ParameterLists.push_back(FTD->getTemplateParameters());
8019     }
8020   }
8021 
8022   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8023     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8024       ParameterLists.push_back(TD->getTemplateParameterList(i));
8025 
8026     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8027       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8028         ParameterLists.push_back(CTD->getTemplateParameters());
8029     }
8030   }
8031 
8032   unsigned Count = 0;
8033   for (TemplateParameterList *Params : ParameterLists) {
8034     if (Params->size() > 0)
8035       // Ignore explicit specializations; they don't contribute to the template
8036       // depth.
8037       ++Count;
8038     for (NamedDecl *Param : *Params) {
8039       if (Param->getDeclName()) {
8040         S->AddDecl(Param);
8041         IdResolver.AddDecl(Param);
8042       }
8043     }
8044   }
8045 
8046   return Count;
8047 }
8048 
8049 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8050   if (!RecordD) return;
8051   AdjustDeclIfTemplate(RecordD);
8052   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8053   PushDeclContext(S, Record);
8054 }
8055 
8056 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8057   if (!RecordD) return;
8058   PopDeclContext();
8059 }
8060 
8061 /// This is used to implement the constant expression evaluation part of the
8062 /// attribute enable_if extension. There is nothing in standard C++ which would
8063 /// require reentering parameters.
8064 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8065   if (!Param)
8066     return;
8067 
8068   S->AddDecl(Param);
8069   if (Param->getDeclName())
8070     IdResolver.AddDecl(Param);
8071 }
8072 
8073 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8074 /// parsing a top-level (non-nested) C++ class, and we are now
8075 /// parsing those parts of the given Method declaration that could
8076 /// not be parsed earlier (C++ [class.mem]p2), such as default
8077 /// arguments. This action should enter the scope of the given
8078 /// Method declaration as if we had just parsed the qualified method
8079 /// name. However, it should not bring the parameters into scope;
8080 /// that will be performed by ActOnDelayedCXXMethodParameter.
8081 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8082 }
8083 
8084 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8085 /// C++ method declaration. We're (re-)introducing the given
8086 /// function parameter into scope for use in parsing later parts of
8087 /// the method declaration. For example, we could see an
8088 /// ActOnParamDefaultArgument event for this parameter.
8089 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8090   if (!ParamD)
8091     return;
8092 
8093   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8094 
8095   // If this parameter has an unparsed default argument, clear it out
8096   // to make way for the parsed default argument.
8097   if (Param->hasUnparsedDefaultArg())
8098     Param->setDefaultArg(nullptr);
8099 
8100   S->AddDecl(Param);
8101   if (Param->getDeclName())
8102     IdResolver.AddDecl(Param);
8103 }
8104 
8105 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8106 /// processing the delayed method declaration for Method. The method
8107 /// declaration is now considered finished. There may be a separate
8108 /// ActOnStartOfFunctionDef action later (not necessarily
8109 /// immediately!) for this method, if it was also defined inside the
8110 /// class body.
8111 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8112   if (!MethodD)
8113     return;
8114 
8115   AdjustDeclIfTemplate(MethodD);
8116 
8117   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8118 
8119   // Now that we have our default arguments, check the constructor
8120   // again. It could produce additional diagnostics or affect whether
8121   // the class has implicitly-declared destructors, among other
8122   // things.
8123   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8124     CheckConstructor(Constructor);
8125 
8126   // Check the default arguments, which we may have added.
8127   if (!Method->isInvalidDecl())
8128     CheckCXXDefaultArguments(Method);
8129 }
8130 
8131 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8132 /// the well-formedness of the constructor declarator @p D with type @p
8133 /// R. If there are any errors in the declarator, this routine will
8134 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8135 /// will be updated to reflect a well-formed type for the constructor and
8136 /// returned.
8137 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8138                                           StorageClass &SC) {
8139   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8140 
8141   // C++ [class.ctor]p3:
8142   //   A constructor shall not be virtual (10.3) or static (9.4). A
8143   //   constructor can be invoked for a const, volatile or const
8144   //   volatile object. A constructor shall not be declared const,
8145   //   volatile, or const volatile (9.3.2).
8146   if (isVirtual) {
8147     if (!D.isInvalidType())
8148       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8149         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8150         << SourceRange(D.getIdentifierLoc());
8151     D.setInvalidType();
8152   }
8153   if (SC == SC_Static) {
8154     if (!D.isInvalidType())
8155       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8156         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8157         << SourceRange(D.getIdentifierLoc());
8158     D.setInvalidType();
8159     SC = SC_None;
8160   }
8161 
8162   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8163     diagnoseIgnoredQualifiers(
8164         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8165         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8166         D.getDeclSpec().getRestrictSpecLoc(),
8167         D.getDeclSpec().getAtomicSpecLoc());
8168     D.setInvalidType();
8169   }
8170 
8171   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8172   if (FTI.TypeQuals != 0) {
8173     if (FTI.TypeQuals & Qualifiers::Const)
8174       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8175         << "const" << SourceRange(D.getIdentifierLoc());
8176     if (FTI.TypeQuals & Qualifiers::Volatile)
8177       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8178         << "volatile" << SourceRange(D.getIdentifierLoc());
8179     if (FTI.TypeQuals & Qualifiers::Restrict)
8180       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8181         << "restrict" << SourceRange(D.getIdentifierLoc());
8182     D.setInvalidType();
8183   }
8184 
8185   // C++0x [class.ctor]p4:
8186   //   A constructor shall not be declared with a ref-qualifier.
8187   if (FTI.hasRefQualifier()) {
8188     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8189       << FTI.RefQualifierIsLValueRef
8190       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8191     D.setInvalidType();
8192   }
8193 
8194   // Rebuild the function type "R" without any type qualifiers (in
8195   // case any of the errors above fired) and with "void" as the
8196   // return type, since constructors don't have return types.
8197   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8198   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8199     return R;
8200 
8201   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8202   EPI.TypeQuals = 0;
8203   EPI.RefQualifier = RQ_None;
8204 
8205   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8206 }
8207 
8208 /// CheckConstructor - Checks a fully-formed constructor for
8209 /// well-formedness, issuing any diagnostics required. Returns true if
8210 /// the constructor declarator is invalid.
8211 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8212   CXXRecordDecl *ClassDecl
8213     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8214   if (!ClassDecl)
8215     return Constructor->setInvalidDecl();
8216 
8217   // C++ [class.copy]p3:
8218   //   A declaration of a constructor for a class X is ill-formed if
8219   //   its first parameter is of type (optionally cv-qualified) X and
8220   //   either there are no other parameters or else all other
8221   //   parameters have default arguments.
8222   if (!Constructor->isInvalidDecl() &&
8223       ((Constructor->getNumParams() == 1) ||
8224        (Constructor->getNumParams() > 1 &&
8225         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8226       Constructor->getTemplateSpecializationKind()
8227                                               != TSK_ImplicitInstantiation) {
8228     QualType ParamType = Constructor->getParamDecl(0)->getType();
8229     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8230     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8231       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8232       const char *ConstRef
8233         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8234                                                         : " const &";
8235       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8236         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8237 
8238       // FIXME: Rather that making the constructor invalid, we should endeavor
8239       // to fix the type.
8240       Constructor->setInvalidDecl();
8241     }
8242   }
8243 }
8244 
8245 /// CheckDestructor - Checks a fully-formed destructor definition for
8246 /// well-formedness, issuing any diagnostics required.  Returns true
8247 /// on error.
8248 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8249   CXXRecordDecl *RD = Destructor->getParent();
8250 
8251   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8252     SourceLocation Loc;
8253 
8254     if (!Destructor->isImplicit())
8255       Loc = Destructor->getLocation();
8256     else
8257       Loc = RD->getLocation();
8258 
8259     // If we have a virtual destructor, look up the deallocation function
8260     if (FunctionDecl *OperatorDelete =
8261             FindDeallocationFunctionForDestructor(Loc, RD)) {
8262       Expr *ThisArg = nullptr;
8263 
8264       // If the notional 'delete this' expression requires a non-trivial
8265       // conversion from 'this' to the type of a destroying operator delete's
8266       // first parameter, perform that conversion now.
8267       if (OperatorDelete->isDestroyingOperatorDelete()) {
8268         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8269         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8270           // C++ [class.dtor]p13:
8271           //   ... as if for the expression 'delete this' appearing in a
8272           //   non-virtual destructor of the destructor's class.
8273           ContextRAII SwitchContext(*this, Destructor);
8274           ExprResult This =
8275               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8276           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8277           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8278           if (This.isInvalid()) {
8279             // FIXME: Register this as a context note so that it comes out
8280             // in the right order.
8281             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8282             return true;
8283           }
8284           ThisArg = This.get();
8285         }
8286       }
8287 
8288       MarkFunctionReferenced(Loc, OperatorDelete);
8289       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8290     }
8291   }
8292 
8293   return false;
8294 }
8295 
8296 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8297 /// the well-formednes of the destructor declarator @p D with type @p
8298 /// R. If there are any errors in the declarator, this routine will
8299 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8300 /// will be updated to reflect a well-formed type for the destructor and
8301 /// returned.
8302 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8303                                          StorageClass& SC) {
8304   // C++ [class.dtor]p1:
8305   //   [...] A typedef-name that names a class is a class-name
8306   //   (7.1.3); however, a typedef-name that names a class shall not
8307   //   be used as the identifier in the declarator for a destructor
8308   //   declaration.
8309   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8310   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8311     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8312       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8313   else if (const TemplateSpecializationType *TST =
8314              DeclaratorType->getAs<TemplateSpecializationType>())
8315     if (TST->isTypeAlias())
8316       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8317         << DeclaratorType << 1;
8318 
8319   // C++ [class.dtor]p2:
8320   //   A destructor is used to destroy objects of its class type. A
8321   //   destructor takes no parameters, and no return type can be
8322   //   specified for it (not even void). The address of a destructor
8323   //   shall not be taken. A destructor shall not be static. A
8324   //   destructor can be invoked for a const, volatile or const
8325   //   volatile object. A destructor shall not be declared const,
8326   //   volatile or const volatile (9.3.2).
8327   if (SC == SC_Static) {
8328     if (!D.isInvalidType())
8329       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8330         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8331         << SourceRange(D.getIdentifierLoc())
8332         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8333 
8334     SC = SC_None;
8335   }
8336   if (!D.isInvalidType()) {
8337     // Destructors don't have return types, but the parser will
8338     // happily parse something like:
8339     //
8340     //   class X {
8341     //     float ~X();
8342     //   };
8343     //
8344     // The return type will be eliminated later.
8345     if (D.getDeclSpec().hasTypeSpecifier())
8346       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8347         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8348         << SourceRange(D.getIdentifierLoc());
8349     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8350       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8351                                 SourceLocation(),
8352                                 D.getDeclSpec().getConstSpecLoc(),
8353                                 D.getDeclSpec().getVolatileSpecLoc(),
8354                                 D.getDeclSpec().getRestrictSpecLoc(),
8355                                 D.getDeclSpec().getAtomicSpecLoc());
8356       D.setInvalidType();
8357     }
8358   }
8359 
8360   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8361   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8362     if (FTI.TypeQuals & Qualifiers::Const)
8363       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8364         << "const" << SourceRange(D.getIdentifierLoc());
8365     if (FTI.TypeQuals & Qualifiers::Volatile)
8366       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8367         << "volatile" << SourceRange(D.getIdentifierLoc());
8368     if (FTI.TypeQuals & Qualifiers::Restrict)
8369       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8370         << "restrict" << SourceRange(D.getIdentifierLoc());
8371     D.setInvalidType();
8372   }
8373 
8374   // C++0x [class.dtor]p2:
8375   //   A destructor shall not be declared with a ref-qualifier.
8376   if (FTI.hasRefQualifier()) {
8377     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8378       << FTI.RefQualifierIsLValueRef
8379       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8380     D.setInvalidType();
8381   }
8382 
8383   // Make sure we don't have any parameters.
8384   if (FTIHasNonVoidParameters(FTI)) {
8385     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8386 
8387     // Delete the parameters.
8388     FTI.freeParams();
8389     D.setInvalidType();
8390   }
8391 
8392   // Make sure the destructor isn't variadic.
8393   if (FTI.isVariadic) {
8394     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8395     D.setInvalidType();
8396   }
8397 
8398   // Rebuild the function type "R" without any type qualifiers or
8399   // parameters (in case any of the errors above fired) and with
8400   // "void" as the return type, since destructors don't have return
8401   // types.
8402   if (!D.isInvalidType())
8403     return R;
8404 
8405   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8406   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8407   EPI.Variadic = false;
8408   EPI.TypeQuals = 0;
8409   EPI.RefQualifier = RQ_None;
8410   return Context.getFunctionType(Context.VoidTy, None, EPI);
8411 }
8412 
8413 static void extendLeft(SourceRange &R, SourceRange Before) {
8414   if (Before.isInvalid())
8415     return;
8416   R.setBegin(Before.getBegin());
8417   if (R.getEnd().isInvalid())
8418     R.setEnd(Before.getEnd());
8419 }
8420 
8421 static void extendRight(SourceRange &R, SourceRange After) {
8422   if (After.isInvalid())
8423     return;
8424   if (R.getBegin().isInvalid())
8425     R.setBegin(After.getBegin());
8426   R.setEnd(After.getEnd());
8427 }
8428 
8429 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8430 /// well-formednes of the conversion function declarator @p D with
8431 /// type @p R. If there are any errors in the declarator, this routine
8432 /// will emit diagnostics and return true. Otherwise, it will return
8433 /// false. Either way, the type @p R will be updated to reflect a
8434 /// well-formed type for the conversion operator.
8435 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8436                                      StorageClass& SC) {
8437   // C++ [class.conv.fct]p1:
8438   //   Neither parameter types nor return type can be specified. The
8439   //   type of a conversion function (8.3.5) is "function taking no
8440   //   parameter returning conversion-type-id."
8441   if (SC == SC_Static) {
8442     if (!D.isInvalidType())
8443       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8444         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8445         << D.getName().getSourceRange();
8446     D.setInvalidType();
8447     SC = SC_None;
8448   }
8449 
8450   TypeSourceInfo *ConvTSI = nullptr;
8451   QualType ConvType =
8452       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8453 
8454   const DeclSpec &DS = D.getDeclSpec();
8455   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8456     // Conversion functions don't have return types, but the parser will
8457     // happily parse something like:
8458     //
8459     //   class X {
8460     //     float operator bool();
8461     //   };
8462     //
8463     // The return type will be changed later anyway.
8464     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8465       << SourceRange(DS.getTypeSpecTypeLoc())
8466       << SourceRange(D.getIdentifierLoc());
8467     D.setInvalidType();
8468   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8469     // It's also plausible that the user writes type qualifiers in the wrong
8470     // place, such as:
8471     //   struct S { const operator int(); };
8472     // FIXME: we could provide a fixit to move the qualifiers onto the
8473     // conversion type.
8474     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8475         << SourceRange(D.getIdentifierLoc()) << 0;
8476     D.setInvalidType();
8477   }
8478 
8479   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8480 
8481   // Make sure we don't have any parameters.
8482   if (Proto->getNumParams() > 0) {
8483     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8484 
8485     // Delete the parameters.
8486     D.getFunctionTypeInfo().freeParams();
8487     D.setInvalidType();
8488   } else if (Proto->isVariadic()) {
8489     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8490     D.setInvalidType();
8491   }
8492 
8493   // Diagnose "&operator bool()" and other such nonsense.  This
8494   // is actually a gcc extension which we don't support.
8495   if (Proto->getReturnType() != ConvType) {
8496     bool NeedsTypedef = false;
8497     SourceRange Before, After;
8498 
8499     // Walk the chunks and extract information on them for our diagnostic.
8500     bool PastFunctionChunk = false;
8501     for (auto &Chunk : D.type_objects()) {
8502       switch (Chunk.Kind) {
8503       case DeclaratorChunk::Function:
8504         if (!PastFunctionChunk) {
8505           if (Chunk.Fun.HasTrailingReturnType) {
8506             TypeSourceInfo *TRT = nullptr;
8507             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8508             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8509           }
8510           PastFunctionChunk = true;
8511           break;
8512         }
8513         LLVM_FALLTHROUGH;
8514       case DeclaratorChunk::Array:
8515         NeedsTypedef = true;
8516         extendRight(After, Chunk.getSourceRange());
8517         break;
8518 
8519       case DeclaratorChunk::Pointer:
8520       case DeclaratorChunk::BlockPointer:
8521       case DeclaratorChunk::Reference:
8522       case DeclaratorChunk::MemberPointer:
8523       case DeclaratorChunk::Pipe:
8524         extendLeft(Before, Chunk.getSourceRange());
8525         break;
8526 
8527       case DeclaratorChunk::Paren:
8528         extendLeft(Before, Chunk.Loc);
8529         extendRight(After, Chunk.EndLoc);
8530         break;
8531       }
8532     }
8533 
8534     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8535                          After.isValid()  ? After.getBegin() :
8536                                             D.getIdentifierLoc();
8537     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8538     DB << Before << After;
8539 
8540     if (!NeedsTypedef) {
8541       DB << /*don't need a typedef*/0;
8542 
8543       // If we can provide a correct fix-it hint, do so.
8544       if (After.isInvalid() && ConvTSI) {
8545         SourceLocation InsertLoc =
8546             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8547         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8548            << FixItHint::CreateInsertionFromRange(
8549                   InsertLoc, CharSourceRange::getTokenRange(Before))
8550            << FixItHint::CreateRemoval(Before);
8551       }
8552     } else if (!Proto->getReturnType()->isDependentType()) {
8553       DB << /*typedef*/1 << Proto->getReturnType();
8554     } else if (getLangOpts().CPlusPlus11) {
8555       DB << /*alias template*/2 << Proto->getReturnType();
8556     } else {
8557       DB << /*might not be fixable*/3;
8558     }
8559 
8560     // Recover by incorporating the other type chunks into the result type.
8561     // Note, this does *not* change the name of the function. This is compatible
8562     // with the GCC extension:
8563     //   struct S { &operator int(); } s;
8564     //   int &r = s.operator int(); // ok in GCC
8565     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8566     ConvType = Proto->getReturnType();
8567   }
8568 
8569   // C++ [class.conv.fct]p4:
8570   //   The conversion-type-id shall not represent a function type nor
8571   //   an array type.
8572   if (ConvType->isArrayType()) {
8573     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8574     ConvType = Context.getPointerType(ConvType);
8575     D.setInvalidType();
8576   } else if (ConvType->isFunctionType()) {
8577     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8578     ConvType = Context.getPointerType(ConvType);
8579     D.setInvalidType();
8580   }
8581 
8582   // Rebuild the function type "R" without any parameters (in case any
8583   // of the errors above fired) and with the conversion type as the
8584   // return type.
8585   if (D.isInvalidType())
8586     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8587 
8588   // C++0x explicit conversion operators.
8589   if (DS.isExplicitSpecified())
8590     Diag(DS.getExplicitSpecLoc(),
8591          getLangOpts().CPlusPlus11
8592              ? diag::warn_cxx98_compat_explicit_conversion_functions
8593              : diag::ext_explicit_conversion_functions)
8594         << SourceRange(DS.getExplicitSpecLoc());
8595 }
8596 
8597 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8598 /// the declaration of the given C++ conversion function. This routine
8599 /// is responsible for recording the conversion function in the C++
8600 /// class, if possible.
8601 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8602   assert(Conversion && "Expected to receive a conversion function declaration");
8603 
8604   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8605 
8606   // Make sure we aren't redeclaring the conversion function.
8607   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8608 
8609   // C++ [class.conv.fct]p1:
8610   //   [...] A conversion function is never used to convert a
8611   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8612   //   same object type (or a reference to it), to a (possibly
8613   //   cv-qualified) base class of that type (or a reference to it),
8614   //   or to (possibly cv-qualified) void.
8615   // FIXME: Suppress this warning if the conversion function ends up being a
8616   // virtual function that overrides a virtual function in a base class.
8617   QualType ClassType
8618     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8619   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8620     ConvType = ConvTypeRef->getPointeeType();
8621   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8622       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8623     /* Suppress diagnostics for instantiations. */;
8624   else if (ConvType->isRecordType()) {
8625     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8626     if (ConvType == ClassType)
8627       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8628         << ClassType;
8629     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8630       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8631         <<  ClassType << ConvType;
8632   } else if (ConvType->isVoidType()) {
8633     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8634       << ClassType << ConvType;
8635   }
8636 
8637   if (FunctionTemplateDecl *ConversionTemplate
8638                                 = Conversion->getDescribedFunctionTemplate())
8639     return ConversionTemplate;
8640 
8641   return Conversion;
8642 }
8643 
8644 namespace {
8645 /// Utility class to accumulate and print a diagnostic listing the invalid
8646 /// specifier(s) on a declaration.
8647 struct BadSpecifierDiagnoser {
8648   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8649       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8650   ~BadSpecifierDiagnoser() {
8651     Diagnostic << Specifiers;
8652   }
8653 
8654   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8655     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8656   }
8657   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8658     return check(SpecLoc,
8659                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8660   }
8661   void check(SourceLocation SpecLoc, const char *Spec) {
8662     if (SpecLoc.isInvalid()) return;
8663     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8664     if (!Specifiers.empty()) Specifiers += " ";
8665     Specifiers += Spec;
8666   }
8667 
8668   Sema &S;
8669   Sema::SemaDiagnosticBuilder Diagnostic;
8670   std::string Specifiers;
8671 };
8672 }
8673 
8674 /// Check the validity of a declarator that we parsed for a deduction-guide.
8675 /// These aren't actually declarators in the grammar, so we need to check that
8676 /// the user didn't specify any pieces that are not part of the deduction-guide
8677 /// grammar.
8678 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8679                                          StorageClass &SC) {
8680   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8681   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8682   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8683 
8684   // C++ [temp.deduct.guide]p3:
8685   //   A deduction-gide shall be declared in the same scope as the
8686   //   corresponding class template.
8687   if (!CurContext->getRedeclContext()->Equals(
8688           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8689     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8690       << GuidedTemplateDecl;
8691     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8692   }
8693 
8694   auto &DS = D.getMutableDeclSpec();
8695   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8696   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8697       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8698       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8699     BadSpecifierDiagnoser Diagnoser(
8700         *this, D.getIdentifierLoc(),
8701         diag::err_deduction_guide_invalid_specifier);
8702 
8703     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8704     DS.ClearStorageClassSpecs();
8705     SC = SC_None;
8706 
8707     // 'explicit' is permitted.
8708     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8709     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8710     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8711     DS.ClearConstexprSpec();
8712 
8713     Diagnoser.check(DS.getConstSpecLoc(), "const");
8714     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8715     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8716     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8717     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8718     DS.ClearTypeQualifiers();
8719 
8720     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8721     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8722     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8723     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8724     DS.ClearTypeSpecType();
8725   }
8726 
8727   if (D.isInvalidType())
8728     return;
8729 
8730   // Check the declarator is simple enough.
8731   bool FoundFunction = false;
8732   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8733     if (Chunk.Kind == DeclaratorChunk::Paren)
8734       continue;
8735     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8736       Diag(D.getDeclSpec().getBeginLoc(),
8737            diag::err_deduction_guide_with_complex_decl)
8738           << D.getSourceRange();
8739       break;
8740     }
8741     if (!Chunk.Fun.hasTrailingReturnType()) {
8742       Diag(D.getName().getBeginLoc(),
8743            diag::err_deduction_guide_no_trailing_return_type);
8744       break;
8745     }
8746 
8747     // Check that the return type is written as a specialization of
8748     // the template specified as the deduction-guide's name.
8749     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8750     TypeSourceInfo *TSI = nullptr;
8751     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8752     assert(TSI && "deduction guide has valid type but invalid return type?");
8753     bool AcceptableReturnType = false;
8754     bool MightInstantiateToSpecialization = false;
8755     if (auto RetTST =
8756             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8757       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8758       bool TemplateMatches =
8759           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8760       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8761         AcceptableReturnType = true;
8762       else {
8763         // This could still instantiate to the right type, unless we know it
8764         // names the wrong class template.
8765         auto *TD = SpecifiedName.getAsTemplateDecl();
8766         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8767                                              !TemplateMatches);
8768       }
8769     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8770       MightInstantiateToSpecialization = true;
8771     }
8772 
8773     if (!AcceptableReturnType) {
8774       Diag(TSI->getTypeLoc().getBeginLoc(),
8775            diag::err_deduction_guide_bad_trailing_return_type)
8776           << GuidedTemplate << TSI->getType()
8777           << MightInstantiateToSpecialization
8778           << TSI->getTypeLoc().getSourceRange();
8779     }
8780 
8781     // Keep going to check that we don't have any inner declarator pieces (we
8782     // could still have a function returning a pointer to a function).
8783     FoundFunction = true;
8784   }
8785 
8786   if (D.isFunctionDefinition())
8787     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8788 }
8789 
8790 //===----------------------------------------------------------------------===//
8791 // Namespace Handling
8792 //===----------------------------------------------------------------------===//
8793 
8794 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8795 /// reopened.
8796 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8797                                             SourceLocation Loc,
8798                                             IdentifierInfo *II, bool *IsInline,
8799                                             NamespaceDecl *PrevNS) {
8800   assert(*IsInline != PrevNS->isInline());
8801 
8802   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8803   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8804   // inline namespaces, with the intention of bringing names into namespace std.
8805   //
8806   // We support this just well enough to get that case working; this is not
8807   // sufficient to support reopening namespaces as inline in general.
8808   if (*IsInline && II && II->getName().startswith("__atomic") &&
8809       S.getSourceManager().isInSystemHeader(Loc)) {
8810     // Mark all prior declarations of the namespace as inline.
8811     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8812          NS = NS->getPreviousDecl())
8813       NS->setInline(*IsInline);
8814     // Patch up the lookup table for the containing namespace. This isn't really
8815     // correct, but it's good enough for this particular case.
8816     for (auto *I : PrevNS->decls())
8817       if (auto *ND = dyn_cast<NamedDecl>(I))
8818         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8819     return;
8820   }
8821 
8822   if (PrevNS->isInline())
8823     // The user probably just forgot the 'inline', so suggest that it
8824     // be added back.
8825     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8826       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8827   else
8828     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8829 
8830   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8831   *IsInline = PrevNS->isInline();
8832 }
8833 
8834 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8835 /// definition.
8836 Decl *Sema::ActOnStartNamespaceDef(
8837     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8838     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8839     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8840   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8841   // For anonymous namespace, take the location of the left brace.
8842   SourceLocation Loc = II ? IdentLoc : LBrace;
8843   bool IsInline = InlineLoc.isValid();
8844   bool IsInvalid = false;
8845   bool IsStd = false;
8846   bool AddToKnown = false;
8847   Scope *DeclRegionScope = NamespcScope->getParent();
8848 
8849   NamespaceDecl *PrevNS = nullptr;
8850   if (II) {
8851     // C++ [namespace.def]p2:
8852     //   The identifier in an original-namespace-definition shall not
8853     //   have been previously defined in the declarative region in
8854     //   which the original-namespace-definition appears. The
8855     //   identifier in an original-namespace-definition is the name of
8856     //   the namespace. Subsequently in that declarative region, it is
8857     //   treated as an original-namespace-name.
8858     //
8859     // Since namespace names are unique in their scope, and we don't
8860     // look through using directives, just look for any ordinary names
8861     // as if by qualified name lookup.
8862     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8863                    ForExternalRedeclaration);
8864     LookupQualifiedName(R, CurContext->getRedeclContext());
8865     NamedDecl *PrevDecl =
8866         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8867     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8868 
8869     if (PrevNS) {
8870       // This is an extended namespace definition.
8871       if (IsInline != PrevNS->isInline())
8872         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8873                                         &IsInline, PrevNS);
8874     } else if (PrevDecl) {
8875       // This is an invalid name redefinition.
8876       Diag(Loc, diag::err_redefinition_different_kind)
8877         << II;
8878       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8879       IsInvalid = true;
8880       // Continue on to push Namespc as current DeclContext and return it.
8881     } else if (II->isStr("std") &&
8882                CurContext->getRedeclContext()->isTranslationUnit()) {
8883       // This is the first "real" definition of the namespace "std", so update
8884       // our cache of the "std" namespace to point at this definition.
8885       PrevNS = getStdNamespace();
8886       IsStd = true;
8887       AddToKnown = !IsInline;
8888     } else {
8889       // We've seen this namespace for the first time.
8890       AddToKnown = !IsInline;
8891     }
8892   } else {
8893     // Anonymous namespaces.
8894 
8895     // Determine whether the parent already has an anonymous namespace.
8896     DeclContext *Parent = CurContext->getRedeclContext();
8897     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8898       PrevNS = TU->getAnonymousNamespace();
8899     } else {
8900       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8901       PrevNS = ND->getAnonymousNamespace();
8902     }
8903 
8904     if (PrevNS && IsInline != PrevNS->isInline())
8905       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8906                                       &IsInline, PrevNS);
8907   }
8908 
8909   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8910                                                  StartLoc, Loc, II, PrevNS);
8911   if (IsInvalid)
8912     Namespc->setInvalidDecl();
8913 
8914   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8915   AddPragmaAttributes(DeclRegionScope, Namespc);
8916 
8917   // FIXME: Should we be merging attributes?
8918   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8919     PushNamespaceVisibilityAttr(Attr, Loc);
8920 
8921   if (IsStd)
8922     StdNamespace = Namespc;
8923   if (AddToKnown)
8924     KnownNamespaces[Namespc] = false;
8925 
8926   if (II) {
8927     PushOnScopeChains(Namespc, DeclRegionScope);
8928   } else {
8929     // Link the anonymous namespace into its parent.
8930     DeclContext *Parent = CurContext->getRedeclContext();
8931     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8932       TU->setAnonymousNamespace(Namespc);
8933     } else {
8934       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8935     }
8936 
8937     CurContext->addDecl(Namespc);
8938 
8939     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8940     //   behaves as if it were replaced by
8941     //     namespace unique { /* empty body */ }
8942     //     using namespace unique;
8943     //     namespace unique { namespace-body }
8944     //   where all occurrences of 'unique' in a translation unit are
8945     //   replaced by the same identifier and this identifier differs
8946     //   from all other identifiers in the entire program.
8947 
8948     // We just create the namespace with an empty name and then add an
8949     // implicit using declaration, just like the standard suggests.
8950     //
8951     // CodeGen enforces the "universally unique" aspect by giving all
8952     // declarations semantically contained within an anonymous
8953     // namespace internal linkage.
8954 
8955     if (!PrevNS) {
8956       UD = UsingDirectiveDecl::Create(Context, Parent,
8957                                       /* 'using' */ LBrace,
8958                                       /* 'namespace' */ SourceLocation(),
8959                                       /* qualifier */ NestedNameSpecifierLoc(),
8960                                       /* identifier */ SourceLocation(),
8961                                       Namespc,
8962                                       /* Ancestor */ Parent);
8963       UD->setImplicit();
8964       Parent->addDecl(UD);
8965     }
8966   }
8967 
8968   ActOnDocumentableDecl(Namespc);
8969 
8970   // Although we could have an invalid decl (i.e. the namespace name is a
8971   // redefinition), push it as current DeclContext and try to continue parsing.
8972   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8973   // for the namespace has the declarations that showed up in that particular
8974   // namespace definition.
8975   PushDeclContext(NamespcScope, Namespc);
8976   return Namespc;
8977 }
8978 
8979 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8980 /// is a namespace alias, returns the namespace it points to.
8981 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8982   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8983     return AD->getNamespace();
8984   return dyn_cast_or_null<NamespaceDecl>(D);
8985 }
8986 
8987 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8988 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8989 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8990   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8991   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8992   Namespc->setRBraceLoc(RBrace);
8993   PopDeclContext();
8994   if (Namespc->hasAttr<VisibilityAttr>())
8995     PopPragmaVisibility(true, RBrace);
8996 }
8997 
8998 CXXRecordDecl *Sema::getStdBadAlloc() const {
8999   return cast_or_null<CXXRecordDecl>(
9000                                   StdBadAlloc.get(Context.getExternalSource()));
9001 }
9002 
9003 EnumDecl *Sema::getStdAlignValT() const {
9004   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9005 }
9006 
9007 NamespaceDecl *Sema::getStdNamespace() const {
9008   return cast_or_null<NamespaceDecl>(
9009                                  StdNamespace.get(Context.getExternalSource()));
9010 }
9011 
9012 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9013   if (!StdExperimentalNamespaceCache) {
9014     if (auto Std = getStdNamespace()) {
9015       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9016                           SourceLocation(), LookupNamespaceName);
9017       if (!LookupQualifiedName(Result, Std) ||
9018           !(StdExperimentalNamespaceCache =
9019                 Result.getAsSingle<NamespaceDecl>()))
9020         Result.suppressDiagnostics();
9021     }
9022   }
9023   return StdExperimentalNamespaceCache;
9024 }
9025 
9026 namespace {
9027 
9028 enum UnsupportedSTLSelect {
9029   USS_InvalidMember,
9030   USS_MissingMember,
9031   USS_NonTrivial,
9032   USS_Other
9033 };
9034 
9035 struct InvalidSTLDiagnoser {
9036   Sema &S;
9037   SourceLocation Loc;
9038   QualType TyForDiags;
9039 
9040   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9041                       const VarDecl *VD = nullptr) {
9042     {
9043       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9044                << TyForDiags << ((int)Sel);
9045       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9046         assert(!Name.empty());
9047         D << Name;
9048       }
9049     }
9050     if (Sel == USS_InvalidMember) {
9051       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9052           << VD << VD->getSourceRange();
9053     }
9054     return QualType();
9055   }
9056 };
9057 } // namespace
9058 
9059 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9060                                            SourceLocation Loc) {
9061   assert(getLangOpts().CPlusPlus &&
9062          "Looking for comparison category type outside of C++.");
9063 
9064   // Check if we've already successfully checked the comparison category type
9065   // before. If so, skip checking it again.
9066   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9067   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9068     return Info->getType();
9069 
9070   // If lookup failed
9071   if (!Info) {
9072     std::string NameForDiags = "std::";
9073     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9074     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9075         << NameForDiags;
9076     return QualType();
9077   }
9078 
9079   assert(Info->Kind == Kind);
9080   assert(Info->Record);
9081 
9082   // Update the Record decl in case we encountered a forward declaration on our
9083   // first pass. FIXME: This is a bit of a hack.
9084   if (Info->Record->hasDefinition())
9085     Info->Record = Info->Record->getDefinition();
9086 
9087   // Use an elaborated type for diagnostics which has a name containing the
9088   // prepended 'std' namespace but not any inline namespace names.
9089   QualType TyForDiags = [&]() {
9090     auto *NNS =
9091         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9092     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9093   }();
9094 
9095   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9096     return QualType();
9097 
9098   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9099 
9100   if (!Info->Record->isTriviallyCopyable())
9101     return UnsupportedSTLError(USS_NonTrivial);
9102 
9103   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9104     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9105     // Tolerate empty base classes.
9106     if (Base->isEmpty())
9107       continue;
9108     // Reject STL implementations which have at least one non-empty base.
9109     return UnsupportedSTLError();
9110   }
9111 
9112   // Check that the STL has implemented the types using a single integer field.
9113   // This expectation allows better codegen for builtin operators. We require:
9114   //   (1) The class has exactly one field.
9115   //   (2) The field is an integral or enumeration type.
9116   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9117   if (std::distance(FIt, FEnd) != 1 ||
9118       !FIt->getType()->isIntegralOrEnumerationType()) {
9119     return UnsupportedSTLError();
9120   }
9121 
9122   // Build each of the require values and store them in Info.
9123   for (ComparisonCategoryResult CCR :
9124        ComparisonCategories::getPossibleResultsForType(Kind)) {
9125     StringRef MemName = ComparisonCategories::getResultString(CCR);
9126     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9127 
9128     if (!ValInfo)
9129       return UnsupportedSTLError(USS_MissingMember, MemName);
9130 
9131     VarDecl *VD = ValInfo->VD;
9132     assert(VD && "should not be null!");
9133 
9134     // Attempt to diagnose reasons why the STL definition of this type
9135     // might be foobar, including it failing to be a constant expression.
9136     // TODO Handle more ways the lookup or result can be invalid.
9137     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9138         !VD->checkInitIsICE())
9139       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9140 
9141     // Attempt to evaluate the var decl as a constant expression and extract
9142     // the value of its first field as a ICE. If this fails, the STL
9143     // implementation is not supported.
9144     if (!ValInfo->hasValidIntValue())
9145       return UnsupportedSTLError();
9146 
9147     MarkVariableReferenced(Loc, VD);
9148   }
9149 
9150   // We've successfully built the required types and expressions. Update
9151   // the cache and return the newly cached value.
9152   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9153   return Info->getType();
9154 }
9155 
9156 /// Retrieve the special "std" namespace, which may require us to
9157 /// implicitly define the namespace.
9158 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9159   if (!StdNamespace) {
9160     // The "std" namespace has not yet been defined, so build one implicitly.
9161     StdNamespace = NamespaceDecl::Create(Context,
9162                                          Context.getTranslationUnitDecl(),
9163                                          /*Inline=*/false,
9164                                          SourceLocation(), SourceLocation(),
9165                                          &PP.getIdentifierTable().get("std"),
9166                                          /*PrevDecl=*/nullptr);
9167     getStdNamespace()->setImplicit(true);
9168   }
9169 
9170   return getStdNamespace();
9171 }
9172 
9173 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9174   assert(getLangOpts().CPlusPlus &&
9175          "Looking for std::initializer_list outside of C++.");
9176 
9177   // We're looking for implicit instantiations of
9178   // template <typename E> class std::initializer_list.
9179 
9180   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9181     return false;
9182 
9183   ClassTemplateDecl *Template = nullptr;
9184   const TemplateArgument *Arguments = nullptr;
9185 
9186   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9187 
9188     ClassTemplateSpecializationDecl *Specialization =
9189         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9190     if (!Specialization)
9191       return false;
9192 
9193     Template = Specialization->getSpecializedTemplate();
9194     Arguments = Specialization->getTemplateArgs().data();
9195   } else if (const TemplateSpecializationType *TST =
9196                  Ty->getAs<TemplateSpecializationType>()) {
9197     Template = dyn_cast_or_null<ClassTemplateDecl>(
9198         TST->getTemplateName().getAsTemplateDecl());
9199     Arguments = TST->getArgs();
9200   }
9201   if (!Template)
9202     return false;
9203 
9204   if (!StdInitializerList) {
9205     // Haven't recognized std::initializer_list yet, maybe this is it.
9206     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9207     if (TemplateClass->getIdentifier() !=
9208             &PP.getIdentifierTable().get("initializer_list") ||
9209         !getStdNamespace()->InEnclosingNamespaceSetOf(
9210             TemplateClass->getDeclContext()))
9211       return false;
9212     // This is a template called std::initializer_list, but is it the right
9213     // template?
9214     TemplateParameterList *Params = Template->getTemplateParameters();
9215     if (Params->getMinRequiredArguments() != 1)
9216       return false;
9217     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9218       return false;
9219 
9220     // It's the right template.
9221     StdInitializerList = Template;
9222   }
9223 
9224   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9225     return false;
9226 
9227   // This is an instance of std::initializer_list. Find the argument type.
9228   if (Element)
9229     *Element = Arguments[0].getAsType();
9230   return true;
9231 }
9232 
9233 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9234   NamespaceDecl *Std = S.getStdNamespace();
9235   if (!Std) {
9236     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9237     return nullptr;
9238   }
9239 
9240   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9241                       Loc, Sema::LookupOrdinaryName);
9242   if (!S.LookupQualifiedName(Result, Std)) {
9243     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9244     return nullptr;
9245   }
9246   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9247   if (!Template) {
9248     Result.suppressDiagnostics();
9249     // We found something weird. Complain about the first thing we found.
9250     NamedDecl *Found = *Result.begin();
9251     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9252     return nullptr;
9253   }
9254 
9255   // We found some template called std::initializer_list. Now verify that it's
9256   // correct.
9257   TemplateParameterList *Params = Template->getTemplateParameters();
9258   if (Params->getMinRequiredArguments() != 1 ||
9259       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9260     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9261     return nullptr;
9262   }
9263 
9264   return Template;
9265 }
9266 
9267 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9268   if (!StdInitializerList) {
9269     StdInitializerList = LookupStdInitializerList(*this, Loc);
9270     if (!StdInitializerList)
9271       return QualType();
9272   }
9273 
9274   TemplateArgumentListInfo Args(Loc, Loc);
9275   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9276                                        Context.getTrivialTypeSourceInfo(Element,
9277                                                                         Loc)));
9278   return Context.getCanonicalType(
9279       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9280 }
9281 
9282 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9283   // C++ [dcl.init.list]p2:
9284   //   A constructor is an initializer-list constructor if its first parameter
9285   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9286   //   std::initializer_list<E> for some type E, and either there are no other
9287   //   parameters or else all other parameters have default arguments.
9288   if (Ctor->getNumParams() < 1 ||
9289       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9290     return false;
9291 
9292   QualType ArgType = Ctor->getParamDecl(0)->getType();
9293   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9294     ArgType = RT->getPointeeType().getUnqualifiedType();
9295 
9296   return isStdInitializerList(ArgType, nullptr);
9297 }
9298 
9299 /// Determine whether a using statement is in a context where it will be
9300 /// apply in all contexts.
9301 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9302   switch (CurContext->getDeclKind()) {
9303     case Decl::TranslationUnit:
9304       return true;
9305     case Decl::LinkageSpec:
9306       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9307     default:
9308       return false;
9309   }
9310 }
9311 
9312 namespace {
9313 
9314 // Callback to only accept typo corrections that are namespaces.
9315 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9316 public:
9317   bool ValidateCandidate(const TypoCorrection &candidate) override {
9318     if (NamedDecl *ND = candidate.getCorrectionDecl())
9319       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9320     return false;
9321   }
9322 };
9323 
9324 }
9325 
9326 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9327                                        CXXScopeSpec &SS,
9328                                        SourceLocation IdentLoc,
9329                                        IdentifierInfo *Ident) {
9330   R.clear();
9331   if (TypoCorrection Corrected =
9332           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9333                         llvm::make_unique<NamespaceValidatorCCC>(),
9334                         Sema::CTK_ErrorRecovery)) {
9335     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9336       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9337       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9338                               Ident->getName().equals(CorrectedStr);
9339       S.diagnoseTypo(Corrected,
9340                      S.PDiag(diag::err_using_directive_member_suggest)
9341                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9342                      S.PDiag(diag::note_namespace_defined_here));
9343     } else {
9344       S.diagnoseTypo(Corrected,
9345                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9346                      S.PDiag(diag::note_namespace_defined_here));
9347     }
9348     R.addDecl(Corrected.getFoundDecl());
9349     return true;
9350   }
9351   return false;
9352 }
9353 
9354 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9355                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9356                                 SourceLocation IdentLoc,
9357                                 IdentifierInfo *NamespcName,
9358                                 const ParsedAttributesView &AttrList) {
9359   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9360   assert(NamespcName && "Invalid NamespcName.");
9361   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9362 
9363   // This can only happen along a recovery path.
9364   while (S->isTemplateParamScope())
9365     S = S->getParent();
9366   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9367 
9368   UsingDirectiveDecl *UDir = nullptr;
9369   NestedNameSpecifier *Qualifier = nullptr;
9370   if (SS.isSet())
9371     Qualifier = SS.getScopeRep();
9372 
9373   // Lookup namespace name.
9374   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9375   LookupParsedName(R, S, &SS);
9376   if (R.isAmbiguous())
9377     return nullptr;
9378 
9379   if (R.empty()) {
9380     R.clear();
9381     // Allow "using namespace std;" or "using namespace ::std;" even if
9382     // "std" hasn't been defined yet, for GCC compatibility.
9383     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9384         NamespcName->isStr("std")) {
9385       Diag(IdentLoc, diag::ext_using_undefined_std);
9386       R.addDecl(getOrCreateStdNamespace());
9387       R.resolveKind();
9388     }
9389     // Otherwise, attempt typo correction.
9390     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9391   }
9392 
9393   if (!R.empty()) {
9394     NamedDecl *Named = R.getRepresentativeDecl();
9395     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9396     assert(NS && "expected namespace decl");
9397 
9398     // The use of a nested name specifier may trigger deprecation warnings.
9399     DiagnoseUseOfDecl(Named, IdentLoc);
9400 
9401     // C++ [namespace.udir]p1:
9402     //   A using-directive specifies that the names in the nominated
9403     //   namespace can be used in the scope in which the
9404     //   using-directive appears after the using-directive. During
9405     //   unqualified name lookup (3.4.1), the names appear as if they
9406     //   were declared in the nearest enclosing namespace which
9407     //   contains both the using-directive and the nominated
9408     //   namespace. [Note: in this context, "contains" means "contains
9409     //   directly or indirectly". ]
9410 
9411     // Find enclosing context containing both using-directive and
9412     // nominated namespace.
9413     DeclContext *CommonAncestor = NS;
9414     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9415       CommonAncestor = CommonAncestor->getParent();
9416 
9417     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9418                                       SS.getWithLocInContext(Context),
9419                                       IdentLoc, Named, CommonAncestor);
9420 
9421     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9422         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9423       Diag(IdentLoc, diag::warn_using_directive_in_header);
9424     }
9425 
9426     PushUsingDirective(S, UDir);
9427   } else {
9428     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9429   }
9430 
9431   if (UDir)
9432     ProcessDeclAttributeList(S, UDir, AttrList);
9433 
9434   return UDir;
9435 }
9436 
9437 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9438   // If the scope has an associated entity and the using directive is at
9439   // namespace or translation unit scope, add the UsingDirectiveDecl into
9440   // its lookup structure so qualified name lookup can find it.
9441   DeclContext *Ctx = S->getEntity();
9442   if (Ctx && !Ctx->isFunctionOrMethod())
9443     Ctx->addDecl(UDir);
9444   else
9445     // Otherwise, it is at block scope. The using-directives will affect lookup
9446     // only to the end of the scope.
9447     S->PushUsingDirective(UDir);
9448 }
9449 
9450 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9451                                   SourceLocation UsingLoc,
9452                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9453                                   UnqualifiedId &Name,
9454                                   SourceLocation EllipsisLoc,
9455                                   const ParsedAttributesView &AttrList) {
9456   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9457 
9458   if (SS.isEmpty()) {
9459     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9460     return nullptr;
9461   }
9462 
9463   switch (Name.getKind()) {
9464   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9465   case UnqualifiedIdKind::IK_Identifier:
9466   case UnqualifiedIdKind::IK_OperatorFunctionId:
9467   case UnqualifiedIdKind::IK_LiteralOperatorId:
9468   case UnqualifiedIdKind::IK_ConversionFunctionId:
9469     break;
9470 
9471   case UnqualifiedIdKind::IK_ConstructorName:
9472   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9473     // C++11 inheriting constructors.
9474     Diag(Name.getBeginLoc(),
9475          getLangOpts().CPlusPlus11
9476              ? diag::warn_cxx98_compat_using_decl_constructor
9477              : diag::err_using_decl_constructor)
9478         << SS.getRange();
9479 
9480     if (getLangOpts().CPlusPlus11) break;
9481 
9482     return nullptr;
9483 
9484   case UnqualifiedIdKind::IK_DestructorName:
9485     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9486     return nullptr;
9487 
9488   case UnqualifiedIdKind::IK_TemplateId:
9489     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9490         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9491     return nullptr;
9492 
9493   case UnqualifiedIdKind::IK_DeductionGuideName:
9494     llvm_unreachable("cannot parse qualified deduction guide name");
9495   }
9496 
9497   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9498   DeclarationName TargetName = TargetNameInfo.getName();
9499   if (!TargetName)
9500     return nullptr;
9501 
9502   // Warn about access declarations.
9503   if (UsingLoc.isInvalid()) {
9504     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9505                                  ? diag::err_access_decl
9506                                  : diag::warn_access_decl_deprecated)
9507         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9508   }
9509 
9510   if (EllipsisLoc.isInvalid()) {
9511     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9512         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9513       return nullptr;
9514   } else {
9515     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9516         !TargetNameInfo.containsUnexpandedParameterPack()) {
9517       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9518         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9519       EllipsisLoc = SourceLocation();
9520     }
9521   }
9522 
9523   NamedDecl *UD =
9524       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9525                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9526                             /*IsInstantiation*/false);
9527   if (UD)
9528     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9529 
9530   return UD;
9531 }
9532 
9533 /// Determine whether a using declaration considers the given
9534 /// declarations as "equivalent", e.g., if they are redeclarations of
9535 /// the same entity or are both typedefs of the same type.
9536 static bool
9537 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9538   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9539     return true;
9540 
9541   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9542     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9543       return Context.hasSameType(TD1->getUnderlyingType(),
9544                                  TD2->getUnderlyingType());
9545 
9546   return false;
9547 }
9548 
9549 
9550 /// Determines whether to create a using shadow decl for a particular
9551 /// decl, given the set of decls existing prior to this using lookup.
9552 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9553                                 const LookupResult &Previous,
9554                                 UsingShadowDecl *&PrevShadow) {
9555   // Diagnose finding a decl which is not from a base class of the
9556   // current class.  We do this now because there are cases where this
9557   // function will silently decide not to build a shadow decl, which
9558   // will pre-empt further diagnostics.
9559   //
9560   // We don't need to do this in C++11 because we do the check once on
9561   // the qualifier.
9562   //
9563   // FIXME: diagnose the following if we care enough:
9564   //   struct A { int foo; };
9565   //   struct B : A { using A::foo; };
9566   //   template <class T> struct C : A {};
9567   //   template <class T> struct D : C<T> { using B::foo; } // <---
9568   // This is invalid (during instantiation) in C++03 because B::foo
9569   // resolves to the using decl in B, which is not a base class of D<T>.
9570   // We can't diagnose it immediately because C<T> is an unknown
9571   // specialization.  The UsingShadowDecl in D<T> then points directly
9572   // to A::foo, which will look well-formed when we instantiate.
9573   // The right solution is to not collapse the shadow-decl chain.
9574   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9575     DeclContext *OrigDC = Orig->getDeclContext();
9576 
9577     // Handle enums and anonymous structs.
9578     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9579     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9580     while (OrigRec->isAnonymousStructOrUnion())
9581       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9582 
9583     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9584       if (OrigDC == CurContext) {
9585         Diag(Using->getLocation(),
9586              diag::err_using_decl_nested_name_specifier_is_current_class)
9587           << Using->getQualifierLoc().getSourceRange();
9588         Diag(Orig->getLocation(), diag::note_using_decl_target);
9589         Using->setInvalidDecl();
9590         return true;
9591       }
9592 
9593       Diag(Using->getQualifierLoc().getBeginLoc(),
9594            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9595         << Using->getQualifier()
9596         << cast<CXXRecordDecl>(CurContext)
9597         << Using->getQualifierLoc().getSourceRange();
9598       Diag(Orig->getLocation(), diag::note_using_decl_target);
9599       Using->setInvalidDecl();
9600       return true;
9601     }
9602   }
9603 
9604   if (Previous.empty()) return false;
9605 
9606   NamedDecl *Target = Orig;
9607   if (isa<UsingShadowDecl>(Target))
9608     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9609 
9610   // If the target happens to be one of the previous declarations, we
9611   // don't have a conflict.
9612   //
9613   // FIXME: but we might be increasing its access, in which case we
9614   // should redeclare it.
9615   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9616   bool FoundEquivalentDecl = false;
9617   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9618          I != E; ++I) {
9619     NamedDecl *D = (*I)->getUnderlyingDecl();
9620     // We can have UsingDecls in our Previous results because we use the same
9621     // LookupResult for checking whether the UsingDecl itself is a valid
9622     // redeclaration.
9623     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9624       continue;
9625 
9626     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9627       // C++ [class.mem]p19:
9628       //   If T is the name of a class, then [every named member other than
9629       //   a non-static data member] shall have a name different from T
9630       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9631           !isa<IndirectFieldDecl>(Target) &&
9632           !isa<UnresolvedUsingValueDecl>(Target) &&
9633           DiagnoseClassNameShadow(
9634               CurContext,
9635               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9636         return true;
9637     }
9638 
9639     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9640       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9641         PrevShadow = Shadow;
9642       FoundEquivalentDecl = true;
9643     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9644       // We don't conflict with an existing using shadow decl of an equivalent
9645       // declaration, but we're not a redeclaration of it.
9646       FoundEquivalentDecl = true;
9647     }
9648 
9649     if (isVisible(D))
9650       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9651   }
9652 
9653   if (FoundEquivalentDecl)
9654     return false;
9655 
9656   if (FunctionDecl *FD = Target->getAsFunction()) {
9657     NamedDecl *OldDecl = nullptr;
9658     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9659                           /*IsForUsingDecl*/ true)) {
9660     case Ovl_Overload:
9661       return false;
9662 
9663     case Ovl_NonFunction:
9664       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9665       break;
9666 
9667     // We found a decl with the exact signature.
9668     case Ovl_Match:
9669       // If we're in a record, we want to hide the target, so we
9670       // return true (without a diagnostic) to tell the caller not to
9671       // build a shadow decl.
9672       if (CurContext->isRecord())
9673         return true;
9674 
9675       // If we're not in a record, this is an error.
9676       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9677       break;
9678     }
9679 
9680     Diag(Target->getLocation(), diag::note_using_decl_target);
9681     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9682     Using->setInvalidDecl();
9683     return true;
9684   }
9685 
9686   // Target is not a function.
9687 
9688   if (isa<TagDecl>(Target)) {
9689     // No conflict between a tag and a non-tag.
9690     if (!Tag) return false;
9691 
9692     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9693     Diag(Target->getLocation(), diag::note_using_decl_target);
9694     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9695     Using->setInvalidDecl();
9696     return true;
9697   }
9698 
9699   // No conflict between a tag and a non-tag.
9700   if (!NonTag) return false;
9701 
9702   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9703   Diag(Target->getLocation(), diag::note_using_decl_target);
9704   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9705   Using->setInvalidDecl();
9706   return true;
9707 }
9708 
9709 /// Determine whether a direct base class is a virtual base class.
9710 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9711   if (!Derived->getNumVBases())
9712     return false;
9713   for (auto &B : Derived->bases())
9714     if (B.getType()->getAsCXXRecordDecl() == Base)
9715       return B.isVirtual();
9716   llvm_unreachable("not a direct base class");
9717 }
9718 
9719 /// Builds a shadow declaration corresponding to a 'using' declaration.
9720 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9721                                             UsingDecl *UD,
9722                                             NamedDecl *Orig,
9723                                             UsingShadowDecl *PrevDecl) {
9724   // If we resolved to another shadow declaration, just coalesce them.
9725   NamedDecl *Target = Orig;
9726   if (isa<UsingShadowDecl>(Target)) {
9727     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9728     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9729   }
9730 
9731   NamedDecl *NonTemplateTarget = Target;
9732   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9733     NonTemplateTarget = TargetTD->getTemplatedDecl();
9734 
9735   UsingShadowDecl *Shadow;
9736   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9737     bool IsVirtualBase =
9738         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9739                             UD->getQualifier()->getAsRecordDecl());
9740     Shadow = ConstructorUsingShadowDecl::Create(
9741         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9742   } else {
9743     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9744                                      Target);
9745   }
9746   UD->addShadowDecl(Shadow);
9747 
9748   Shadow->setAccess(UD->getAccess());
9749   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9750     Shadow->setInvalidDecl();
9751 
9752   Shadow->setPreviousDecl(PrevDecl);
9753 
9754   if (S)
9755     PushOnScopeChains(Shadow, S);
9756   else
9757     CurContext->addDecl(Shadow);
9758 
9759 
9760   return Shadow;
9761 }
9762 
9763 /// Hides a using shadow declaration.  This is required by the current
9764 /// using-decl implementation when a resolvable using declaration in a
9765 /// class is followed by a declaration which would hide or override
9766 /// one or more of the using decl's targets; for example:
9767 ///
9768 ///   struct Base { void foo(int); };
9769 ///   struct Derived : Base {
9770 ///     using Base::foo;
9771 ///     void foo(int);
9772 ///   };
9773 ///
9774 /// The governing language is C++03 [namespace.udecl]p12:
9775 ///
9776 ///   When a using-declaration brings names from a base class into a
9777 ///   derived class scope, member functions in the derived class
9778 ///   override and/or hide member functions with the same name and
9779 ///   parameter types in a base class (rather than conflicting).
9780 ///
9781 /// There are two ways to implement this:
9782 ///   (1) optimistically create shadow decls when they're not hidden
9783 ///       by existing declarations, or
9784 ///   (2) don't create any shadow decls (or at least don't make them
9785 ///       visible) until we've fully parsed/instantiated the class.
9786 /// The problem with (1) is that we might have to retroactively remove
9787 /// a shadow decl, which requires several O(n) operations because the
9788 /// decl structures are (very reasonably) not designed for removal.
9789 /// (2) avoids this but is very fiddly and phase-dependent.
9790 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9791   if (Shadow->getDeclName().getNameKind() ==
9792         DeclarationName::CXXConversionFunctionName)
9793     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9794 
9795   // Remove it from the DeclContext...
9796   Shadow->getDeclContext()->removeDecl(Shadow);
9797 
9798   // ...and the scope, if applicable...
9799   if (S) {
9800     S->RemoveDecl(Shadow);
9801     IdResolver.RemoveDecl(Shadow);
9802   }
9803 
9804   // ...and the using decl.
9805   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9806 
9807   // TODO: complain somehow if Shadow was used.  It shouldn't
9808   // be possible for this to happen, because...?
9809 }
9810 
9811 /// Find the base specifier for a base class with the given type.
9812 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9813                                                 QualType DesiredBase,
9814                                                 bool &AnyDependentBases) {
9815   // Check whether the named type is a direct base class.
9816   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9817   for (auto &Base : Derived->bases()) {
9818     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9819     if (CanonicalDesiredBase == BaseType)
9820       return &Base;
9821     if (BaseType->isDependentType())
9822       AnyDependentBases = true;
9823   }
9824   return nullptr;
9825 }
9826 
9827 namespace {
9828 class UsingValidatorCCC : public CorrectionCandidateCallback {
9829 public:
9830   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9831                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9832       : HasTypenameKeyword(HasTypenameKeyword),
9833         IsInstantiation(IsInstantiation), OldNNS(NNS),
9834         RequireMemberOf(RequireMemberOf) {}
9835 
9836   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9837     NamedDecl *ND = Candidate.getCorrectionDecl();
9838 
9839     // Keywords are not valid here.
9840     if (!ND || isa<NamespaceDecl>(ND))
9841       return false;
9842 
9843     // Completely unqualified names are invalid for a 'using' declaration.
9844     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9845       return false;
9846 
9847     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9848     // reject.
9849 
9850     if (RequireMemberOf) {
9851       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9852       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9853         // No-one ever wants a using-declaration to name an injected-class-name
9854         // of a base class, unless they're declaring an inheriting constructor.
9855         ASTContext &Ctx = ND->getASTContext();
9856         if (!Ctx.getLangOpts().CPlusPlus11)
9857           return false;
9858         QualType FoundType = Ctx.getRecordType(FoundRecord);
9859 
9860         // Check that the injected-class-name is named as a member of its own
9861         // type; we don't want to suggest 'using Derived::Base;', since that
9862         // means something else.
9863         NestedNameSpecifier *Specifier =
9864             Candidate.WillReplaceSpecifier()
9865                 ? Candidate.getCorrectionSpecifier()
9866                 : OldNNS;
9867         if (!Specifier->getAsType() ||
9868             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9869           return false;
9870 
9871         // Check that this inheriting constructor declaration actually names a
9872         // direct base class of the current class.
9873         bool AnyDependentBases = false;
9874         if (!findDirectBaseWithType(RequireMemberOf,
9875                                     Ctx.getRecordType(FoundRecord),
9876                                     AnyDependentBases) &&
9877             !AnyDependentBases)
9878           return false;
9879       } else {
9880         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9881         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9882           return false;
9883 
9884         // FIXME: Check that the base class member is accessible?
9885       }
9886     } else {
9887       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9888       if (FoundRecord && FoundRecord->isInjectedClassName())
9889         return false;
9890     }
9891 
9892     if (isa<TypeDecl>(ND))
9893       return HasTypenameKeyword || !IsInstantiation;
9894 
9895     return !HasTypenameKeyword;
9896   }
9897 
9898 private:
9899   bool HasTypenameKeyword;
9900   bool IsInstantiation;
9901   NestedNameSpecifier *OldNNS;
9902   CXXRecordDecl *RequireMemberOf;
9903 };
9904 } // end anonymous namespace
9905 
9906 /// Builds a using declaration.
9907 ///
9908 /// \param IsInstantiation - Whether this call arises from an
9909 ///   instantiation of an unresolved using declaration.  We treat
9910 ///   the lookup differently for these declarations.
9911 NamedDecl *Sema::BuildUsingDeclaration(
9912     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9913     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9914     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9915     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9916   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9917   SourceLocation IdentLoc = NameInfo.getLoc();
9918   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9919 
9920   // FIXME: We ignore attributes for now.
9921 
9922   // For an inheriting constructor declaration, the name of the using
9923   // declaration is the name of a constructor in this class, not in the
9924   // base class.
9925   DeclarationNameInfo UsingName = NameInfo;
9926   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9927     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9928       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9929           Context.getCanonicalType(Context.getRecordType(RD))));
9930 
9931   // Do the redeclaration lookup in the current scope.
9932   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9933                         ForVisibleRedeclaration);
9934   Previous.setHideTags(false);
9935   if (S) {
9936     LookupName(Previous, S);
9937 
9938     // It is really dumb that we have to do this.
9939     LookupResult::Filter F = Previous.makeFilter();
9940     while (F.hasNext()) {
9941       NamedDecl *D = F.next();
9942       if (!isDeclInScope(D, CurContext, S))
9943         F.erase();
9944       // If we found a local extern declaration that's not ordinarily visible,
9945       // and this declaration is being added to a non-block scope, ignore it.
9946       // We're only checking for scope conflicts here, not also for violations
9947       // of the linkage rules.
9948       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9949                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9950         F.erase();
9951     }
9952     F.done();
9953   } else {
9954     assert(IsInstantiation && "no scope in non-instantiation");
9955     if (CurContext->isRecord())
9956       LookupQualifiedName(Previous, CurContext);
9957     else {
9958       // No redeclaration check is needed here; in non-member contexts we
9959       // diagnosed all possible conflicts with other using-declarations when
9960       // building the template:
9961       //
9962       // For a dependent non-type using declaration, the only valid case is
9963       // if we instantiate to a single enumerator. We check for conflicts
9964       // between shadow declarations we introduce, and we check in the template
9965       // definition for conflicts between a non-type using declaration and any
9966       // other declaration, which together covers all cases.
9967       //
9968       // A dependent typename using declaration will never successfully
9969       // instantiate, since it will always name a class member, so we reject
9970       // that in the template definition.
9971     }
9972   }
9973 
9974   // Check for invalid redeclarations.
9975   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9976                                   SS, IdentLoc, Previous))
9977     return nullptr;
9978 
9979   // Check for bad qualifiers.
9980   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9981                               IdentLoc))
9982     return nullptr;
9983 
9984   DeclContext *LookupContext = computeDeclContext(SS);
9985   NamedDecl *D;
9986   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9987   if (!LookupContext || EllipsisLoc.isValid()) {
9988     if (HasTypenameKeyword) {
9989       // FIXME: not all declaration name kinds are legal here
9990       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9991                                               UsingLoc, TypenameLoc,
9992                                               QualifierLoc,
9993                                               IdentLoc, NameInfo.getName(),
9994                                               EllipsisLoc);
9995     } else {
9996       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9997                                            QualifierLoc, NameInfo, EllipsisLoc);
9998     }
9999     D->setAccess(AS);
10000     CurContext->addDecl(D);
10001     return D;
10002   }
10003 
10004   auto Build = [&](bool Invalid) {
10005     UsingDecl *UD =
10006         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10007                           UsingName, HasTypenameKeyword);
10008     UD->setAccess(AS);
10009     CurContext->addDecl(UD);
10010     UD->setInvalidDecl(Invalid);
10011     return UD;
10012   };
10013   auto BuildInvalid = [&]{ return Build(true); };
10014   auto BuildValid = [&]{ return Build(false); };
10015 
10016   if (RequireCompleteDeclContext(SS, LookupContext))
10017     return BuildInvalid();
10018 
10019   // Look up the target name.
10020   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10021 
10022   // Unlike most lookups, we don't always want to hide tag
10023   // declarations: tag names are visible through the using declaration
10024   // even if hidden by ordinary names, *except* in a dependent context
10025   // where it's important for the sanity of two-phase lookup.
10026   if (!IsInstantiation)
10027     R.setHideTags(false);
10028 
10029   // For the purposes of this lookup, we have a base object type
10030   // equal to that of the current context.
10031   if (CurContext->isRecord()) {
10032     R.setBaseObjectType(
10033                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10034   }
10035 
10036   LookupQualifiedName(R, LookupContext);
10037 
10038   // Try to correct typos if possible. If constructor name lookup finds no
10039   // results, that means the named class has no explicit constructors, and we
10040   // suppressed declaring implicit ones (probably because it's dependent or
10041   // invalid).
10042   if (R.empty() &&
10043       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10044     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10045     // it will believe that glibc provides a ::gets in cases where it does not,
10046     // and will try to pull it into namespace std with a using-declaration.
10047     // Just ignore the using-declaration in that case.
10048     auto *II = NameInfo.getName().getAsIdentifierInfo();
10049     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10050         CurContext->isStdNamespace() &&
10051         isa<TranslationUnitDecl>(LookupContext) &&
10052         getSourceManager().isInSystemHeader(UsingLoc))
10053       return nullptr;
10054     if (TypoCorrection Corrected = CorrectTypo(
10055             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
10056             llvm::make_unique<UsingValidatorCCC>(
10057                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10058                 dyn_cast<CXXRecordDecl>(CurContext)),
10059             CTK_ErrorRecovery)) {
10060       // We reject candidates where DroppedSpecifier == true, hence the
10061       // literal '0' below.
10062       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10063                                 << NameInfo.getName() << LookupContext << 0
10064                                 << SS.getRange());
10065 
10066       // If we picked a correction with no attached Decl we can't do anything
10067       // useful with it, bail out.
10068       NamedDecl *ND = Corrected.getCorrectionDecl();
10069       if (!ND)
10070         return BuildInvalid();
10071 
10072       // If we corrected to an inheriting constructor, handle it as one.
10073       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10074       if (RD && RD->isInjectedClassName()) {
10075         // The parent of the injected class name is the class itself.
10076         RD = cast<CXXRecordDecl>(RD->getParent());
10077 
10078         // Fix up the information we'll use to build the using declaration.
10079         if (Corrected.WillReplaceSpecifier()) {
10080           NestedNameSpecifierLocBuilder Builder;
10081           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10082                               QualifierLoc.getSourceRange());
10083           QualifierLoc = Builder.getWithLocInContext(Context);
10084         }
10085 
10086         // In this case, the name we introduce is the name of a derived class
10087         // constructor.
10088         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10089         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10090             Context.getCanonicalType(Context.getRecordType(CurClass))));
10091         UsingName.setNamedTypeInfo(nullptr);
10092         for (auto *Ctor : LookupConstructors(RD))
10093           R.addDecl(Ctor);
10094         R.resolveKind();
10095       } else {
10096         // FIXME: Pick up all the declarations if we found an overloaded
10097         // function.
10098         UsingName.setName(ND->getDeclName());
10099         R.addDecl(ND);
10100       }
10101     } else {
10102       Diag(IdentLoc, diag::err_no_member)
10103         << NameInfo.getName() << LookupContext << SS.getRange();
10104       return BuildInvalid();
10105     }
10106   }
10107 
10108   if (R.isAmbiguous())
10109     return BuildInvalid();
10110 
10111   if (HasTypenameKeyword) {
10112     // If we asked for a typename and got a non-type decl, error out.
10113     if (!R.getAsSingle<TypeDecl>()) {
10114       Diag(IdentLoc, diag::err_using_typename_non_type);
10115       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10116         Diag((*I)->getUnderlyingDecl()->getLocation(),
10117              diag::note_using_decl_target);
10118       return BuildInvalid();
10119     }
10120   } else {
10121     // If we asked for a non-typename and we got a type, error out,
10122     // but only if this is an instantiation of an unresolved using
10123     // decl.  Otherwise just silently find the type name.
10124     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10125       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10126       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10127       return BuildInvalid();
10128     }
10129   }
10130 
10131   // C++14 [namespace.udecl]p6:
10132   // A using-declaration shall not name a namespace.
10133   if (R.getAsSingle<NamespaceDecl>()) {
10134     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10135       << SS.getRange();
10136     return BuildInvalid();
10137   }
10138 
10139   // C++14 [namespace.udecl]p7:
10140   // A using-declaration shall not name a scoped enumerator.
10141   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10142     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10143       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10144         << SS.getRange();
10145       return BuildInvalid();
10146     }
10147   }
10148 
10149   UsingDecl *UD = BuildValid();
10150 
10151   // Some additional rules apply to inheriting constructors.
10152   if (UsingName.getName().getNameKind() ==
10153         DeclarationName::CXXConstructorName) {
10154     // Suppress access diagnostics; the access check is instead performed at the
10155     // point of use for an inheriting constructor.
10156     R.suppressDiagnostics();
10157     if (CheckInheritingConstructorUsingDecl(UD))
10158       return UD;
10159   }
10160 
10161   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10162     UsingShadowDecl *PrevDecl = nullptr;
10163     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10164       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10165   }
10166 
10167   return UD;
10168 }
10169 
10170 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10171                                     ArrayRef<NamedDecl *> Expansions) {
10172   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10173          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10174          isa<UsingPackDecl>(InstantiatedFrom));
10175 
10176   auto *UPD =
10177       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10178   UPD->setAccess(InstantiatedFrom->getAccess());
10179   CurContext->addDecl(UPD);
10180   return UPD;
10181 }
10182 
10183 /// Additional checks for a using declaration referring to a constructor name.
10184 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10185   assert(!UD->hasTypename() && "expecting a constructor name");
10186 
10187   const Type *SourceType = UD->getQualifier()->getAsType();
10188   assert(SourceType &&
10189          "Using decl naming constructor doesn't have type in scope spec.");
10190   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10191 
10192   // Check whether the named type is a direct base class.
10193   bool AnyDependentBases = false;
10194   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10195                                       AnyDependentBases);
10196   if (!Base && !AnyDependentBases) {
10197     Diag(UD->getUsingLoc(),
10198          diag::err_using_decl_constructor_not_in_direct_base)
10199       << UD->getNameInfo().getSourceRange()
10200       << QualType(SourceType, 0) << TargetClass;
10201     UD->setInvalidDecl();
10202     return true;
10203   }
10204 
10205   if (Base)
10206     Base->setInheritConstructors();
10207 
10208   return false;
10209 }
10210 
10211 /// Checks that the given using declaration is not an invalid
10212 /// redeclaration.  Note that this is checking only for the using decl
10213 /// itself, not for any ill-formedness among the UsingShadowDecls.
10214 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10215                                        bool HasTypenameKeyword,
10216                                        const CXXScopeSpec &SS,
10217                                        SourceLocation NameLoc,
10218                                        const LookupResult &Prev) {
10219   NestedNameSpecifier *Qual = SS.getScopeRep();
10220 
10221   // C++03 [namespace.udecl]p8:
10222   // C++0x [namespace.udecl]p10:
10223   //   A using-declaration is a declaration and can therefore be used
10224   //   repeatedly where (and only where) multiple declarations are
10225   //   allowed.
10226   //
10227   // That's in non-member contexts.
10228   if (!CurContext->getRedeclContext()->isRecord()) {
10229     // A dependent qualifier outside a class can only ever resolve to an
10230     // enumeration type. Therefore it conflicts with any other non-type
10231     // declaration in the same scope.
10232     // FIXME: How should we check for dependent type-type conflicts at block
10233     // scope?
10234     if (Qual->isDependent() && !HasTypenameKeyword) {
10235       for (auto *D : Prev) {
10236         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10237           bool OldCouldBeEnumerator =
10238               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10239           Diag(NameLoc,
10240                OldCouldBeEnumerator ? diag::err_redefinition
10241                                     : diag::err_redefinition_different_kind)
10242               << Prev.getLookupName();
10243           Diag(D->getLocation(), diag::note_previous_definition);
10244           return true;
10245         }
10246       }
10247     }
10248     return false;
10249   }
10250 
10251   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10252     NamedDecl *D = *I;
10253 
10254     bool DTypename;
10255     NestedNameSpecifier *DQual;
10256     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10257       DTypename = UD->hasTypename();
10258       DQual = UD->getQualifier();
10259     } else if (UnresolvedUsingValueDecl *UD
10260                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10261       DTypename = false;
10262       DQual = UD->getQualifier();
10263     } else if (UnresolvedUsingTypenameDecl *UD
10264                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10265       DTypename = true;
10266       DQual = UD->getQualifier();
10267     } else continue;
10268 
10269     // using decls differ if one says 'typename' and the other doesn't.
10270     // FIXME: non-dependent using decls?
10271     if (HasTypenameKeyword != DTypename) continue;
10272 
10273     // using decls differ if they name different scopes (but note that
10274     // template instantiation can cause this check to trigger when it
10275     // didn't before instantiation).
10276     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10277         Context.getCanonicalNestedNameSpecifier(DQual))
10278       continue;
10279 
10280     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10281     Diag(D->getLocation(), diag::note_using_decl) << 1;
10282     return true;
10283   }
10284 
10285   return false;
10286 }
10287 
10288 
10289 /// Checks that the given nested-name qualifier used in a using decl
10290 /// in the current context is appropriately related to the current
10291 /// scope.  If an error is found, diagnoses it and returns true.
10292 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10293                                    bool HasTypename,
10294                                    const CXXScopeSpec &SS,
10295                                    const DeclarationNameInfo &NameInfo,
10296                                    SourceLocation NameLoc) {
10297   DeclContext *NamedContext = computeDeclContext(SS);
10298 
10299   if (!CurContext->isRecord()) {
10300     // C++03 [namespace.udecl]p3:
10301     // C++0x [namespace.udecl]p8:
10302     //   A using-declaration for a class member shall be a member-declaration.
10303 
10304     // If we weren't able to compute a valid scope, it might validly be a
10305     // dependent class scope or a dependent enumeration unscoped scope. If
10306     // we have a 'typename' keyword, the scope must resolve to a class type.
10307     if ((HasTypename && !NamedContext) ||
10308         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10309       auto *RD = NamedContext
10310                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10311                      : nullptr;
10312       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10313         RD = nullptr;
10314 
10315       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10316         << SS.getRange();
10317 
10318       // If we have a complete, non-dependent source type, try to suggest a
10319       // way to get the same effect.
10320       if (!RD)
10321         return true;
10322 
10323       // Find what this using-declaration was referring to.
10324       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10325       R.setHideTags(false);
10326       R.suppressDiagnostics();
10327       LookupQualifiedName(R, RD);
10328 
10329       if (R.getAsSingle<TypeDecl>()) {
10330         if (getLangOpts().CPlusPlus11) {
10331           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10332           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10333             << 0 // alias declaration
10334             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10335                                           NameInfo.getName().getAsString() +
10336                                               " = ");
10337         } else {
10338           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10339           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10340           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10341             << 1 // typedef declaration
10342             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10343             << FixItHint::CreateInsertion(
10344                    InsertLoc, " " + NameInfo.getName().getAsString());
10345         }
10346       } else if (R.getAsSingle<VarDecl>()) {
10347         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10348         // repeating the type of the static data member here.
10349         FixItHint FixIt;
10350         if (getLangOpts().CPlusPlus11) {
10351           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10352           FixIt = FixItHint::CreateReplacement(
10353               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10354         }
10355 
10356         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10357           << 2 // reference declaration
10358           << FixIt;
10359       } else if (R.getAsSingle<EnumConstantDecl>()) {
10360         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10361         // repeating the type of the enumeration here, and we can't do so if
10362         // the type is anonymous.
10363         FixItHint FixIt;
10364         if (getLangOpts().CPlusPlus11) {
10365           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10366           FixIt = FixItHint::CreateReplacement(
10367               UsingLoc,
10368               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10369         }
10370 
10371         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10372           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10373           << FixIt;
10374       }
10375       return true;
10376     }
10377 
10378     // Otherwise, this might be valid.
10379     return false;
10380   }
10381 
10382   // The current scope is a record.
10383 
10384   // If the named context is dependent, we can't decide much.
10385   if (!NamedContext) {
10386     // FIXME: in C++0x, we can diagnose if we can prove that the
10387     // nested-name-specifier does not refer to a base class, which is
10388     // still possible in some cases.
10389 
10390     // Otherwise we have to conservatively report that things might be
10391     // okay.
10392     return false;
10393   }
10394 
10395   if (!NamedContext->isRecord()) {
10396     // Ideally this would point at the last name in the specifier,
10397     // but we don't have that level of source info.
10398     Diag(SS.getRange().getBegin(),
10399          diag::err_using_decl_nested_name_specifier_is_not_class)
10400       << SS.getScopeRep() << SS.getRange();
10401     return true;
10402   }
10403 
10404   if (!NamedContext->isDependentContext() &&
10405       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10406     return true;
10407 
10408   if (getLangOpts().CPlusPlus11) {
10409     // C++11 [namespace.udecl]p3:
10410     //   In a using-declaration used as a member-declaration, the
10411     //   nested-name-specifier shall name a base class of the class
10412     //   being defined.
10413 
10414     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10415                                  cast<CXXRecordDecl>(NamedContext))) {
10416       if (CurContext == NamedContext) {
10417         Diag(NameLoc,
10418              diag::err_using_decl_nested_name_specifier_is_current_class)
10419           << SS.getRange();
10420         return true;
10421       }
10422 
10423       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10424         Diag(SS.getRange().getBegin(),
10425              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10426           << SS.getScopeRep()
10427           << cast<CXXRecordDecl>(CurContext)
10428           << SS.getRange();
10429       }
10430       return true;
10431     }
10432 
10433     return false;
10434   }
10435 
10436   // C++03 [namespace.udecl]p4:
10437   //   A using-declaration used as a member-declaration shall refer
10438   //   to a member of a base class of the class being defined [etc.].
10439 
10440   // Salient point: SS doesn't have to name a base class as long as
10441   // lookup only finds members from base classes.  Therefore we can
10442   // diagnose here only if we can prove that that can't happen,
10443   // i.e. if the class hierarchies provably don't intersect.
10444 
10445   // TODO: it would be nice if "definitely valid" results were cached
10446   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10447   // need to be repeated.
10448 
10449   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10450   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10451     Bases.insert(Base);
10452     return true;
10453   };
10454 
10455   // Collect all bases. Return false if we find a dependent base.
10456   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10457     return false;
10458 
10459   // Returns true if the base is dependent or is one of the accumulated base
10460   // classes.
10461   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10462     return !Bases.count(Base);
10463   };
10464 
10465   // Return false if the class has a dependent base or if it or one
10466   // of its bases is present in the base set of the current context.
10467   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10468       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10469     return false;
10470 
10471   Diag(SS.getRange().getBegin(),
10472        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10473     << SS.getScopeRep()
10474     << cast<CXXRecordDecl>(CurContext)
10475     << SS.getRange();
10476 
10477   return true;
10478 }
10479 
10480 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10481                                   MultiTemplateParamsArg TemplateParamLists,
10482                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10483                                   const ParsedAttributesView &AttrList,
10484                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10485   // Skip up to the relevant declaration scope.
10486   while (S->isTemplateParamScope())
10487     S = S->getParent();
10488   assert((S->getFlags() & Scope::DeclScope) &&
10489          "got alias-declaration outside of declaration scope");
10490 
10491   if (Type.isInvalid())
10492     return nullptr;
10493 
10494   bool Invalid = false;
10495   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10496   TypeSourceInfo *TInfo = nullptr;
10497   GetTypeFromParser(Type.get(), &TInfo);
10498 
10499   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10500     return nullptr;
10501 
10502   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10503                                       UPPC_DeclarationType)) {
10504     Invalid = true;
10505     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10506                                              TInfo->getTypeLoc().getBeginLoc());
10507   }
10508 
10509   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10510                         TemplateParamLists.size()
10511                             ? forRedeclarationInCurContext()
10512                             : ForVisibleRedeclaration);
10513   LookupName(Previous, S);
10514 
10515   // Warn about shadowing the name of a template parameter.
10516   if (Previous.isSingleResult() &&
10517       Previous.getFoundDecl()->isTemplateParameter()) {
10518     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10519     Previous.clear();
10520   }
10521 
10522   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10523          "name in alias declaration must be an identifier");
10524   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10525                                                Name.StartLocation,
10526                                                Name.Identifier, TInfo);
10527 
10528   NewTD->setAccess(AS);
10529 
10530   if (Invalid)
10531     NewTD->setInvalidDecl();
10532 
10533   ProcessDeclAttributeList(S, NewTD, AttrList);
10534   AddPragmaAttributes(S, NewTD);
10535 
10536   CheckTypedefForVariablyModifiedType(S, NewTD);
10537   Invalid |= NewTD->isInvalidDecl();
10538 
10539   bool Redeclaration = false;
10540 
10541   NamedDecl *NewND;
10542   if (TemplateParamLists.size()) {
10543     TypeAliasTemplateDecl *OldDecl = nullptr;
10544     TemplateParameterList *OldTemplateParams = nullptr;
10545 
10546     if (TemplateParamLists.size() != 1) {
10547       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10548         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10549          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10550     }
10551     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10552 
10553     // Check that we can declare a template here.
10554     if (CheckTemplateDeclScope(S, TemplateParams))
10555       return nullptr;
10556 
10557     // Only consider previous declarations in the same scope.
10558     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10559                          /*ExplicitInstantiationOrSpecialization*/false);
10560     if (!Previous.empty()) {
10561       Redeclaration = true;
10562 
10563       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10564       if (!OldDecl && !Invalid) {
10565         Diag(UsingLoc, diag::err_redefinition_different_kind)
10566           << Name.Identifier;
10567 
10568         NamedDecl *OldD = Previous.getRepresentativeDecl();
10569         if (OldD->getLocation().isValid())
10570           Diag(OldD->getLocation(), diag::note_previous_definition);
10571 
10572         Invalid = true;
10573       }
10574 
10575       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10576         if (TemplateParameterListsAreEqual(TemplateParams,
10577                                            OldDecl->getTemplateParameters(),
10578                                            /*Complain=*/true,
10579                                            TPL_TemplateMatch))
10580           OldTemplateParams =
10581               OldDecl->getMostRecentDecl()->getTemplateParameters();
10582         else
10583           Invalid = true;
10584 
10585         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10586         if (!Invalid &&
10587             !Context.hasSameType(OldTD->getUnderlyingType(),
10588                                  NewTD->getUnderlyingType())) {
10589           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10590           // but we can't reasonably accept it.
10591           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10592             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10593           if (OldTD->getLocation().isValid())
10594             Diag(OldTD->getLocation(), diag::note_previous_definition);
10595           Invalid = true;
10596         }
10597       }
10598     }
10599 
10600     // Merge any previous default template arguments into our parameters,
10601     // and check the parameter list.
10602     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10603                                    TPC_TypeAliasTemplate))
10604       return nullptr;
10605 
10606     TypeAliasTemplateDecl *NewDecl =
10607       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10608                                     Name.Identifier, TemplateParams,
10609                                     NewTD);
10610     NewTD->setDescribedAliasTemplate(NewDecl);
10611 
10612     NewDecl->setAccess(AS);
10613 
10614     if (Invalid)
10615       NewDecl->setInvalidDecl();
10616     else if (OldDecl) {
10617       NewDecl->setPreviousDecl(OldDecl);
10618       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10619     }
10620 
10621     NewND = NewDecl;
10622   } else {
10623     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10624       setTagNameForLinkagePurposes(TD, NewTD);
10625       handleTagNumbering(TD, S);
10626     }
10627     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10628     NewND = NewTD;
10629   }
10630 
10631   PushOnScopeChains(NewND, S);
10632   ActOnDocumentableDecl(NewND);
10633   return NewND;
10634 }
10635 
10636 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10637                                    SourceLocation AliasLoc,
10638                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10639                                    SourceLocation IdentLoc,
10640                                    IdentifierInfo *Ident) {
10641 
10642   // Lookup the namespace name.
10643   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10644   LookupParsedName(R, S, &SS);
10645 
10646   if (R.isAmbiguous())
10647     return nullptr;
10648 
10649   if (R.empty()) {
10650     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10651       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10652       return nullptr;
10653     }
10654   }
10655   assert(!R.isAmbiguous() && !R.empty());
10656   NamedDecl *ND = R.getRepresentativeDecl();
10657 
10658   // Check if we have a previous declaration with the same name.
10659   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10660                      ForVisibleRedeclaration);
10661   LookupName(PrevR, S);
10662 
10663   // Check we're not shadowing a template parameter.
10664   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10665     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10666     PrevR.clear();
10667   }
10668 
10669   // Filter out any other lookup result from an enclosing scope.
10670   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10671                        /*AllowInlineNamespace*/false);
10672 
10673   // Find the previous declaration and check that we can redeclare it.
10674   NamespaceAliasDecl *Prev = nullptr;
10675   if (PrevR.isSingleResult()) {
10676     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10677     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10678       // We already have an alias with the same name that points to the same
10679       // namespace; check that it matches.
10680       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10681         Prev = AD;
10682       } else if (isVisible(PrevDecl)) {
10683         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10684           << Alias;
10685         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10686           << AD->getNamespace();
10687         return nullptr;
10688       }
10689     } else if (isVisible(PrevDecl)) {
10690       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10691                             ? diag::err_redefinition
10692                             : diag::err_redefinition_different_kind;
10693       Diag(AliasLoc, DiagID) << Alias;
10694       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10695       return nullptr;
10696     }
10697   }
10698 
10699   // The use of a nested name specifier may trigger deprecation warnings.
10700   DiagnoseUseOfDecl(ND, IdentLoc);
10701 
10702   NamespaceAliasDecl *AliasDecl =
10703     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10704                                Alias, SS.getWithLocInContext(Context),
10705                                IdentLoc, ND);
10706   if (Prev)
10707     AliasDecl->setPreviousDecl(Prev);
10708 
10709   PushOnScopeChains(AliasDecl, S);
10710   return AliasDecl;
10711 }
10712 
10713 namespace {
10714 struct SpecialMemberExceptionSpecInfo
10715     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10716   SourceLocation Loc;
10717   Sema::ImplicitExceptionSpecification ExceptSpec;
10718 
10719   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10720                                  Sema::CXXSpecialMember CSM,
10721                                  Sema::InheritedConstructorInfo *ICI,
10722                                  SourceLocation Loc)
10723       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10724 
10725   bool visitBase(CXXBaseSpecifier *Base);
10726   bool visitField(FieldDecl *FD);
10727 
10728   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10729                            unsigned Quals);
10730 
10731   void visitSubobjectCall(Subobject Subobj,
10732                           Sema::SpecialMemberOverloadResult SMOR);
10733 };
10734 }
10735 
10736 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10737   auto *RT = Base->getType()->getAs<RecordType>();
10738   if (!RT)
10739     return false;
10740 
10741   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10742   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10743   if (auto *BaseCtor = SMOR.getMethod()) {
10744     visitSubobjectCall(Base, BaseCtor);
10745     return false;
10746   }
10747 
10748   visitClassSubobject(BaseClass, Base, 0);
10749   return false;
10750 }
10751 
10752 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10753   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10754     Expr *E = FD->getInClassInitializer();
10755     if (!E)
10756       // FIXME: It's a little wasteful to build and throw away a
10757       // CXXDefaultInitExpr here.
10758       // FIXME: We should have a single context note pointing at Loc, and
10759       // this location should be MD->getLocation() instead, since that's
10760       // the location where we actually use the default init expression.
10761       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10762     if (E)
10763       ExceptSpec.CalledExpr(E);
10764   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10765                             ->getAs<RecordType>()) {
10766     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10767                         FD->getType().getCVRQualifiers());
10768   }
10769   return false;
10770 }
10771 
10772 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10773                                                          Subobject Subobj,
10774                                                          unsigned Quals) {
10775   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10776   bool IsMutable = Field && Field->isMutable();
10777   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10778 }
10779 
10780 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10781     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10782   // Note, if lookup fails, it doesn't matter what exception specification we
10783   // choose because the special member will be deleted.
10784   if (CXXMethodDecl *MD = SMOR.getMethod())
10785     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10786 }
10787 
10788 namespace {
10789 /// RAII object to register a special member as being currently declared.
10790 struct ComputingExceptionSpec {
10791   Sema &S;
10792 
10793   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10794       : S(S) {
10795     Sema::CodeSynthesisContext Ctx;
10796     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10797     Ctx.PointOfInstantiation = Loc;
10798     Ctx.Entity = MD;
10799     S.pushCodeSynthesisContext(Ctx);
10800   }
10801   ~ComputingExceptionSpec() {
10802     S.popCodeSynthesisContext();
10803   }
10804 };
10805 }
10806 
10807 static Sema::ImplicitExceptionSpecification
10808 ComputeDefaultedSpecialMemberExceptionSpec(
10809     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10810     Sema::InheritedConstructorInfo *ICI) {
10811   ComputingExceptionSpec CES(S, MD, Loc);
10812 
10813   CXXRecordDecl *ClassDecl = MD->getParent();
10814 
10815   // C++ [except.spec]p14:
10816   //   An implicitly declared special member function (Clause 12) shall have an
10817   //   exception-specification. [...]
10818   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10819   if (ClassDecl->isInvalidDecl())
10820     return Info.ExceptSpec;
10821 
10822   // FIXME: If this diagnostic fires, we're probably missing a check for
10823   // attempting to resolve an exception specification before it's known
10824   // at a higher level.
10825   if (S.RequireCompleteType(MD->getLocation(),
10826                             S.Context.getRecordType(ClassDecl),
10827                             diag::err_exception_spec_incomplete_type))
10828     return Info.ExceptSpec;
10829 
10830   // C++1z [except.spec]p7:
10831   //   [Look for exceptions thrown by] a constructor selected [...] to
10832   //   initialize a potentially constructed subobject,
10833   // C++1z [except.spec]p8:
10834   //   The exception specification for an implicitly-declared destructor, or a
10835   //   destructor without a noexcept-specifier, is potentially-throwing if and
10836   //   only if any of the destructors for any of its potentially constructed
10837   //   subojects is potentially throwing.
10838   // FIXME: We respect the first rule but ignore the "potentially constructed"
10839   // in the second rule to resolve a core issue (no number yet) that would have
10840   // us reject:
10841   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10842   //   struct B : A {};
10843   //   struct C : B { void f(); };
10844   // ... due to giving B::~B() a non-throwing exception specification.
10845   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10846                                 : Info.VisitAllBases);
10847 
10848   return Info.ExceptSpec;
10849 }
10850 
10851 namespace {
10852 /// RAII object to register a special member as being currently declared.
10853 struct DeclaringSpecialMember {
10854   Sema &S;
10855   Sema::SpecialMemberDecl D;
10856   Sema::ContextRAII SavedContext;
10857   bool WasAlreadyBeingDeclared;
10858 
10859   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10860       : S(S), D(RD, CSM), SavedContext(S, RD) {
10861     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10862     if (WasAlreadyBeingDeclared)
10863       // This almost never happens, but if it does, ensure that our cache
10864       // doesn't contain a stale result.
10865       S.SpecialMemberCache.clear();
10866     else {
10867       // Register a note to be produced if we encounter an error while
10868       // declaring the special member.
10869       Sema::CodeSynthesisContext Ctx;
10870       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10871       // FIXME: We don't have a location to use here. Using the class's
10872       // location maintains the fiction that we declare all special members
10873       // with the class, but (1) it's not clear that lying about that helps our
10874       // users understand what's going on, and (2) there may be outer contexts
10875       // on the stack (some of which are relevant) and printing them exposes
10876       // our lies.
10877       Ctx.PointOfInstantiation = RD->getLocation();
10878       Ctx.Entity = RD;
10879       Ctx.SpecialMember = CSM;
10880       S.pushCodeSynthesisContext(Ctx);
10881     }
10882   }
10883   ~DeclaringSpecialMember() {
10884     if (!WasAlreadyBeingDeclared) {
10885       S.SpecialMembersBeingDeclared.erase(D);
10886       S.popCodeSynthesisContext();
10887     }
10888   }
10889 
10890   /// Are we already trying to declare this special member?
10891   bool isAlreadyBeingDeclared() const {
10892     return WasAlreadyBeingDeclared;
10893   }
10894 };
10895 }
10896 
10897 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10898   // Look up any existing declarations, but don't trigger declaration of all
10899   // implicit special members with this name.
10900   DeclarationName Name = FD->getDeclName();
10901   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10902                  ForExternalRedeclaration);
10903   for (auto *D : FD->getParent()->lookup(Name))
10904     if (auto *Acceptable = R.getAcceptableDecl(D))
10905       R.addDecl(Acceptable);
10906   R.resolveKind();
10907   R.suppressDiagnostics();
10908 
10909   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10910 }
10911 
10912 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10913                                                      CXXRecordDecl *ClassDecl) {
10914   // C++ [class.ctor]p5:
10915   //   A default constructor for a class X is a constructor of class X
10916   //   that can be called without an argument. If there is no
10917   //   user-declared constructor for class X, a default constructor is
10918   //   implicitly declared. An implicitly-declared default constructor
10919   //   is an inline public member of its class.
10920   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10921          "Should not build implicit default constructor!");
10922 
10923   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10924   if (DSM.isAlreadyBeingDeclared())
10925     return nullptr;
10926 
10927   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10928                                                      CXXDefaultConstructor,
10929                                                      false);
10930 
10931   // Create the actual constructor declaration.
10932   CanQualType ClassType
10933     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10934   SourceLocation ClassLoc = ClassDecl->getLocation();
10935   DeclarationName Name
10936     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10937   DeclarationNameInfo NameInfo(Name, ClassLoc);
10938   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10939       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10940       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10941       /*isImplicitlyDeclared=*/true, Constexpr);
10942   DefaultCon->setAccess(AS_public);
10943   DefaultCon->setDefaulted();
10944 
10945   if (getLangOpts().CUDA) {
10946     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10947                                             DefaultCon,
10948                                             /* ConstRHS */ false,
10949                                             /* Diagnose */ false);
10950   }
10951 
10952   // Build an exception specification pointing back at this constructor.
10953   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10954   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10955 
10956   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10957   // constructors is easy to compute.
10958   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10959 
10960   // Note that we have declared this constructor.
10961   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10962 
10963   Scope *S = getScopeForContext(ClassDecl);
10964   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10965 
10966   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10967     SetDeclDeleted(DefaultCon, ClassLoc);
10968 
10969   if (S)
10970     PushOnScopeChains(DefaultCon, S, false);
10971   ClassDecl->addDecl(DefaultCon);
10972 
10973   return DefaultCon;
10974 }
10975 
10976 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10977                                             CXXConstructorDecl *Constructor) {
10978   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10979           !Constructor->doesThisDeclarationHaveABody() &&
10980           !Constructor->isDeleted()) &&
10981     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10982   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10983     return;
10984 
10985   CXXRecordDecl *ClassDecl = Constructor->getParent();
10986   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10987 
10988   SynthesizedFunctionScope Scope(*this, Constructor);
10989 
10990   // The exception specification is needed because we are defining the
10991   // function.
10992   ResolveExceptionSpec(CurrentLocation,
10993                        Constructor->getType()->castAs<FunctionProtoType>());
10994   MarkVTableUsed(CurrentLocation, ClassDecl);
10995 
10996   // Add a context note for diagnostics produced after this point.
10997   Scope.addContextNote(CurrentLocation);
10998 
10999   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11000     Constructor->setInvalidDecl();
11001     return;
11002   }
11003 
11004   SourceLocation Loc = Constructor->getEndLoc().isValid()
11005                            ? Constructor->getEndLoc()
11006                            : Constructor->getLocation();
11007   Constructor->setBody(new (Context) CompoundStmt(Loc));
11008   Constructor->markUsed(Context);
11009 
11010   if (ASTMutationListener *L = getASTMutationListener()) {
11011     L->CompletedImplicitDefinition(Constructor);
11012   }
11013 
11014   DiagnoseUninitializedFields(*this, Constructor);
11015 }
11016 
11017 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11018   // Perform any delayed checks on exception specifications.
11019   CheckDelayedMemberExceptionSpecs();
11020 }
11021 
11022 /// Find or create the fake constructor we synthesize to model constructing an
11023 /// object of a derived class via a constructor of a base class.
11024 CXXConstructorDecl *
11025 Sema::findInheritingConstructor(SourceLocation Loc,
11026                                 CXXConstructorDecl *BaseCtor,
11027                                 ConstructorUsingShadowDecl *Shadow) {
11028   CXXRecordDecl *Derived = Shadow->getParent();
11029   SourceLocation UsingLoc = Shadow->getLocation();
11030 
11031   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11032   // For now we use the name of the base class constructor as a member of the
11033   // derived class to indicate a (fake) inherited constructor name.
11034   DeclarationName Name = BaseCtor->getDeclName();
11035 
11036   // Check to see if we already have a fake constructor for this inherited
11037   // constructor call.
11038   for (NamedDecl *Ctor : Derived->lookup(Name))
11039     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11040                                ->getInheritedConstructor()
11041                                .getConstructor(),
11042                            BaseCtor))
11043       return cast<CXXConstructorDecl>(Ctor);
11044 
11045   DeclarationNameInfo NameInfo(Name, UsingLoc);
11046   TypeSourceInfo *TInfo =
11047       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11048   FunctionProtoTypeLoc ProtoLoc =
11049       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11050 
11051   // Check the inherited constructor is valid and find the list of base classes
11052   // from which it was inherited.
11053   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11054 
11055   bool Constexpr =
11056       BaseCtor->isConstexpr() &&
11057       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11058                                         false, BaseCtor, &ICI);
11059 
11060   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11061       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11062       BaseCtor->isExplicit(), /*Inline=*/true,
11063       /*ImplicitlyDeclared=*/true, Constexpr,
11064       InheritedConstructor(Shadow, BaseCtor));
11065   if (Shadow->isInvalidDecl())
11066     DerivedCtor->setInvalidDecl();
11067 
11068   // Build an unevaluated exception specification for this fake constructor.
11069   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11070   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11071   EPI.ExceptionSpec.Type = EST_Unevaluated;
11072   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11073   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11074                                                FPT->getParamTypes(), EPI));
11075 
11076   // Build the parameter declarations.
11077   SmallVector<ParmVarDecl *, 16> ParamDecls;
11078   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11079     TypeSourceInfo *TInfo =
11080         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11081     ParmVarDecl *PD = ParmVarDecl::Create(
11082         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11083         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11084     PD->setScopeInfo(0, I);
11085     PD->setImplicit();
11086     // Ensure attributes are propagated onto parameters (this matters for
11087     // format, pass_object_size, ...).
11088     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11089     ParamDecls.push_back(PD);
11090     ProtoLoc.setParam(I, PD);
11091   }
11092 
11093   // Set up the new constructor.
11094   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11095   DerivedCtor->setAccess(BaseCtor->getAccess());
11096   DerivedCtor->setParams(ParamDecls);
11097   Derived->addDecl(DerivedCtor);
11098 
11099   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11100     SetDeclDeleted(DerivedCtor, UsingLoc);
11101 
11102   return DerivedCtor;
11103 }
11104 
11105 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11106   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11107                                Ctor->getInheritedConstructor().getShadowDecl());
11108   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11109                             /*Diagnose*/true);
11110 }
11111 
11112 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11113                                        CXXConstructorDecl *Constructor) {
11114   CXXRecordDecl *ClassDecl = Constructor->getParent();
11115   assert(Constructor->getInheritedConstructor() &&
11116          !Constructor->doesThisDeclarationHaveABody() &&
11117          !Constructor->isDeleted());
11118   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11119     return;
11120 
11121   // Initializations are performed "as if by a defaulted default constructor",
11122   // so enter the appropriate scope.
11123   SynthesizedFunctionScope Scope(*this, Constructor);
11124 
11125   // The exception specification is needed because we are defining the
11126   // function.
11127   ResolveExceptionSpec(CurrentLocation,
11128                        Constructor->getType()->castAs<FunctionProtoType>());
11129   MarkVTableUsed(CurrentLocation, ClassDecl);
11130 
11131   // Add a context note for diagnostics produced after this point.
11132   Scope.addContextNote(CurrentLocation);
11133 
11134   ConstructorUsingShadowDecl *Shadow =
11135       Constructor->getInheritedConstructor().getShadowDecl();
11136   CXXConstructorDecl *InheritedCtor =
11137       Constructor->getInheritedConstructor().getConstructor();
11138 
11139   // [class.inhctor.init]p1:
11140   //   initialization proceeds as if a defaulted default constructor is used to
11141   //   initialize the D object and each base class subobject from which the
11142   //   constructor was inherited
11143 
11144   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11145   CXXRecordDecl *RD = Shadow->getParent();
11146   SourceLocation InitLoc = Shadow->getLocation();
11147 
11148   // Build explicit initializers for all base classes from which the
11149   // constructor was inherited.
11150   SmallVector<CXXCtorInitializer*, 8> Inits;
11151   for (bool VBase : {false, true}) {
11152     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11153       if (B.isVirtual() != VBase)
11154         continue;
11155 
11156       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11157       if (!BaseRD)
11158         continue;
11159 
11160       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11161       if (!BaseCtor.first)
11162         continue;
11163 
11164       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11165       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11166           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11167 
11168       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11169       Inits.push_back(new (Context) CXXCtorInitializer(
11170           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11171           SourceLocation()));
11172     }
11173   }
11174 
11175   // We now proceed as if for a defaulted default constructor, with the relevant
11176   // initializers replaced.
11177 
11178   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11179     Constructor->setInvalidDecl();
11180     return;
11181   }
11182 
11183   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11184   Constructor->markUsed(Context);
11185 
11186   if (ASTMutationListener *L = getASTMutationListener()) {
11187     L->CompletedImplicitDefinition(Constructor);
11188   }
11189 
11190   DiagnoseUninitializedFields(*this, Constructor);
11191 }
11192 
11193 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11194   // C++ [class.dtor]p2:
11195   //   If a class has no user-declared destructor, a destructor is
11196   //   declared implicitly. An implicitly-declared destructor is an
11197   //   inline public member of its class.
11198   assert(ClassDecl->needsImplicitDestructor());
11199 
11200   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11201   if (DSM.isAlreadyBeingDeclared())
11202     return nullptr;
11203 
11204   // Create the actual destructor declaration.
11205   CanQualType ClassType
11206     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11207   SourceLocation ClassLoc = ClassDecl->getLocation();
11208   DeclarationName Name
11209     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11210   DeclarationNameInfo NameInfo(Name, ClassLoc);
11211   CXXDestructorDecl *Destructor
11212       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11213                                   QualType(), nullptr, /*isInline=*/true,
11214                                   /*isImplicitlyDeclared=*/true);
11215   Destructor->setAccess(AS_public);
11216   Destructor->setDefaulted();
11217 
11218   if (getLangOpts().CUDA) {
11219     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11220                                             Destructor,
11221                                             /* ConstRHS */ false,
11222                                             /* Diagnose */ false);
11223   }
11224 
11225   // Build an exception specification pointing back at this destructor.
11226   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11227   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11228 
11229   // We don't need to use SpecialMemberIsTrivial here; triviality for
11230   // destructors is easy to compute.
11231   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11232   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11233                                 ClassDecl->hasTrivialDestructorForCall());
11234 
11235   // Note that we have declared this destructor.
11236   ++ASTContext::NumImplicitDestructorsDeclared;
11237 
11238   Scope *S = getScopeForContext(ClassDecl);
11239   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11240 
11241   // We can't check whether an implicit destructor is deleted before we complete
11242   // the definition of the class, because its validity depends on the alignment
11243   // of the class. We'll check this from ActOnFields once the class is complete.
11244   if (ClassDecl->isCompleteDefinition() &&
11245       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11246     SetDeclDeleted(Destructor, ClassLoc);
11247 
11248   // Introduce this destructor into its scope.
11249   if (S)
11250     PushOnScopeChains(Destructor, S, false);
11251   ClassDecl->addDecl(Destructor);
11252 
11253   return Destructor;
11254 }
11255 
11256 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11257                                     CXXDestructorDecl *Destructor) {
11258   assert((Destructor->isDefaulted() &&
11259           !Destructor->doesThisDeclarationHaveABody() &&
11260           !Destructor->isDeleted()) &&
11261          "DefineImplicitDestructor - call it for implicit default dtor");
11262   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11263     return;
11264 
11265   CXXRecordDecl *ClassDecl = Destructor->getParent();
11266   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11267 
11268   SynthesizedFunctionScope Scope(*this, Destructor);
11269 
11270   // The exception specification is needed because we are defining the
11271   // function.
11272   ResolveExceptionSpec(CurrentLocation,
11273                        Destructor->getType()->castAs<FunctionProtoType>());
11274   MarkVTableUsed(CurrentLocation, ClassDecl);
11275 
11276   // Add a context note for diagnostics produced after this point.
11277   Scope.addContextNote(CurrentLocation);
11278 
11279   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11280                                          Destructor->getParent());
11281 
11282   if (CheckDestructor(Destructor)) {
11283     Destructor->setInvalidDecl();
11284     return;
11285   }
11286 
11287   SourceLocation Loc = Destructor->getEndLoc().isValid()
11288                            ? Destructor->getEndLoc()
11289                            : Destructor->getLocation();
11290   Destructor->setBody(new (Context) CompoundStmt(Loc));
11291   Destructor->markUsed(Context);
11292 
11293   if (ASTMutationListener *L = getASTMutationListener()) {
11294     L->CompletedImplicitDefinition(Destructor);
11295   }
11296 }
11297 
11298 /// Perform any semantic analysis which needs to be delayed until all
11299 /// pending class member declarations have been parsed.
11300 void Sema::ActOnFinishCXXMemberDecls() {
11301   // If the context is an invalid C++ class, just suppress these checks.
11302   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11303     if (Record->isInvalidDecl()) {
11304       DelayedOverridingExceptionSpecChecks.clear();
11305       DelayedEquivalentExceptionSpecChecks.clear();
11306       DelayedDefaultedMemberExceptionSpecs.clear();
11307       return;
11308     }
11309     checkForMultipleExportedDefaultConstructors(*this, Record);
11310   }
11311 }
11312 
11313 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11314   referenceDLLExportedClassMethods();
11315 }
11316 
11317 void Sema::referenceDLLExportedClassMethods() {
11318   if (!DelayedDllExportClasses.empty()) {
11319     // Calling ReferenceDllExportedMembers might cause the current function to
11320     // be called again, so use a local copy of DelayedDllExportClasses.
11321     SmallVector<CXXRecordDecl *, 4> WorkList;
11322     std::swap(DelayedDllExportClasses, WorkList);
11323     for (CXXRecordDecl *Class : WorkList)
11324       ReferenceDllExportedMembers(*this, Class);
11325   }
11326 }
11327 
11328 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11329   assert(getLangOpts().CPlusPlus11 &&
11330          "adjusting dtor exception specs was introduced in c++11");
11331 
11332   if (Destructor->isDependentContext())
11333     return;
11334 
11335   // C++11 [class.dtor]p3:
11336   //   A declaration of a destructor that does not have an exception-
11337   //   specification is implicitly considered to have the same exception-
11338   //   specification as an implicit declaration.
11339   const FunctionProtoType *DtorType = Destructor->getType()->
11340                                         getAs<FunctionProtoType>();
11341   if (DtorType->hasExceptionSpec())
11342     return;
11343 
11344   // Replace the destructor's type, building off the existing one. Fortunately,
11345   // the only thing of interest in the destructor type is its extended info.
11346   // The return and arguments are fixed.
11347   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11348   EPI.ExceptionSpec.Type = EST_Unevaluated;
11349   EPI.ExceptionSpec.SourceDecl = Destructor;
11350   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11351 
11352   // FIXME: If the destructor has a body that could throw, and the newly created
11353   // spec doesn't allow exceptions, we should emit a warning, because this
11354   // change in behavior can break conforming C++03 programs at runtime.
11355   // However, we don't have a body or an exception specification yet, so it
11356   // needs to be done somewhere else.
11357 }
11358 
11359 namespace {
11360 /// An abstract base class for all helper classes used in building the
11361 //  copy/move operators. These classes serve as factory functions and help us
11362 //  avoid using the same Expr* in the AST twice.
11363 class ExprBuilder {
11364   ExprBuilder(const ExprBuilder&) = delete;
11365   ExprBuilder &operator=(const ExprBuilder&) = delete;
11366 
11367 protected:
11368   static Expr *assertNotNull(Expr *E) {
11369     assert(E && "Expression construction must not fail.");
11370     return E;
11371   }
11372 
11373 public:
11374   ExprBuilder() {}
11375   virtual ~ExprBuilder() {}
11376 
11377   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11378 };
11379 
11380 class RefBuilder: public ExprBuilder {
11381   VarDecl *Var;
11382   QualType VarType;
11383 
11384 public:
11385   Expr *build(Sema &S, SourceLocation Loc) const override {
11386     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11387   }
11388 
11389   RefBuilder(VarDecl *Var, QualType VarType)
11390       : Var(Var), VarType(VarType) {}
11391 };
11392 
11393 class ThisBuilder: public ExprBuilder {
11394 public:
11395   Expr *build(Sema &S, SourceLocation Loc) const override {
11396     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11397   }
11398 };
11399 
11400 class CastBuilder: public ExprBuilder {
11401   const ExprBuilder &Builder;
11402   QualType Type;
11403   ExprValueKind Kind;
11404   const CXXCastPath &Path;
11405 
11406 public:
11407   Expr *build(Sema &S, SourceLocation Loc) const override {
11408     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11409                                              CK_UncheckedDerivedToBase, Kind,
11410                                              &Path).get());
11411   }
11412 
11413   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11414               const CXXCastPath &Path)
11415       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11416 };
11417 
11418 class DerefBuilder: public ExprBuilder {
11419   const ExprBuilder &Builder;
11420 
11421 public:
11422   Expr *build(Sema &S, SourceLocation Loc) const override {
11423     return assertNotNull(
11424         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11425   }
11426 
11427   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11428 };
11429 
11430 class MemberBuilder: public ExprBuilder {
11431   const ExprBuilder &Builder;
11432   QualType Type;
11433   CXXScopeSpec SS;
11434   bool IsArrow;
11435   LookupResult &MemberLookup;
11436 
11437 public:
11438   Expr *build(Sema &S, SourceLocation Loc) const override {
11439     return assertNotNull(S.BuildMemberReferenceExpr(
11440         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11441         nullptr, MemberLookup, nullptr, nullptr).get());
11442   }
11443 
11444   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11445                 LookupResult &MemberLookup)
11446       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11447         MemberLookup(MemberLookup) {}
11448 };
11449 
11450 class MoveCastBuilder: public ExprBuilder {
11451   const ExprBuilder &Builder;
11452 
11453 public:
11454   Expr *build(Sema &S, SourceLocation Loc) const override {
11455     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11456   }
11457 
11458   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11459 };
11460 
11461 class LvalueConvBuilder: public ExprBuilder {
11462   const ExprBuilder &Builder;
11463 
11464 public:
11465   Expr *build(Sema &S, SourceLocation Loc) const override {
11466     return assertNotNull(
11467         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11468   }
11469 
11470   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11471 };
11472 
11473 class SubscriptBuilder: public ExprBuilder {
11474   const ExprBuilder &Base;
11475   const ExprBuilder &Index;
11476 
11477 public:
11478   Expr *build(Sema &S, SourceLocation Loc) const override {
11479     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11480         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11481   }
11482 
11483   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11484       : Base(Base), Index(Index) {}
11485 };
11486 
11487 } // end anonymous namespace
11488 
11489 /// When generating a defaulted copy or move assignment operator, if a field
11490 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11491 /// do so. This optimization only applies for arrays of scalars, and for arrays
11492 /// of class type where the selected copy/move-assignment operator is trivial.
11493 static StmtResult
11494 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11495                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11496   // Compute the size of the memory buffer to be copied.
11497   QualType SizeType = S.Context.getSizeType();
11498   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11499                    S.Context.getTypeSizeInChars(T).getQuantity());
11500 
11501   // Take the address of the field references for "from" and "to". We
11502   // directly construct UnaryOperators here because semantic analysis
11503   // does not permit us to take the address of an xvalue.
11504   Expr *From = FromB.build(S, Loc);
11505   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11506                          S.Context.getPointerType(From->getType()),
11507                          VK_RValue, OK_Ordinary, Loc, false);
11508   Expr *To = ToB.build(S, Loc);
11509   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11510                        S.Context.getPointerType(To->getType()),
11511                        VK_RValue, OK_Ordinary, Loc, false);
11512 
11513   const Type *E = T->getBaseElementTypeUnsafe();
11514   bool NeedsCollectableMemCpy =
11515     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11516 
11517   // Create a reference to the __builtin_objc_memmove_collectable function
11518   StringRef MemCpyName = NeedsCollectableMemCpy ?
11519     "__builtin_objc_memmove_collectable" :
11520     "__builtin_memcpy";
11521   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11522                  Sema::LookupOrdinaryName);
11523   S.LookupName(R, S.TUScope, true);
11524 
11525   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11526   if (!MemCpy)
11527     // Something went horribly wrong earlier, and we will have complained
11528     // about it.
11529     return StmtError();
11530 
11531   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11532                                             VK_RValue, Loc, nullptr);
11533   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11534 
11535   Expr *CallArgs[] = {
11536     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11537   };
11538   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11539                                     Loc, CallArgs, Loc);
11540 
11541   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11542   return Call.getAs<Stmt>();
11543 }
11544 
11545 /// Builds a statement that copies/moves the given entity from \p From to
11546 /// \c To.
11547 ///
11548 /// This routine is used to copy/move the members of a class with an
11549 /// implicitly-declared copy/move assignment operator. When the entities being
11550 /// copied are arrays, this routine builds for loops to copy them.
11551 ///
11552 /// \param S The Sema object used for type-checking.
11553 ///
11554 /// \param Loc The location where the implicit copy/move is being generated.
11555 ///
11556 /// \param T The type of the expressions being copied/moved. Both expressions
11557 /// must have this type.
11558 ///
11559 /// \param To The expression we are copying/moving to.
11560 ///
11561 /// \param From The expression we are copying/moving from.
11562 ///
11563 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11564 /// Otherwise, it's a non-static member subobject.
11565 ///
11566 /// \param Copying Whether we're copying or moving.
11567 ///
11568 /// \param Depth Internal parameter recording the depth of the recursion.
11569 ///
11570 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11571 /// if a memcpy should be used instead.
11572 static StmtResult
11573 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11574                                  const ExprBuilder &To, const ExprBuilder &From,
11575                                  bool CopyingBaseSubobject, bool Copying,
11576                                  unsigned Depth = 0) {
11577   // C++11 [class.copy]p28:
11578   //   Each subobject is assigned in the manner appropriate to its type:
11579   //
11580   //     - if the subobject is of class type, as if by a call to operator= with
11581   //       the subobject as the object expression and the corresponding
11582   //       subobject of x as a single function argument (as if by explicit
11583   //       qualification; that is, ignoring any possible virtual overriding
11584   //       functions in more derived classes);
11585   //
11586   // C++03 [class.copy]p13:
11587   //     - if the subobject is of class type, the copy assignment operator for
11588   //       the class is used (as if by explicit qualification; that is,
11589   //       ignoring any possible virtual overriding functions in more derived
11590   //       classes);
11591   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11592     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11593 
11594     // Look for operator=.
11595     DeclarationName Name
11596       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11597     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11598     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11599 
11600     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11601     // operator.
11602     if (!S.getLangOpts().CPlusPlus11) {
11603       LookupResult::Filter F = OpLookup.makeFilter();
11604       while (F.hasNext()) {
11605         NamedDecl *D = F.next();
11606         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11607           if (Method->isCopyAssignmentOperator() ||
11608               (!Copying && Method->isMoveAssignmentOperator()))
11609             continue;
11610 
11611         F.erase();
11612       }
11613       F.done();
11614     }
11615 
11616     // Suppress the protected check (C++ [class.protected]) for each of the
11617     // assignment operators we found. This strange dance is required when
11618     // we're assigning via a base classes's copy-assignment operator. To
11619     // ensure that we're getting the right base class subobject (without
11620     // ambiguities), we need to cast "this" to that subobject type; to
11621     // ensure that we don't go through the virtual call mechanism, we need
11622     // to qualify the operator= name with the base class (see below). However,
11623     // this means that if the base class has a protected copy assignment
11624     // operator, the protected member access check will fail. So, we
11625     // rewrite "protected" access to "public" access in this case, since we
11626     // know by construction that we're calling from a derived class.
11627     if (CopyingBaseSubobject) {
11628       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11629            L != LEnd; ++L) {
11630         if (L.getAccess() == AS_protected)
11631           L.setAccess(AS_public);
11632       }
11633     }
11634 
11635     // Create the nested-name-specifier that will be used to qualify the
11636     // reference to operator=; this is required to suppress the virtual
11637     // call mechanism.
11638     CXXScopeSpec SS;
11639     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11640     SS.MakeTrivial(S.Context,
11641                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11642                                                CanonicalT),
11643                    Loc);
11644 
11645     // Create the reference to operator=.
11646     ExprResult OpEqualRef
11647       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11648                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11649                                    /*FirstQualifierInScope=*/nullptr,
11650                                    OpLookup,
11651                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11652                                    /*SuppressQualifierCheck=*/true);
11653     if (OpEqualRef.isInvalid())
11654       return StmtError();
11655 
11656     // Build the call to the assignment operator.
11657 
11658     Expr *FromInst = From.build(S, Loc);
11659     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11660                                                   OpEqualRef.getAs<Expr>(),
11661                                                   Loc, FromInst, Loc);
11662     if (Call.isInvalid())
11663       return StmtError();
11664 
11665     // If we built a call to a trivial 'operator=' while copying an array,
11666     // bail out. We'll replace the whole shebang with a memcpy.
11667     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11668     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11669       return StmtResult((Stmt*)nullptr);
11670 
11671     // Convert to an expression-statement, and clean up any produced
11672     // temporaries.
11673     return S.ActOnExprStmt(Call);
11674   }
11675 
11676   //     - if the subobject is of scalar type, the built-in assignment
11677   //       operator is used.
11678   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11679   if (!ArrayTy) {
11680     ExprResult Assignment = S.CreateBuiltinBinOp(
11681         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11682     if (Assignment.isInvalid())
11683       return StmtError();
11684     return S.ActOnExprStmt(Assignment);
11685   }
11686 
11687   //     - if the subobject is an array, each element is assigned, in the
11688   //       manner appropriate to the element type;
11689 
11690   // Construct a loop over the array bounds, e.g.,
11691   //
11692   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11693   //
11694   // that will copy each of the array elements.
11695   QualType SizeType = S.Context.getSizeType();
11696 
11697   // Create the iteration variable.
11698   IdentifierInfo *IterationVarName = nullptr;
11699   {
11700     SmallString<8> Str;
11701     llvm::raw_svector_ostream OS(Str);
11702     OS << "__i" << Depth;
11703     IterationVarName = &S.Context.Idents.get(OS.str());
11704   }
11705   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11706                                           IterationVarName, SizeType,
11707                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11708                                           SC_None);
11709 
11710   // Initialize the iteration variable to zero.
11711   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11712   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11713 
11714   // Creates a reference to the iteration variable.
11715   RefBuilder IterationVarRef(IterationVar, SizeType);
11716   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11717 
11718   // Create the DeclStmt that holds the iteration variable.
11719   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11720 
11721   // Subscript the "from" and "to" expressions with the iteration variable.
11722   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11723   MoveCastBuilder FromIndexMove(FromIndexCopy);
11724   const ExprBuilder *FromIndex;
11725   if (Copying)
11726     FromIndex = &FromIndexCopy;
11727   else
11728     FromIndex = &FromIndexMove;
11729 
11730   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11731 
11732   // Build the copy/move for an individual element of the array.
11733   StmtResult Copy =
11734     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11735                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11736                                      Copying, Depth + 1);
11737   // Bail out if copying fails or if we determined that we should use memcpy.
11738   if (Copy.isInvalid() || !Copy.get())
11739     return Copy;
11740 
11741   // Create the comparison against the array bound.
11742   llvm::APInt Upper
11743     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11744   Expr *Comparison
11745     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11746                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11747                                      BO_NE, S.Context.BoolTy,
11748                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11749 
11750   // Create the pre-increment of the iteration variable. We can determine
11751   // whether the increment will overflow based on the value of the array
11752   // bound.
11753   Expr *Increment = new (S.Context)
11754       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11755                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11756 
11757   // Construct the loop that copies all elements of this array.
11758   return S.ActOnForStmt(
11759       Loc, Loc, InitStmt,
11760       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11761       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11762 }
11763 
11764 static StmtResult
11765 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11766                       const ExprBuilder &To, const ExprBuilder &From,
11767                       bool CopyingBaseSubobject, bool Copying) {
11768   // Maybe we should use a memcpy?
11769   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11770       T.isTriviallyCopyableType(S.Context))
11771     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11772 
11773   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11774                                                      CopyingBaseSubobject,
11775                                                      Copying, 0));
11776 
11777   // If we ended up picking a trivial assignment operator for an array of a
11778   // non-trivially-copyable class type, just emit a memcpy.
11779   if (!Result.isInvalid() && !Result.get())
11780     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11781 
11782   return Result;
11783 }
11784 
11785 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11786   // Note: The following rules are largely analoguous to the copy
11787   // constructor rules. Note that virtual bases are not taken into account
11788   // for determining the argument type of the operator. Note also that
11789   // operators taking an object instead of a reference are allowed.
11790   assert(ClassDecl->needsImplicitCopyAssignment());
11791 
11792   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11793   if (DSM.isAlreadyBeingDeclared())
11794     return nullptr;
11795 
11796   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11797   QualType RetType = Context.getLValueReferenceType(ArgType);
11798   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11799   if (Const)
11800     ArgType = ArgType.withConst();
11801   ArgType = Context.getLValueReferenceType(ArgType);
11802 
11803   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11804                                                      CXXCopyAssignment,
11805                                                      Const);
11806 
11807   //   An implicitly-declared copy assignment operator is an inline public
11808   //   member of its class.
11809   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11810   SourceLocation ClassLoc = ClassDecl->getLocation();
11811   DeclarationNameInfo NameInfo(Name, ClassLoc);
11812   CXXMethodDecl *CopyAssignment =
11813       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11814                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11815                             /*isInline=*/true, Constexpr, SourceLocation());
11816   CopyAssignment->setAccess(AS_public);
11817   CopyAssignment->setDefaulted();
11818   CopyAssignment->setImplicit();
11819 
11820   if (getLangOpts().CUDA) {
11821     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11822                                             CopyAssignment,
11823                                             /* ConstRHS */ Const,
11824                                             /* Diagnose */ false);
11825   }
11826 
11827   // Build an exception specification pointing back at this member.
11828   FunctionProtoType::ExtProtoInfo EPI =
11829       getImplicitMethodEPI(*this, CopyAssignment);
11830   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11831 
11832   // Add the parameter to the operator.
11833   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11834                                                ClassLoc, ClassLoc,
11835                                                /*Id=*/nullptr, ArgType,
11836                                                /*TInfo=*/nullptr, SC_None,
11837                                                nullptr);
11838   CopyAssignment->setParams(FromParam);
11839 
11840   CopyAssignment->setTrivial(
11841     ClassDecl->needsOverloadResolutionForCopyAssignment()
11842       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11843       : ClassDecl->hasTrivialCopyAssignment());
11844 
11845   // Note that we have added this copy-assignment operator.
11846   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11847 
11848   Scope *S = getScopeForContext(ClassDecl);
11849   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11850 
11851   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11852     SetDeclDeleted(CopyAssignment, ClassLoc);
11853 
11854   if (S)
11855     PushOnScopeChains(CopyAssignment, S, false);
11856   ClassDecl->addDecl(CopyAssignment);
11857 
11858   return CopyAssignment;
11859 }
11860 
11861 /// Diagnose an implicit copy operation for a class which is odr-used, but
11862 /// which is deprecated because the class has a user-declared copy constructor,
11863 /// copy assignment operator, or destructor.
11864 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11865   assert(CopyOp->isImplicit());
11866 
11867   CXXRecordDecl *RD = CopyOp->getParent();
11868   CXXMethodDecl *UserDeclaredOperation = nullptr;
11869 
11870   // In Microsoft mode, assignment operations don't affect constructors and
11871   // vice versa.
11872   if (RD->hasUserDeclaredDestructor()) {
11873     UserDeclaredOperation = RD->getDestructor();
11874   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11875              RD->hasUserDeclaredCopyConstructor() &&
11876              !S.getLangOpts().MSVCCompat) {
11877     // Find any user-declared copy constructor.
11878     for (auto *I : RD->ctors()) {
11879       if (I->isCopyConstructor()) {
11880         UserDeclaredOperation = I;
11881         break;
11882       }
11883     }
11884     assert(UserDeclaredOperation);
11885   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11886              RD->hasUserDeclaredCopyAssignment() &&
11887              !S.getLangOpts().MSVCCompat) {
11888     // Find any user-declared move assignment operator.
11889     for (auto *I : RD->methods()) {
11890       if (I->isCopyAssignmentOperator()) {
11891         UserDeclaredOperation = I;
11892         break;
11893       }
11894     }
11895     assert(UserDeclaredOperation);
11896   }
11897 
11898   if (UserDeclaredOperation) {
11899     S.Diag(UserDeclaredOperation->getLocation(),
11900          diag::warn_deprecated_copy_operation)
11901       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11902       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11903   }
11904 }
11905 
11906 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11907                                         CXXMethodDecl *CopyAssignOperator) {
11908   assert((CopyAssignOperator->isDefaulted() &&
11909           CopyAssignOperator->isOverloadedOperator() &&
11910           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11911           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11912           !CopyAssignOperator->isDeleted()) &&
11913          "DefineImplicitCopyAssignment called for wrong function");
11914   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11915     return;
11916 
11917   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11918   if (ClassDecl->isInvalidDecl()) {
11919     CopyAssignOperator->setInvalidDecl();
11920     return;
11921   }
11922 
11923   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11924 
11925   // The exception specification is needed because we are defining the
11926   // function.
11927   ResolveExceptionSpec(CurrentLocation,
11928                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11929 
11930   // Add a context note for diagnostics produced after this point.
11931   Scope.addContextNote(CurrentLocation);
11932 
11933   // C++11 [class.copy]p18:
11934   //   The [definition of an implicitly declared copy assignment operator] is
11935   //   deprecated if the class has a user-declared copy constructor or a
11936   //   user-declared destructor.
11937   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11938     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11939 
11940   // C++0x [class.copy]p30:
11941   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11942   //   for a non-union class X performs memberwise copy assignment of its
11943   //   subobjects. The direct base classes of X are assigned first, in the
11944   //   order of their declaration in the base-specifier-list, and then the
11945   //   immediate non-static data members of X are assigned, in the order in
11946   //   which they were declared in the class definition.
11947 
11948   // The statements that form the synthesized function body.
11949   SmallVector<Stmt*, 8> Statements;
11950 
11951   // The parameter for the "other" object, which we are copying from.
11952   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11953   Qualifiers OtherQuals = Other->getType().getQualifiers();
11954   QualType OtherRefType = Other->getType();
11955   if (const LValueReferenceType *OtherRef
11956                                 = OtherRefType->getAs<LValueReferenceType>()) {
11957     OtherRefType = OtherRef->getPointeeType();
11958     OtherQuals = OtherRefType.getQualifiers();
11959   }
11960 
11961   // Our location for everything implicitly-generated.
11962   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11963                            ? CopyAssignOperator->getEndLoc()
11964                            : CopyAssignOperator->getLocation();
11965 
11966   // Builds a DeclRefExpr for the "other" object.
11967   RefBuilder OtherRef(Other, OtherRefType);
11968 
11969   // Builds the "this" pointer.
11970   ThisBuilder This;
11971 
11972   // Assign base classes.
11973   bool Invalid = false;
11974   for (auto &Base : ClassDecl->bases()) {
11975     // Form the assignment:
11976     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11977     QualType BaseType = Base.getType().getUnqualifiedType();
11978     if (!BaseType->isRecordType()) {
11979       Invalid = true;
11980       continue;
11981     }
11982 
11983     CXXCastPath BasePath;
11984     BasePath.push_back(&Base);
11985 
11986     // Construct the "from" expression, which is an implicit cast to the
11987     // appropriately-qualified base type.
11988     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11989                      VK_LValue, BasePath);
11990 
11991     // Dereference "this".
11992     DerefBuilder DerefThis(This);
11993     CastBuilder To(DerefThis,
11994                    Context.getCVRQualifiedType(
11995                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11996                    VK_LValue, BasePath);
11997 
11998     // Build the copy.
11999     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12000                                             To, From,
12001                                             /*CopyingBaseSubobject=*/true,
12002                                             /*Copying=*/true);
12003     if (Copy.isInvalid()) {
12004       CopyAssignOperator->setInvalidDecl();
12005       return;
12006     }
12007 
12008     // Success! Record the copy.
12009     Statements.push_back(Copy.getAs<Expr>());
12010   }
12011 
12012   // Assign non-static members.
12013   for (auto *Field : ClassDecl->fields()) {
12014     // FIXME: We should form some kind of AST representation for the implied
12015     // memcpy in a union copy operation.
12016     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12017       continue;
12018 
12019     if (Field->isInvalidDecl()) {
12020       Invalid = true;
12021       continue;
12022     }
12023 
12024     // Check for members of reference type; we can't copy those.
12025     if (Field->getType()->isReferenceType()) {
12026       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12027         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12028       Diag(Field->getLocation(), diag::note_declared_at);
12029       Invalid = true;
12030       continue;
12031     }
12032 
12033     // Check for members of const-qualified, non-class type.
12034     QualType BaseType = Context.getBaseElementType(Field->getType());
12035     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12036       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12037         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12038       Diag(Field->getLocation(), diag::note_declared_at);
12039       Invalid = true;
12040       continue;
12041     }
12042 
12043     // Suppress assigning zero-width bitfields.
12044     if (Field->isZeroLengthBitField(Context))
12045       continue;
12046 
12047     QualType FieldType = Field->getType().getNonReferenceType();
12048     if (FieldType->isIncompleteArrayType()) {
12049       assert(ClassDecl->hasFlexibleArrayMember() &&
12050              "Incomplete array type is not valid");
12051       continue;
12052     }
12053 
12054     // Build references to the field in the object we're copying from and to.
12055     CXXScopeSpec SS; // Intentionally empty
12056     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12057                               LookupMemberName);
12058     MemberLookup.addDecl(Field);
12059     MemberLookup.resolveKind();
12060 
12061     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12062 
12063     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12064 
12065     // Build the copy of this field.
12066     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12067                                             To, From,
12068                                             /*CopyingBaseSubobject=*/false,
12069                                             /*Copying=*/true);
12070     if (Copy.isInvalid()) {
12071       CopyAssignOperator->setInvalidDecl();
12072       return;
12073     }
12074 
12075     // Success! Record the copy.
12076     Statements.push_back(Copy.getAs<Stmt>());
12077   }
12078 
12079   if (!Invalid) {
12080     // Add a "return *this;"
12081     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12082 
12083     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12084     if (Return.isInvalid())
12085       Invalid = true;
12086     else
12087       Statements.push_back(Return.getAs<Stmt>());
12088   }
12089 
12090   if (Invalid) {
12091     CopyAssignOperator->setInvalidDecl();
12092     return;
12093   }
12094 
12095   StmtResult Body;
12096   {
12097     CompoundScopeRAII CompoundScope(*this);
12098     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12099                              /*isStmtExpr=*/false);
12100     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12101   }
12102   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12103   CopyAssignOperator->markUsed(Context);
12104 
12105   if (ASTMutationListener *L = getASTMutationListener()) {
12106     L->CompletedImplicitDefinition(CopyAssignOperator);
12107   }
12108 }
12109 
12110 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12111   assert(ClassDecl->needsImplicitMoveAssignment());
12112 
12113   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12114   if (DSM.isAlreadyBeingDeclared())
12115     return nullptr;
12116 
12117   // Note: The following rules are largely analoguous to the move
12118   // constructor rules.
12119 
12120   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12121   QualType RetType = Context.getLValueReferenceType(ArgType);
12122   ArgType = Context.getRValueReferenceType(ArgType);
12123 
12124   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12125                                                      CXXMoveAssignment,
12126                                                      false);
12127 
12128   //   An implicitly-declared move assignment operator is an inline public
12129   //   member of its class.
12130   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12131   SourceLocation ClassLoc = ClassDecl->getLocation();
12132   DeclarationNameInfo NameInfo(Name, ClassLoc);
12133   CXXMethodDecl *MoveAssignment =
12134       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12135                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12136                             /*isInline=*/true, Constexpr, SourceLocation());
12137   MoveAssignment->setAccess(AS_public);
12138   MoveAssignment->setDefaulted();
12139   MoveAssignment->setImplicit();
12140 
12141   if (getLangOpts().CUDA) {
12142     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12143                                             MoveAssignment,
12144                                             /* ConstRHS */ false,
12145                                             /* Diagnose */ false);
12146   }
12147 
12148   // Build an exception specification pointing back at this member.
12149   FunctionProtoType::ExtProtoInfo EPI =
12150       getImplicitMethodEPI(*this, MoveAssignment);
12151   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12152 
12153   // Add the parameter to the operator.
12154   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12155                                                ClassLoc, ClassLoc,
12156                                                /*Id=*/nullptr, ArgType,
12157                                                /*TInfo=*/nullptr, SC_None,
12158                                                nullptr);
12159   MoveAssignment->setParams(FromParam);
12160 
12161   MoveAssignment->setTrivial(
12162     ClassDecl->needsOverloadResolutionForMoveAssignment()
12163       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12164       : ClassDecl->hasTrivialMoveAssignment());
12165 
12166   // Note that we have added this copy-assignment operator.
12167   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12168 
12169   Scope *S = getScopeForContext(ClassDecl);
12170   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12171 
12172   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12173     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12174     SetDeclDeleted(MoveAssignment, ClassLoc);
12175   }
12176 
12177   if (S)
12178     PushOnScopeChains(MoveAssignment, S, false);
12179   ClassDecl->addDecl(MoveAssignment);
12180 
12181   return MoveAssignment;
12182 }
12183 
12184 /// Check if we're implicitly defining a move assignment operator for a class
12185 /// with virtual bases. Such a move assignment might move-assign the virtual
12186 /// base multiple times.
12187 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12188                                                SourceLocation CurrentLocation) {
12189   assert(!Class->isDependentContext() && "should not define dependent move");
12190 
12191   // Only a virtual base could get implicitly move-assigned multiple times.
12192   // Only a non-trivial move assignment can observe this. We only want to
12193   // diagnose if we implicitly define an assignment operator that assigns
12194   // two base classes, both of which move-assign the same virtual base.
12195   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12196       Class->getNumBases() < 2)
12197     return;
12198 
12199   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12200   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12201   VBaseMap VBases;
12202 
12203   for (auto &BI : Class->bases()) {
12204     Worklist.push_back(&BI);
12205     while (!Worklist.empty()) {
12206       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12207       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12208 
12209       // If the base has no non-trivial move assignment operators,
12210       // we don't care about moves from it.
12211       if (!Base->hasNonTrivialMoveAssignment())
12212         continue;
12213 
12214       // If there's nothing virtual here, skip it.
12215       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12216         continue;
12217 
12218       // If we're not actually going to call a move assignment for this base,
12219       // or the selected move assignment is trivial, skip it.
12220       Sema::SpecialMemberOverloadResult SMOR =
12221         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12222                               /*ConstArg*/false, /*VolatileArg*/false,
12223                               /*RValueThis*/true, /*ConstThis*/false,
12224                               /*VolatileThis*/false);
12225       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12226           !SMOR.getMethod()->isMoveAssignmentOperator())
12227         continue;
12228 
12229       if (BaseSpec->isVirtual()) {
12230         // We're going to move-assign this virtual base, and its move
12231         // assignment operator is not trivial. If this can happen for
12232         // multiple distinct direct bases of Class, diagnose it. (If it
12233         // only happens in one base, we'll diagnose it when synthesizing
12234         // that base class's move assignment operator.)
12235         CXXBaseSpecifier *&Existing =
12236             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12237                 .first->second;
12238         if (Existing && Existing != &BI) {
12239           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12240             << Class << Base;
12241           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12242               << (Base->getCanonicalDecl() ==
12243                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12244               << Base << Existing->getType() << Existing->getSourceRange();
12245           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12246               << (Base->getCanonicalDecl() ==
12247                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12248               << Base << BI.getType() << BaseSpec->getSourceRange();
12249 
12250           // Only diagnose each vbase once.
12251           Existing = nullptr;
12252         }
12253       } else {
12254         // Only walk over bases that have defaulted move assignment operators.
12255         // We assume that any user-provided move assignment operator handles
12256         // the multiple-moves-of-vbase case itself somehow.
12257         if (!SMOR.getMethod()->isDefaulted())
12258           continue;
12259 
12260         // We're going to move the base classes of Base. Add them to the list.
12261         for (auto &BI : Base->bases())
12262           Worklist.push_back(&BI);
12263       }
12264     }
12265   }
12266 }
12267 
12268 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12269                                         CXXMethodDecl *MoveAssignOperator) {
12270   assert((MoveAssignOperator->isDefaulted() &&
12271           MoveAssignOperator->isOverloadedOperator() &&
12272           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12273           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12274           !MoveAssignOperator->isDeleted()) &&
12275          "DefineImplicitMoveAssignment called for wrong function");
12276   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12277     return;
12278 
12279   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12280   if (ClassDecl->isInvalidDecl()) {
12281     MoveAssignOperator->setInvalidDecl();
12282     return;
12283   }
12284 
12285   // C++0x [class.copy]p28:
12286   //   The implicitly-defined or move assignment operator for a non-union class
12287   //   X performs memberwise move assignment of its subobjects. The direct base
12288   //   classes of X are assigned first, in the order of their declaration in the
12289   //   base-specifier-list, and then the immediate non-static data members of X
12290   //   are assigned, in the order in which they were declared in the class
12291   //   definition.
12292 
12293   // Issue a warning if our implicit move assignment operator will move
12294   // from a virtual base more than once.
12295   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12296 
12297   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12298 
12299   // The exception specification is needed because we are defining the
12300   // function.
12301   ResolveExceptionSpec(CurrentLocation,
12302                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12303 
12304   // Add a context note for diagnostics produced after this point.
12305   Scope.addContextNote(CurrentLocation);
12306 
12307   // The statements that form the synthesized function body.
12308   SmallVector<Stmt*, 8> Statements;
12309 
12310   // The parameter for the "other" object, which we are move from.
12311   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12312   QualType OtherRefType = Other->getType()->
12313       getAs<RValueReferenceType>()->getPointeeType();
12314   assert(!OtherRefType.getQualifiers() &&
12315          "Bad argument type of defaulted move assignment");
12316 
12317   // Our location for everything implicitly-generated.
12318   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12319                            ? MoveAssignOperator->getEndLoc()
12320                            : MoveAssignOperator->getLocation();
12321 
12322   // Builds a reference to the "other" object.
12323   RefBuilder OtherRef(Other, OtherRefType);
12324   // Cast to rvalue.
12325   MoveCastBuilder MoveOther(OtherRef);
12326 
12327   // Builds the "this" pointer.
12328   ThisBuilder This;
12329 
12330   // Assign base classes.
12331   bool Invalid = false;
12332   for (auto &Base : ClassDecl->bases()) {
12333     // C++11 [class.copy]p28:
12334     //   It is unspecified whether subobjects representing virtual base classes
12335     //   are assigned more than once by the implicitly-defined copy assignment
12336     //   operator.
12337     // FIXME: Do not assign to a vbase that will be assigned by some other base
12338     // class. For a move-assignment, this can result in the vbase being moved
12339     // multiple times.
12340 
12341     // Form the assignment:
12342     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12343     QualType BaseType = Base.getType().getUnqualifiedType();
12344     if (!BaseType->isRecordType()) {
12345       Invalid = true;
12346       continue;
12347     }
12348 
12349     CXXCastPath BasePath;
12350     BasePath.push_back(&Base);
12351 
12352     // Construct the "from" expression, which is an implicit cast to the
12353     // appropriately-qualified base type.
12354     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12355 
12356     // Dereference "this".
12357     DerefBuilder DerefThis(This);
12358 
12359     // Implicitly cast "this" to the appropriately-qualified base type.
12360     CastBuilder To(DerefThis,
12361                    Context.getCVRQualifiedType(
12362                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12363                    VK_LValue, BasePath);
12364 
12365     // Build the move.
12366     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12367                                             To, From,
12368                                             /*CopyingBaseSubobject=*/true,
12369                                             /*Copying=*/false);
12370     if (Move.isInvalid()) {
12371       MoveAssignOperator->setInvalidDecl();
12372       return;
12373     }
12374 
12375     // Success! Record the move.
12376     Statements.push_back(Move.getAs<Expr>());
12377   }
12378 
12379   // Assign non-static members.
12380   for (auto *Field : ClassDecl->fields()) {
12381     // FIXME: We should form some kind of AST representation for the implied
12382     // memcpy in a union copy operation.
12383     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12384       continue;
12385 
12386     if (Field->isInvalidDecl()) {
12387       Invalid = true;
12388       continue;
12389     }
12390 
12391     // Check for members of reference type; we can't move those.
12392     if (Field->getType()->isReferenceType()) {
12393       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12394         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12395       Diag(Field->getLocation(), diag::note_declared_at);
12396       Invalid = true;
12397       continue;
12398     }
12399 
12400     // Check for members of const-qualified, non-class type.
12401     QualType BaseType = Context.getBaseElementType(Field->getType());
12402     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12403       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12404         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12405       Diag(Field->getLocation(), diag::note_declared_at);
12406       Invalid = true;
12407       continue;
12408     }
12409 
12410     // Suppress assigning zero-width bitfields.
12411     if (Field->isZeroLengthBitField(Context))
12412       continue;
12413 
12414     QualType FieldType = Field->getType().getNonReferenceType();
12415     if (FieldType->isIncompleteArrayType()) {
12416       assert(ClassDecl->hasFlexibleArrayMember() &&
12417              "Incomplete array type is not valid");
12418       continue;
12419     }
12420 
12421     // Build references to the field in the object we're copying from and to.
12422     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12423                               LookupMemberName);
12424     MemberLookup.addDecl(Field);
12425     MemberLookup.resolveKind();
12426     MemberBuilder From(MoveOther, OtherRefType,
12427                        /*IsArrow=*/false, MemberLookup);
12428     MemberBuilder To(This, getCurrentThisType(),
12429                      /*IsArrow=*/true, MemberLookup);
12430 
12431     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12432         "Member reference with rvalue base must be rvalue except for reference "
12433         "members, which aren't allowed for move assignment.");
12434 
12435     // Build the move of this field.
12436     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12437                                             To, From,
12438                                             /*CopyingBaseSubobject=*/false,
12439                                             /*Copying=*/false);
12440     if (Move.isInvalid()) {
12441       MoveAssignOperator->setInvalidDecl();
12442       return;
12443     }
12444 
12445     // Success! Record the copy.
12446     Statements.push_back(Move.getAs<Stmt>());
12447   }
12448 
12449   if (!Invalid) {
12450     // Add a "return *this;"
12451     ExprResult ThisObj =
12452         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12453 
12454     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12455     if (Return.isInvalid())
12456       Invalid = true;
12457     else
12458       Statements.push_back(Return.getAs<Stmt>());
12459   }
12460 
12461   if (Invalid) {
12462     MoveAssignOperator->setInvalidDecl();
12463     return;
12464   }
12465 
12466   StmtResult Body;
12467   {
12468     CompoundScopeRAII CompoundScope(*this);
12469     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12470                              /*isStmtExpr=*/false);
12471     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12472   }
12473   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12474   MoveAssignOperator->markUsed(Context);
12475 
12476   if (ASTMutationListener *L = getASTMutationListener()) {
12477     L->CompletedImplicitDefinition(MoveAssignOperator);
12478   }
12479 }
12480 
12481 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12482                                                     CXXRecordDecl *ClassDecl) {
12483   // C++ [class.copy]p4:
12484   //   If the class definition does not explicitly declare a copy
12485   //   constructor, one is declared implicitly.
12486   assert(ClassDecl->needsImplicitCopyConstructor());
12487 
12488   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12489   if (DSM.isAlreadyBeingDeclared())
12490     return nullptr;
12491 
12492   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12493   QualType ArgType = ClassType;
12494   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12495   if (Const)
12496     ArgType = ArgType.withConst();
12497   ArgType = Context.getLValueReferenceType(ArgType);
12498 
12499   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12500                                                      CXXCopyConstructor,
12501                                                      Const);
12502 
12503   DeclarationName Name
12504     = Context.DeclarationNames.getCXXConstructorName(
12505                                            Context.getCanonicalType(ClassType));
12506   SourceLocation ClassLoc = ClassDecl->getLocation();
12507   DeclarationNameInfo NameInfo(Name, ClassLoc);
12508 
12509   //   An implicitly-declared copy constructor is an inline public
12510   //   member of its class.
12511   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12512       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12513       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12514       Constexpr);
12515   CopyConstructor->setAccess(AS_public);
12516   CopyConstructor->setDefaulted();
12517 
12518   if (getLangOpts().CUDA) {
12519     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12520                                             CopyConstructor,
12521                                             /* ConstRHS */ Const,
12522                                             /* Diagnose */ false);
12523   }
12524 
12525   // Build an exception specification pointing back at this member.
12526   FunctionProtoType::ExtProtoInfo EPI =
12527       getImplicitMethodEPI(*this, CopyConstructor);
12528   CopyConstructor->setType(
12529       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12530 
12531   // Add the parameter to the constructor.
12532   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12533                                                ClassLoc, ClassLoc,
12534                                                /*IdentifierInfo=*/nullptr,
12535                                                ArgType, /*TInfo=*/nullptr,
12536                                                SC_None, nullptr);
12537   CopyConstructor->setParams(FromParam);
12538 
12539   CopyConstructor->setTrivial(
12540       ClassDecl->needsOverloadResolutionForCopyConstructor()
12541           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12542           : ClassDecl->hasTrivialCopyConstructor());
12543 
12544   CopyConstructor->setTrivialForCall(
12545       ClassDecl->hasAttr<TrivialABIAttr>() ||
12546       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12547            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12548              TAH_ConsiderTrivialABI)
12549            : ClassDecl->hasTrivialCopyConstructorForCall()));
12550 
12551   // Note that we have declared this constructor.
12552   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12553 
12554   Scope *S = getScopeForContext(ClassDecl);
12555   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12556 
12557   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12558     ClassDecl->setImplicitCopyConstructorIsDeleted();
12559     SetDeclDeleted(CopyConstructor, ClassLoc);
12560   }
12561 
12562   if (S)
12563     PushOnScopeChains(CopyConstructor, S, false);
12564   ClassDecl->addDecl(CopyConstructor);
12565 
12566   return CopyConstructor;
12567 }
12568 
12569 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12570                                          CXXConstructorDecl *CopyConstructor) {
12571   assert((CopyConstructor->isDefaulted() &&
12572           CopyConstructor->isCopyConstructor() &&
12573           !CopyConstructor->doesThisDeclarationHaveABody() &&
12574           !CopyConstructor->isDeleted()) &&
12575          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12576   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12577     return;
12578 
12579   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12580   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12581 
12582   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12583 
12584   // The exception specification is needed because we are defining the
12585   // function.
12586   ResolveExceptionSpec(CurrentLocation,
12587                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12588   MarkVTableUsed(CurrentLocation, ClassDecl);
12589 
12590   // Add a context note for diagnostics produced after this point.
12591   Scope.addContextNote(CurrentLocation);
12592 
12593   // C++11 [class.copy]p7:
12594   //   The [definition of an implicitly declared copy constructor] is
12595   //   deprecated if the class has a user-declared copy assignment operator
12596   //   or a user-declared destructor.
12597   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12598     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12599 
12600   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12601     CopyConstructor->setInvalidDecl();
12602   }  else {
12603     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12604                              ? CopyConstructor->getEndLoc()
12605                              : CopyConstructor->getLocation();
12606     Sema::CompoundScopeRAII CompoundScope(*this);
12607     CopyConstructor->setBody(
12608         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12609     CopyConstructor->markUsed(Context);
12610   }
12611 
12612   if (ASTMutationListener *L = getASTMutationListener()) {
12613     L->CompletedImplicitDefinition(CopyConstructor);
12614   }
12615 }
12616 
12617 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12618                                                     CXXRecordDecl *ClassDecl) {
12619   assert(ClassDecl->needsImplicitMoveConstructor());
12620 
12621   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12622   if (DSM.isAlreadyBeingDeclared())
12623     return nullptr;
12624 
12625   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12626   QualType ArgType = Context.getRValueReferenceType(ClassType);
12627 
12628   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12629                                                      CXXMoveConstructor,
12630                                                      false);
12631 
12632   DeclarationName Name
12633     = Context.DeclarationNames.getCXXConstructorName(
12634                                            Context.getCanonicalType(ClassType));
12635   SourceLocation ClassLoc = ClassDecl->getLocation();
12636   DeclarationNameInfo NameInfo(Name, ClassLoc);
12637 
12638   // C++11 [class.copy]p11:
12639   //   An implicitly-declared copy/move constructor is an inline public
12640   //   member of its class.
12641   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12642       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12643       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12644       Constexpr);
12645   MoveConstructor->setAccess(AS_public);
12646   MoveConstructor->setDefaulted();
12647 
12648   if (getLangOpts().CUDA) {
12649     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12650                                             MoveConstructor,
12651                                             /* ConstRHS */ false,
12652                                             /* Diagnose */ false);
12653   }
12654 
12655   // Build an exception specification pointing back at this member.
12656   FunctionProtoType::ExtProtoInfo EPI =
12657       getImplicitMethodEPI(*this, MoveConstructor);
12658   MoveConstructor->setType(
12659       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12660 
12661   // Add the parameter to the constructor.
12662   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12663                                                ClassLoc, ClassLoc,
12664                                                /*IdentifierInfo=*/nullptr,
12665                                                ArgType, /*TInfo=*/nullptr,
12666                                                SC_None, nullptr);
12667   MoveConstructor->setParams(FromParam);
12668 
12669   MoveConstructor->setTrivial(
12670       ClassDecl->needsOverloadResolutionForMoveConstructor()
12671           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12672           : ClassDecl->hasTrivialMoveConstructor());
12673 
12674   MoveConstructor->setTrivialForCall(
12675       ClassDecl->hasAttr<TrivialABIAttr>() ||
12676       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12677            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12678                                     TAH_ConsiderTrivialABI)
12679            : ClassDecl->hasTrivialMoveConstructorForCall()));
12680 
12681   // Note that we have declared this constructor.
12682   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12683 
12684   Scope *S = getScopeForContext(ClassDecl);
12685   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12686 
12687   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12688     ClassDecl->setImplicitMoveConstructorIsDeleted();
12689     SetDeclDeleted(MoveConstructor, ClassLoc);
12690   }
12691 
12692   if (S)
12693     PushOnScopeChains(MoveConstructor, S, false);
12694   ClassDecl->addDecl(MoveConstructor);
12695 
12696   return MoveConstructor;
12697 }
12698 
12699 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12700                                          CXXConstructorDecl *MoveConstructor) {
12701   assert((MoveConstructor->isDefaulted() &&
12702           MoveConstructor->isMoveConstructor() &&
12703           !MoveConstructor->doesThisDeclarationHaveABody() &&
12704           !MoveConstructor->isDeleted()) &&
12705          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12706   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12707     return;
12708 
12709   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12710   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12711 
12712   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12713 
12714   // The exception specification is needed because we are defining the
12715   // function.
12716   ResolveExceptionSpec(CurrentLocation,
12717                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12718   MarkVTableUsed(CurrentLocation, ClassDecl);
12719 
12720   // Add a context note for diagnostics produced after this point.
12721   Scope.addContextNote(CurrentLocation);
12722 
12723   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12724     MoveConstructor->setInvalidDecl();
12725   } else {
12726     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12727                              ? MoveConstructor->getEndLoc()
12728                              : MoveConstructor->getLocation();
12729     Sema::CompoundScopeRAII CompoundScope(*this);
12730     MoveConstructor->setBody(ActOnCompoundStmt(
12731         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12732     MoveConstructor->markUsed(Context);
12733   }
12734 
12735   if (ASTMutationListener *L = getASTMutationListener()) {
12736     L->CompletedImplicitDefinition(MoveConstructor);
12737   }
12738 }
12739 
12740 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12741   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12742 }
12743 
12744 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12745                             SourceLocation CurrentLocation,
12746                             CXXConversionDecl *Conv) {
12747   SynthesizedFunctionScope Scope(*this, Conv);
12748   assert(!Conv->getReturnType()->isUndeducedType());
12749 
12750   CXXRecordDecl *Lambda = Conv->getParent();
12751   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12752   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12753 
12754   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12755     CallOp = InstantiateFunctionDeclaration(
12756         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12757     if (!CallOp)
12758       return;
12759 
12760     Invoker = InstantiateFunctionDeclaration(
12761         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12762     if (!Invoker)
12763       return;
12764   }
12765 
12766   if (CallOp->isInvalidDecl())
12767     return;
12768 
12769   // Mark the call operator referenced (and add to pending instantiations
12770   // if necessary).
12771   // For both the conversion and static-invoker template specializations
12772   // we construct their body's in this function, so no need to add them
12773   // to the PendingInstantiations.
12774   MarkFunctionReferenced(CurrentLocation, CallOp);
12775 
12776   // Fill in the __invoke function with a dummy implementation. IR generation
12777   // will fill in the actual details. Update its type in case it contained
12778   // an 'auto'.
12779   Invoker->markUsed(Context);
12780   Invoker->setReferenced();
12781   Invoker->setType(Conv->getReturnType()->getPointeeType());
12782   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12783 
12784   // Construct the body of the conversion function { return __invoke; }.
12785   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12786                                        VK_LValue, Conv->getLocation()).get();
12787   assert(FunctionRef && "Can't refer to __invoke function?");
12788   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12789   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12790                                      Conv->getLocation()));
12791   Conv->markUsed(Context);
12792   Conv->setReferenced();
12793 
12794   if (ASTMutationListener *L = getASTMutationListener()) {
12795     L->CompletedImplicitDefinition(Conv);
12796     L->CompletedImplicitDefinition(Invoker);
12797   }
12798 }
12799 
12800 
12801 
12802 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12803        SourceLocation CurrentLocation,
12804        CXXConversionDecl *Conv)
12805 {
12806   assert(!Conv->getParent()->isGenericLambda());
12807 
12808   SynthesizedFunctionScope Scope(*this, Conv);
12809 
12810   // Copy-initialize the lambda object as needed to capture it.
12811   Expr *This = ActOnCXXThis(CurrentLocation).get();
12812   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12813 
12814   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12815                                                         Conv->getLocation(),
12816                                                         Conv, DerefThis);
12817 
12818   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12819   // behavior.  Note that only the general conversion function does this
12820   // (since it's unusable otherwise); in the case where we inline the
12821   // block literal, it has block literal lifetime semantics.
12822   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12823     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12824                                           CK_CopyAndAutoreleaseBlockObject,
12825                                           BuildBlock.get(), nullptr, VK_RValue);
12826 
12827   if (BuildBlock.isInvalid()) {
12828     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12829     Conv->setInvalidDecl();
12830     return;
12831   }
12832 
12833   // Create the return statement that returns the block from the conversion
12834   // function.
12835   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12836   if (Return.isInvalid()) {
12837     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12838     Conv->setInvalidDecl();
12839     return;
12840   }
12841 
12842   // Set the body of the conversion function.
12843   Stmt *ReturnS = Return.get();
12844   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12845                                      Conv->getLocation()));
12846   Conv->markUsed(Context);
12847 
12848   // We're done; notify the mutation listener, if any.
12849   if (ASTMutationListener *L = getASTMutationListener()) {
12850     L->CompletedImplicitDefinition(Conv);
12851   }
12852 }
12853 
12854 /// Determine whether the given list arguments contains exactly one
12855 /// "real" (non-default) argument.
12856 static bool hasOneRealArgument(MultiExprArg Args) {
12857   switch (Args.size()) {
12858   case 0:
12859     return false;
12860 
12861   default:
12862     if (!Args[1]->isDefaultArgument())
12863       return false;
12864 
12865     LLVM_FALLTHROUGH;
12866   case 1:
12867     return !Args[0]->isDefaultArgument();
12868   }
12869 
12870   return false;
12871 }
12872 
12873 ExprResult
12874 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12875                             NamedDecl *FoundDecl,
12876                             CXXConstructorDecl *Constructor,
12877                             MultiExprArg ExprArgs,
12878                             bool HadMultipleCandidates,
12879                             bool IsListInitialization,
12880                             bool IsStdInitListInitialization,
12881                             bool RequiresZeroInit,
12882                             unsigned ConstructKind,
12883                             SourceRange ParenRange) {
12884   bool Elidable = false;
12885 
12886   // C++0x [class.copy]p34:
12887   //   When certain criteria are met, an implementation is allowed to
12888   //   omit the copy/move construction of a class object, even if the
12889   //   copy/move constructor and/or destructor for the object have
12890   //   side effects. [...]
12891   //     - when a temporary class object that has not been bound to a
12892   //       reference (12.2) would be copied/moved to a class object
12893   //       with the same cv-unqualified type, the copy/move operation
12894   //       can be omitted by constructing the temporary object
12895   //       directly into the target of the omitted copy/move
12896   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12897       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12898     Expr *SubExpr = ExprArgs[0];
12899     Elidable = SubExpr->isTemporaryObject(
12900         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12901   }
12902 
12903   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12904                                FoundDecl, Constructor,
12905                                Elidable, ExprArgs, HadMultipleCandidates,
12906                                IsListInitialization,
12907                                IsStdInitListInitialization, RequiresZeroInit,
12908                                ConstructKind, ParenRange);
12909 }
12910 
12911 ExprResult
12912 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12913                             NamedDecl *FoundDecl,
12914                             CXXConstructorDecl *Constructor,
12915                             bool Elidable,
12916                             MultiExprArg ExprArgs,
12917                             bool HadMultipleCandidates,
12918                             bool IsListInitialization,
12919                             bool IsStdInitListInitialization,
12920                             bool RequiresZeroInit,
12921                             unsigned ConstructKind,
12922                             SourceRange ParenRange) {
12923   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12924     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12925     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12926       return ExprError();
12927   }
12928 
12929   return BuildCXXConstructExpr(
12930       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12931       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12932       RequiresZeroInit, ConstructKind, ParenRange);
12933 }
12934 
12935 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12936 /// including handling of its default argument expressions.
12937 ExprResult
12938 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12939                             CXXConstructorDecl *Constructor,
12940                             bool Elidable,
12941                             MultiExprArg ExprArgs,
12942                             bool HadMultipleCandidates,
12943                             bool IsListInitialization,
12944                             bool IsStdInitListInitialization,
12945                             bool RequiresZeroInit,
12946                             unsigned ConstructKind,
12947                             SourceRange ParenRange) {
12948   assert(declaresSameEntity(
12949              Constructor->getParent(),
12950              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12951          "given constructor for wrong type");
12952   MarkFunctionReferenced(ConstructLoc, Constructor);
12953   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12954     return ExprError();
12955 
12956   return CXXConstructExpr::Create(
12957       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12958       ExprArgs, HadMultipleCandidates, IsListInitialization,
12959       IsStdInitListInitialization, RequiresZeroInit,
12960       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12961       ParenRange);
12962 }
12963 
12964 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12965   assert(Field->hasInClassInitializer());
12966 
12967   // If we already have the in-class initializer nothing needs to be done.
12968   if (Field->getInClassInitializer())
12969     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12970 
12971   // If we might have already tried and failed to instantiate, don't try again.
12972   if (Field->isInvalidDecl())
12973     return ExprError();
12974 
12975   // Maybe we haven't instantiated the in-class initializer. Go check the
12976   // pattern FieldDecl to see if it has one.
12977   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12978 
12979   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12980     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12981     DeclContext::lookup_result Lookup =
12982         ClassPattern->lookup(Field->getDeclName());
12983 
12984     // Lookup can return at most two results: the pattern for the field, or the
12985     // injected class name of the parent record. No other member can have the
12986     // same name as the field.
12987     // In modules mode, lookup can return multiple results (coming from
12988     // different modules).
12989     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12990            "more than two lookup results for field name");
12991     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12992     if (!Pattern) {
12993       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12994              "cannot have other non-field member with same name");
12995       for (auto L : Lookup)
12996         if (isa<FieldDecl>(L)) {
12997           Pattern = cast<FieldDecl>(L);
12998           break;
12999         }
13000       assert(Pattern && "We must have set the Pattern!");
13001     }
13002 
13003     if (!Pattern->hasInClassInitializer() ||
13004         InstantiateInClassInitializer(Loc, Field, Pattern,
13005                                       getTemplateInstantiationArgs(Field))) {
13006       // Don't diagnose this again.
13007       Field->setInvalidDecl();
13008       return ExprError();
13009     }
13010     return CXXDefaultInitExpr::Create(Context, Loc, Field);
13011   }
13012 
13013   // DR1351:
13014   //   If the brace-or-equal-initializer of a non-static data member
13015   //   invokes a defaulted default constructor of its class or of an
13016   //   enclosing class in a potentially evaluated subexpression, the
13017   //   program is ill-formed.
13018   //
13019   // This resolution is unworkable: the exception specification of the
13020   // default constructor can be needed in an unevaluated context, in
13021   // particular, in the operand of a noexcept-expression, and we can be
13022   // unable to compute an exception specification for an enclosed class.
13023   //
13024   // Any attempt to resolve the exception specification of a defaulted default
13025   // constructor before the initializer is lexically complete will ultimately
13026   // come here at which point we can diagnose it.
13027   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13028   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13029       << OutermostClass << Field;
13030   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13031   // Recover by marking the field invalid, unless we're in a SFINAE context.
13032   if (!isSFINAEContext())
13033     Field->setInvalidDecl();
13034   return ExprError();
13035 }
13036 
13037 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13038   if (VD->isInvalidDecl()) return;
13039 
13040   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13041   if (ClassDecl->isInvalidDecl()) return;
13042   if (ClassDecl->hasIrrelevantDestructor()) return;
13043   if (ClassDecl->isDependentContext()) return;
13044 
13045   if (VD->isNoDestroy(getASTContext()))
13046     return;
13047 
13048   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13049   MarkFunctionReferenced(VD->getLocation(), Destructor);
13050   CheckDestructorAccess(VD->getLocation(), Destructor,
13051                         PDiag(diag::err_access_dtor_var)
13052                         << VD->getDeclName()
13053                         << VD->getType());
13054   DiagnoseUseOfDecl(Destructor, VD->getLocation());
13055 
13056   if (Destructor->isTrivial()) return;
13057   if (!VD->hasGlobalStorage()) return;
13058 
13059   // Emit warning for non-trivial dtor in global scope (a real global,
13060   // class-static, function-static).
13061   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13062 
13063   // TODO: this should be re-enabled for static locals by !CXAAtExit
13064   if (!VD->isStaticLocal())
13065     Diag(VD->getLocation(), diag::warn_global_destructor);
13066 }
13067 
13068 /// Given a constructor and the set of arguments provided for the
13069 /// constructor, convert the arguments and add any required default arguments
13070 /// to form a proper call to this constructor.
13071 ///
13072 /// \returns true if an error occurred, false otherwise.
13073 bool
13074 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13075                               MultiExprArg ArgsPtr,
13076                               SourceLocation Loc,
13077                               SmallVectorImpl<Expr*> &ConvertedArgs,
13078                               bool AllowExplicit,
13079                               bool IsListInitialization) {
13080   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13081   unsigned NumArgs = ArgsPtr.size();
13082   Expr **Args = ArgsPtr.data();
13083 
13084   const FunctionProtoType *Proto
13085     = Constructor->getType()->getAs<FunctionProtoType>();
13086   assert(Proto && "Constructor without a prototype?");
13087   unsigned NumParams = Proto->getNumParams();
13088 
13089   // If too few arguments are available, we'll fill in the rest with defaults.
13090   if (NumArgs < NumParams)
13091     ConvertedArgs.reserve(NumParams);
13092   else
13093     ConvertedArgs.reserve(NumArgs);
13094 
13095   VariadicCallType CallType =
13096     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13097   SmallVector<Expr *, 8> AllArgs;
13098   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13099                                         Proto, 0,
13100                                         llvm::makeArrayRef(Args, NumArgs),
13101                                         AllArgs,
13102                                         CallType, AllowExplicit,
13103                                         IsListInitialization);
13104   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13105 
13106   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13107 
13108   CheckConstructorCall(Constructor,
13109                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13110                        Proto, Loc);
13111 
13112   return Invalid;
13113 }
13114 
13115 static inline bool
13116 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13117                                        const FunctionDecl *FnDecl) {
13118   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13119   if (isa<NamespaceDecl>(DC)) {
13120     return SemaRef.Diag(FnDecl->getLocation(),
13121                         diag::err_operator_new_delete_declared_in_namespace)
13122       << FnDecl->getDeclName();
13123   }
13124 
13125   if (isa<TranslationUnitDecl>(DC) &&
13126       FnDecl->getStorageClass() == SC_Static) {
13127     return SemaRef.Diag(FnDecl->getLocation(),
13128                         diag::err_operator_new_delete_declared_static)
13129       << FnDecl->getDeclName();
13130   }
13131 
13132   return false;
13133 }
13134 
13135 static QualType
13136 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13137   QualType QTy = PtrTy->getPointeeType();
13138   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13139   return SemaRef.Context.getPointerType(QTy);
13140 }
13141 
13142 static inline bool
13143 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13144                             CanQualType ExpectedResultType,
13145                             CanQualType ExpectedFirstParamType,
13146                             unsigned DependentParamTypeDiag,
13147                             unsigned InvalidParamTypeDiag) {
13148   QualType ResultType =
13149       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13150 
13151   // Check that the result type is not dependent.
13152   if (ResultType->isDependentType())
13153     return SemaRef.Diag(FnDecl->getLocation(),
13154                         diag::err_operator_new_delete_dependent_result_type)
13155     << FnDecl->getDeclName() << ExpectedResultType;
13156 
13157   // OpenCL C++: the operator is valid on any address space.
13158   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13159     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13160       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13161     }
13162   }
13163 
13164   // Check that the result type is what we expect.
13165   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13166     return SemaRef.Diag(FnDecl->getLocation(),
13167                         diag::err_operator_new_delete_invalid_result_type)
13168     << FnDecl->getDeclName() << ExpectedResultType;
13169 
13170   // A function template must have at least 2 parameters.
13171   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13172     return SemaRef.Diag(FnDecl->getLocation(),
13173                       diag::err_operator_new_delete_template_too_few_parameters)
13174         << FnDecl->getDeclName();
13175 
13176   // The function decl must have at least 1 parameter.
13177   if (FnDecl->getNumParams() == 0)
13178     return SemaRef.Diag(FnDecl->getLocation(),
13179                         diag::err_operator_new_delete_too_few_parameters)
13180       << FnDecl->getDeclName();
13181 
13182   // Check the first parameter type is not dependent.
13183   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13184   if (FirstParamType->isDependentType())
13185     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13186       << FnDecl->getDeclName() << ExpectedFirstParamType;
13187 
13188   // Check that the first parameter type is what we expect.
13189   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13190     // OpenCL C++: the operator is valid on any address space.
13191     if (auto *PtrTy =
13192             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13193       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13194     }
13195   }
13196   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13197       ExpectedFirstParamType)
13198     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13199     << FnDecl->getDeclName() << ExpectedFirstParamType;
13200 
13201   return false;
13202 }
13203 
13204 static bool
13205 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13206   // C++ [basic.stc.dynamic.allocation]p1:
13207   //   A program is ill-formed if an allocation function is declared in a
13208   //   namespace scope other than global scope or declared static in global
13209   //   scope.
13210   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13211     return true;
13212 
13213   CanQualType SizeTy =
13214     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13215 
13216   // C++ [basic.stc.dynamic.allocation]p1:
13217   //  The return type shall be void*. The first parameter shall have type
13218   //  std::size_t.
13219   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13220                                   SizeTy,
13221                                   diag::err_operator_new_dependent_param_type,
13222                                   diag::err_operator_new_param_type))
13223     return true;
13224 
13225   // C++ [basic.stc.dynamic.allocation]p1:
13226   //  The first parameter shall not have an associated default argument.
13227   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13228     return SemaRef.Diag(FnDecl->getLocation(),
13229                         diag::err_operator_new_default_arg)
13230       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13231 
13232   return false;
13233 }
13234 
13235 static bool
13236 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13237   // C++ [basic.stc.dynamic.deallocation]p1:
13238   //   A program is ill-formed if deallocation functions are declared in a
13239   //   namespace scope other than global scope or declared static in global
13240   //   scope.
13241   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13242     return true;
13243 
13244   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13245 
13246   // C++ P0722:
13247   //   Within a class C, the first parameter of a destroying operator delete
13248   //   shall be of type C *. The first parameter of any other deallocation
13249   //   function shall be of type void *.
13250   CanQualType ExpectedFirstParamType =
13251       MD && MD->isDestroyingOperatorDelete()
13252           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13253                 SemaRef.Context.getRecordType(MD->getParent())))
13254           : SemaRef.Context.VoidPtrTy;
13255 
13256   // C++ [basic.stc.dynamic.deallocation]p2:
13257   //   Each deallocation function shall return void
13258   if (CheckOperatorNewDeleteTypes(
13259           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13260           diag::err_operator_delete_dependent_param_type,
13261           diag::err_operator_delete_param_type))
13262     return true;
13263 
13264   // C++ P0722:
13265   //   A destroying operator delete shall be a usual deallocation function.
13266   if (MD && !MD->getParent()->isDependentContext() &&
13267       MD->isDestroyingOperatorDelete() &&
13268       !SemaRef.isUsualDeallocationFunction(MD)) {
13269     SemaRef.Diag(MD->getLocation(),
13270                  diag::err_destroying_operator_delete_not_usual);
13271     return true;
13272   }
13273 
13274   return false;
13275 }
13276 
13277 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13278 /// of this overloaded operator is well-formed. If so, returns false;
13279 /// otherwise, emits appropriate diagnostics and returns true.
13280 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13281   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13282          "Expected an overloaded operator declaration");
13283 
13284   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13285 
13286   // C++ [over.oper]p5:
13287   //   The allocation and deallocation functions, operator new,
13288   //   operator new[], operator delete and operator delete[], are
13289   //   described completely in 3.7.3. The attributes and restrictions
13290   //   found in the rest of this subclause do not apply to them unless
13291   //   explicitly stated in 3.7.3.
13292   if (Op == OO_Delete || Op == OO_Array_Delete)
13293     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13294 
13295   if (Op == OO_New || Op == OO_Array_New)
13296     return CheckOperatorNewDeclaration(*this, FnDecl);
13297 
13298   // C++ [over.oper]p6:
13299   //   An operator function shall either be a non-static member
13300   //   function or be a non-member function and have at least one
13301   //   parameter whose type is a class, a reference to a class, an
13302   //   enumeration, or a reference to an enumeration.
13303   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13304     if (MethodDecl->isStatic())
13305       return Diag(FnDecl->getLocation(),
13306                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13307   } else {
13308     bool ClassOrEnumParam = false;
13309     for (auto Param : FnDecl->parameters()) {
13310       QualType ParamType = Param->getType().getNonReferenceType();
13311       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13312           ParamType->isEnumeralType()) {
13313         ClassOrEnumParam = true;
13314         break;
13315       }
13316     }
13317 
13318     if (!ClassOrEnumParam)
13319       return Diag(FnDecl->getLocation(),
13320                   diag::err_operator_overload_needs_class_or_enum)
13321         << FnDecl->getDeclName();
13322   }
13323 
13324   // C++ [over.oper]p8:
13325   //   An operator function cannot have default arguments (8.3.6),
13326   //   except where explicitly stated below.
13327   //
13328   // Only the function-call operator allows default arguments
13329   // (C++ [over.call]p1).
13330   if (Op != OO_Call) {
13331     for (auto Param : FnDecl->parameters()) {
13332       if (Param->hasDefaultArg())
13333         return Diag(Param->getLocation(),
13334                     diag::err_operator_overload_default_arg)
13335           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13336     }
13337   }
13338 
13339   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13340     { false, false, false }
13341 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13342     , { Unary, Binary, MemberOnly }
13343 #include "clang/Basic/OperatorKinds.def"
13344   };
13345 
13346   bool CanBeUnaryOperator = OperatorUses[Op][0];
13347   bool CanBeBinaryOperator = OperatorUses[Op][1];
13348   bool MustBeMemberOperator = OperatorUses[Op][2];
13349 
13350   // C++ [over.oper]p8:
13351   //   [...] Operator functions cannot have more or fewer parameters
13352   //   than the number required for the corresponding operator, as
13353   //   described in the rest of this subclause.
13354   unsigned NumParams = FnDecl->getNumParams()
13355                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13356   if (Op != OO_Call &&
13357       ((NumParams == 1 && !CanBeUnaryOperator) ||
13358        (NumParams == 2 && !CanBeBinaryOperator) ||
13359        (NumParams < 1) || (NumParams > 2))) {
13360     // We have the wrong number of parameters.
13361     unsigned ErrorKind;
13362     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13363       ErrorKind = 2;  // 2 -> unary or binary.
13364     } else if (CanBeUnaryOperator) {
13365       ErrorKind = 0;  // 0 -> unary
13366     } else {
13367       assert(CanBeBinaryOperator &&
13368              "All non-call overloaded operators are unary or binary!");
13369       ErrorKind = 1;  // 1 -> binary
13370     }
13371 
13372     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13373       << FnDecl->getDeclName() << NumParams << ErrorKind;
13374   }
13375 
13376   // Overloaded operators other than operator() cannot be variadic.
13377   if (Op != OO_Call &&
13378       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13379     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13380       << FnDecl->getDeclName();
13381   }
13382 
13383   // Some operators must be non-static member functions.
13384   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13385     return Diag(FnDecl->getLocation(),
13386                 diag::err_operator_overload_must_be_member)
13387       << FnDecl->getDeclName();
13388   }
13389 
13390   // C++ [over.inc]p1:
13391   //   The user-defined function called operator++ implements the
13392   //   prefix and postfix ++ operator. If this function is a member
13393   //   function with no parameters, or a non-member function with one
13394   //   parameter of class or enumeration type, it defines the prefix
13395   //   increment operator ++ for objects of that type. If the function
13396   //   is a member function with one parameter (which shall be of type
13397   //   int) or a non-member function with two parameters (the second
13398   //   of which shall be of type int), it defines the postfix
13399   //   increment operator ++ for objects of that type.
13400   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13401     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13402     QualType ParamType = LastParam->getType();
13403 
13404     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13405         !ParamType->isDependentType())
13406       return Diag(LastParam->getLocation(),
13407                   diag::err_operator_overload_post_incdec_must_be_int)
13408         << LastParam->getType() << (Op == OO_MinusMinus);
13409   }
13410 
13411   return false;
13412 }
13413 
13414 static bool
13415 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13416                                           FunctionTemplateDecl *TpDecl) {
13417   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13418 
13419   // Must have one or two template parameters.
13420   if (TemplateParams->size() == 1) {
13421     NonTypeTemplateParmDecl *PmDecl =
13422         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13423 
13424     // The template parameter must be a char parameter pack.
13425     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13426         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13427       return false;
13428 
13429   } else if (TemplateParams->size() == 2) {
13430     TemplateTypeParmDecl *PmType =
13431         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13432     NonTypeTemplateParmDecl *PmArgs =
13433         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13434 
13435     // The second template parameter must be a parameter pack with the
13436     // first template parameter as its type.
13437     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13438         PmArgs->isTemplateParameterPack()) {
13439       const TemplateTypeParmType *TArgs =
13440           PmArgs->getType()->getAs<TemplateTypeParmType>();
13441       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13442           TArgs->getIndex() == PmType->getIndex()) {
13443         if (!SemaRef.inTemplateInstantiation())
13444           SemaRef.Diag(TpDecl->getLocation(),
13445                        diag::ext_string_literal_operator_template);
13446         return false;
13447       }
13448     }
13449   }
13450 
13451   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13452                diag::err_literal_operator_template)
13453       << TpDecl->getTemplateParameters()->getSourceRange();
13454   return true;
13455 }
13456 
13457 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13458 /// of this literal operator function is well-formed. If so, returns
13459 /// false; otherwise, emits appropriate diagnostics and returns true.
13460 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13461   if (isa<CXXMethodDecl>(FnDecl)) {
13462     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13463       << FnDecl->getDeclName();
13464     return true;
13465   }
13466 
13467   if (FnDecl->isExternC()) {
13468     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13469     if (const LinkageSpecDecl *LSD =
13470             FnDecl->getDeclContext()->getExternCContext())
13471       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13472     return true;
13473   }
13474 
13475   // This might be the definition of a literal operator template.
13476   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13477 
13478   // This might be a specialization of a literal operator template.
13479   if (!TpDecl)
13480     TpDecl = FnDecl->getPrimaryTemplate();
13481 
13482   // template <char...> type operator "" name() and
13483   // template <class T, T...> type operator "" name() are the only valid
13484   // template signatures, and the only valid signatures with no parameters.
13485   if (TpDecl) {
13486     if (FnDecl->param_size() != 0) {
13487       Diag(FnDecl->getLocation(),
13488            diag::err_literal_operator_template_with_params);
13489       return true;
13490     }
13491 
13492     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13493       return true;
13494 
13495   } else if (FnDecl->param_size() == 1) {
13496     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13497 
13498     QualType ParamType = Param->getType().getUnqualifiedType();
13499 
13500     // Only unsigned long long int, long double, any character type, and const
13501     // char * are allowed as the only parameters.
13502     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13503         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13504         Context.hasSameType(ParamType, Context.CharTy) ||
13505         Context.hasSameType(ParamType, Context.WideCharTy) ||
13506         Context.hasSameType(ParamType, Context.Char8Ty) ||
13507         Context.hasSameType(ParamType, Context.Char16Ty) ||
13508         Context.hasSameType(ParamType, Context.Char32Ty)) {
13509     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13510       QualType InnerType = Ptr->getPointeeType();
13511 
13512       // Pointer parameter must be a const char *.
13513       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13514                                 Context.CharTy) &&
13515             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13516         Diag(Param->getSourceRange().getBegin(),
13517              diag::err_literal_operator_param)
13518             << ParamType << "'const char *'" << Param->getSourceRange();
13519         return true;
13520       }
13521 
13522     } else if (ParamType->isRealFloatingType()) {
13523       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13524           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13525       return true;
13526 
13527     } else if (ParamType->isIntegerType()) {
13528       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13529           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13530       return true;
13531 
13532     } else {
13533       Diag(Param->getSourceRange().getBegin(),
13534            diag::err_literal_operator_invalid_param)
13535           << ParamType << Param->getSourceRange();
13536       return true;
13537     }
13538 
13539   } else if (FnDecl->param_size() == 2) {
13540     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13541 
13542     // First, verify that the first parameter is correct.
13543 
13544     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13545 
13546     // Two parameter function must have a pointer to const as a
13547     // first parameter; let's strip those qualifiers.
13548     const PointerType *PT = FirstParamType->getAs<PointerType>();
13549 
13550     if (!PT) {
13551       Diag((*Param)->getSourceRange().getBegin(),
13552            diag::err_literal_operator_param)
13553           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13554       return true;
13555     }
13556 
13557     QualType PointeeType = PT->getPointeeType();
13558     // First parameter must be const
13559     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13560       Diag((*Param)->getSourceRange().getBegin(),
13561            diag::err_literal_operator_param)
13562           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13563       return true;
13564     }
13565 
13566     QualType InnerType = PointeeType.getUnqualifiedType();
13567     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13568     // const char32_t* are allowed as the first parameter to a two-parameter
13569     // function
13570     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13571           Context.hasSameType(InnerType, Context.WideCharTy) ||
13572           Context.hasSameType(InnerType, Context.Char8Ty) ||
13573           Context.hasSameType(InnerType, Context.Char16Ty) ||
13574           Context.hasSameType(InnerType, Context.Char32Ty))) {
13575       Diag((*Param)->getSourceRange().getBegin(),
13576            diag::err_literal_operator_param)
13577           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13578       return true;
13579     }
13580 
13581     // Move on to the second and final parameter.
13582     ++Param;
13583 
13584     // The second parameter must be a std::size_t.
13585     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13586     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13587       Diag((*Param)->getSourceRange().getBegin(),
13588            diag::err_literal_operator_param)
13589           << SecondParamType << Context.getSizeType()
13590           << (*Param)->getSourceRange();
13591       return true;
13592     }
13593   } else {
13594     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13595     return true;
13596   }
13597 
13598   // Parameters are good.
13599 
13600   // A parameter-declaration-clause containing a default argument is not
13601   // equivalent to any of the permitted forms.
13602   for (auto Param : FnDecl->parameters()) {
13603     if (Param->hasDefaultArg()) {
13604       Diag(Param->getDefaultArgRange().getBegin(),
13605            diag::err_literal_operator_default_argument)
13606         << Param->getDefaultArgRange();
13607       break;
13608     }
13609   }
13610 
13611   StringRef LiteralName
13612     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13613   if (LiteralName[0] != '_' &&
13614       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13615     // C++11 [usrlit.suffix]p1:
13616     //   Literal suffix identifiers that do not start with an underscore
13617     //   are reserved for future standardization.
13618     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13619       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13620   }
13621 
13622   return false;
13623 }
13624 
13625 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13626 /// linkage specification, including the language and (if present)
13627 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13628 /// language string literal. LBraceLoc, if valid, provides the location of
13629 /// the '{' brace. Otherwise, this linkage specification does not
13630 /// have any braces.
13631 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13632                                            Expr *LangStr,
13633                                            SourceLocation LBraceLoc) {
13634   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13635   if (!Lit->isAscii()) {
13636     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13637       << LangStr->getSourceRange();
13638     return nullptr;
13639   }
13640 
13641   StringRef Lang = Lit->getString();
13642   LinkageSpecDecl::LanguageIDs Language;
13643   if (Lang == "C")
13644     Language = LinkageSpecDecl::lang_c;
13645   else if (Lang == "C++")
13646     Language = LinkageSpecDecl::lang_cxx;
13647   else {
13648     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13649       << LangStr->getSourceRange();
13650     return nullptr;
13651   }
13652 
13653   // FIXME: Add all the various semantics of linkage specifications
13654 
13655   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13656                                                LangStr->getExprLoc(), Language,
13657                                                LBraceLoc.isValid());
13658   CurContext->addDecl(D);
13659   PushDeclContext(S, D);
13660   return D;
13661 }
13662 
13663 /// ActOnFinishLinkageSpecification - Complete the definition of
13664 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13665 /// valid, it's the position of the closing '}' brace in a linkage
13666 /// specification that uses braces.
13667 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13668                                             Decl *LinkageSpec,
13669                                             SourceLocation RBraceLoc) {
13670   if (RBraceLoc.isValid()) {
13671     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13672     LSDecl->setRBraceLoc(RBraceLoc);
13673   }
13674   PopDeclContext();
13675   return LinkageSpec;
13676 }
13677 
13678 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13679                                   const ParsedAttributesView &AttrList,
13680                                   SourceLocation SemiLoc) {
13681   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13682   // Attribute declarations appertain to empty declaration so we handle
13683   // them here.
13684   ProcessDeclAttributeList(S, ED, AttrList);
13685 
13686   CurContext->addDecl(ED);
13687   return ED;
13688 }
13689 
13690 /// Perform semantic analysis for the variable declaration that
13691 /// occurs within a C++ catch clause, returning the newly-created
13692 /// variable.
13693 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13694                                          TypeSourceInfo *TInfo,
13695                                          SourceLocation StartLoc,
13696                                          SourceLocation Loc,
13697                                          IdentifierInfo *Name) {
13698   bool Invalid = false;
13699   QualType ExDeclType = TInfo->getType();
13700 
13701   // Arrays and functions decay.
13702   if (ExDeclType->isArrayType())
13703     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13704   else if (ExDeclType->isFunctionType())
13705     ExDeclType = Context.getPointerType(ExDeclType);
13706 
13707   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13708   // The exception-declaration shall not denote a pointer or reference to an
13709   // incomplete type, other than [cv] void*.
13710   // N2844 forbids rvalue references.
13711   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13712     Diag(Loc, diag::err_catch_rvalue_ref);
13713     Invalid = true;
13714   }
13715 
13716   if (ExDeclType->isVariablyModifiedType()) {
13717     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13718     Invalid = true;
13719   }
13720 
13721   QualType BaseType = ExDeclType;
13722   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13723   unsigned DK = diag::err_catch_incomplete;
13724   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13725     BaseType = Ptr->getPointeeType();
13726     Mode = 1;
13727     DK = diag::err_catch_incomplete_ptr;
13728   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13729     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13730     BaseType = Ref->getPointeeType();
13731     Mode = 2;
13732     DK = diag::err_catch_incomplete_ref;
13733   }
13734   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13735       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13736     Invalid = true;
13737 
13738   if (!Invalid && !ExDeclType->isDependentType() &&
13739       RequireNonAbstractType(Loc, ExDeclType,
13740                              diag::err_abstract_type_in_decl,
13741                              AbstractVariableType))
13742     Invalid = true;
13743 
13744   // Only the non-fragile NeXT runtime currently supports C++ catches
13745   // of ObjC types, and no runtime supports catching ObjC types by value.
13746   if (!Invalid && getLangOpts().ObjC) {
13747     QualType T = ExDeclType;
13748     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13749       T = RT->getPointeeType();
13750 
13751     if (T->isObjCObjectType()) {
13752       Diag(Loc, diag::err_objc_object_catch);
13753       Invalid = true;
13754     } else if (T->isObjCObjectPointerType()) {
13755       // FIXME: should this be a test for macosx-fragile specifically?
13756       if (getLangOpts().ObjCRuntime.isFragile())
13757         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13758     }
13759   }
13760 
13761   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13762                                     ExDeclType, TInfo, SC_None);
13763   ExDecl->setExceptionVariable(true);
13764 
13765   // In ARC, infer 'retaining' for variables of retainable type.
13766   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13767     Invalid = true;
13768 
13769   if (!Invalid && !ExDeclType->isDependentType()) {
13770     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13771       // Insulate this from anything else we might currently be parsing.
13772       EnterExpressionEvaluationContext scope(
13773           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13774 
13775       // C++ [except.handle]p16:
13776       //   The object declared in an exception-declaration or, if the
13777       //   exception-declaration does not specify a name, a temporary (12.2) is
13778       //   copy-initialized (8.5) from the exception object. [...]
13779       //   The object is destroyed when the handler exits, after the destruction
13780       //   of any automatic objects initialized within the handler.
13781       //
13782       // We just pretend to initialize the object with itself, then make sure
13783       // it can be destroyed later.
13784       QualType initType = Context.getExceptionObjectType(ExDeclType);
13785 
13786       InitializedEntity entity =
13787         InitializedEntity::InitializeVariable(ExDecl);
13788       InitializationKind initKind =
13789         InitializationKind::CreateCopy(Loc, SourceLocation());
13790 
13791       Expr *opaqueValue =
13792         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13793       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13794       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13795       if (result.isInvalid())
13796         Invalid = true;
13797       else {
13798         // If the constructor used was non-trivial, set this as the
13799         // "initializer".
13800         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13801         if (!construct->getConstructor()->isTrivial()) {
13802           Expr *init = MaybeCreateExprWithCleanups(construct);
13803           ExDecl->setInit(init);
13804         }
13805 
13806         // And make sure it's destructable.
13807         FinalizeVarWithDestructor(ExDecl, recordType);
13808       }
13809     }
13810   }
13811 
13812   if (Invalid)
13813     ExDecl->setInvalidDecl();
13814 
13815   return ExDecl;
13816 }
13817 
13818 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13819 /// handler.
13820 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13821   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13822   bool Invalid = D.isInvalidType();
13823 
13824   // Check for unexpanded parameter packs.
13825   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13826                                       UPPC_ExceptionType)) {
13827     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13828                                              D.getIdentifierLoc());
13829     Invalid = true;
13830   }
13831 
13832   IdentifierInfo *II = D.getIdentifier();
13833   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13834                                              LookupOrdinaryName,
13835                                              ForVisibleRedeclaration)) {
13836     // The scope should be freshly made just for us. There is just no way
13837     // it contains any previous declaration, except for function parameters in
13838     // a function-try-block's catch statement.
13839     assert(!S->isDeclScope(PrevDecl));
13840     if (isDeclInScope(PrevDecl, CurContext, S)) {
13841       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13842         << D.getIdentifier();
13843       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13844       Invalid = true;
13845     } else if (PrevDecl->isTemplateParameter())
13846       // Maybe we will complain about the shadowed template parameter.
13847       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13848   }
13849 
13850   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13851     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13852       << D.getCXXScopeSpec().getRange();
13853     Invalid = true;
13854   }
13855 
13856   VarDecl *ExDecl = BuildExceptionDeclaration(
13857       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13858   if (Invalid)
13859     ExDecl->setInvalidDecl();
13860 
13861   // Add the exception declaration into this scope.
13862   if (II)
13863     PushOnScopeChains(ExDecl, S);
13864   else
13865     CurContext->addDecl(ExDecl);
13866 
13867   ProcessDeclAttributes(S, ExDecl, D);
13868   return ExDecl;
13869 }
13870 
13871 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13872                                          Expr *AssertExpr,
13873                                          Expr *AssertMessageExpr,
13874                                          SourceLocation RParenLoc) {
13875   StringLiteral *AssertMessage =
13876       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13877 
13878   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13879     return nullptr;
13880 
13881   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13882                                       AssertMessage, RParenLoc, false);
13883 }
13884 
13885 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13886                                          Expr *AssertExpr,
13887                                          StringLiteral *AssertMessage,
13888                                          SourceLocation RParenLoc,
13889                                          bool Failed) {
13890   assert(AssertExpr != nullptr && "Expected non-null condition");
13891   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13892       !Failed) {
13893     // In a static_assert-declaration, the constant-expression shall be a
13894     // constant expression that can be contextually converted to bool.
13895     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13896     if (Converted.isInvalid())
13897       Failed = true;
13898     else
13899       Converted = ConstantExpr::Create(Context, Converted.get());
13900 
13901     llvm::APSInt Cond;
13902     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13903           diag::err_static_assert_expression_is_not_constant,
13904           /*AllowFold=*/false).isInvalid())
13905       Failed = true;
13906 
13907     if (!Failed && !Cond) {
13908       SmallString<256> MsgBuffer;
13909       llvm::raw_svector_ostream Msg(MsgBuffer);
13910       if (AssertMessage)
13911         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13912 
13913       Expr *InnerCond = nullptr;
13914       std::string InnerCondDescription;
13915       std::tie(InnerCond, InnerCondDescription) =
13916         findFailedBooleanCondition(Converted.get());
13917       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13918                     && !isa<IntegerLiteral>(InnerCond)) {
13919         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13920           << InnerCondDescription << !AssertMessage
13921           << Msg.str() << InnerCond->getSourceRange();
13922       } else {
13923         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13924           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13925       }
13926       Failed = true;
13927     }
13928   }
13929 
13930   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13931                                                   /*DiscardedValue*/false,
13932                                                   /*IsConstexpr*/true);
13933   if (FullAssertExpr.isInvalid())
13934     Failed = true;
13935   else
13936     AssertExpr = FullAssertExpr.get();
13937 
13938   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13939                                         AssertExpr, AssertMessage, RParenLoc,
13940                                         Failed);
13941 
13942   CurContext->addDecl(Decl);
13943   return Decl;
13944 }
13945 
13946 /// Perform semantic analysis of the given friend type declaration.
13947 ///
13948 /// \returns A friend declaration that.
13949 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13950                                       SourceLocation FriendLoc,
13951                                       TypeSourceInfo *TSInfo) {
13952   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13953 
13954   QualType T = TSInfo->getType();
13955   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13956 
13957   // C++03 [class.friend]p2:
13958   //   An elaborated-type-specifier shall be used in a friend declaration
13959   //   for a class.*
13960   //
13961   //   * The class-key of the elaborated-type-specifier is required.
13962   if (!CodeSynthesisContexts.empty()) {
13963     // Do not complain about the form of friend template types during any kind
13964     // of code synthesis. For template instantiation, we will have complained
13965     // when the template was defined.
13966   } else {
13967     if (!T->isElaboratedTypeSpecifier()) {
13968       // If we evaluated the type to a record type, suggest putting
13969       // a tag in front.
13970       if (const RecordType *RT = T->getAs<RecordType>()) {
13971         RecordDecl *RD = RT->getDecl();
13972 
13973         SmallString<16> InsertionText(" ");
13974         InsertionText += RD->getKindName();
13975 
13976         Diag(TypeRange.getBegin(),
13977              getLangOpts().CPlusPlus11 ?
13978                diag::warn_cxx98_compat_unelaborated_friend_type :
13979                diag::ext_unelaborated_friend_type)
13980           << (unsigned) RD->getTagKind()
13981           << T
13982           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13983                                         InsertionText);
13984       } else {
13985         Diag(FriendLoc,
13986              getLangOpts().CPlusPlus11 ?
13987                diag::warn_cxx98_compat_nonclass_type_friend :
13988                diag::ext_nonclass_type_friend)
13989           << T
13990           << TypeRange;
13991       }
13992     } else if (T->getAs<EnumType>()) {
13993       Diag(FriendLoc,
13994            getLangOpts().CPlusPlus11 ?
13995              diag::warn_cxx98_compat_enum_friend :
13996              diag::ext_enum_friend)
13997         << T
13998         << TypeRange;
13999     }
14000 
14001     // C++11 [class.friend]p3:
14002     //   A friend declaration that does not declare a function shall have one
14003     //   of the following forms:
14004     //     friend elaborated-type-specifier ;
14005     //     friend simple-type-specifier ;
14006     //     friend typename-specifier ;
14007     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14008       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14009   }
14010 
14011   //   If the type specifier in a friend declaration designates a (possibly
14012   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14013   //   the friend declaration is ignored.
14014   return FriendDecl::Create(Context, CurContext,
14015                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14016                             FriendLoc);
14017 }
14018 
14019 /// Handle a friend tag declaration where the scope specifier was
14020 /// templated.
14021 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14022                                     unsigned TagSpec, SourceLocation TagLoc,
14023                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14024                                     SourceLocation NameLoc,
14025                                     const ParsedAttributesView &Attr,
14026                                     MultiTemplateParamsArg TempParamLists) {
14027   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14028 
14029   bool IsMemberSpecialization = false;
14030   bool Invalid = false;
14031 
14032   if (TemplateParameterList *TemplateParams =
14033           MatchTemplateParametersToScopeSpecifier(
14034               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14035               IsMemberSpecialization, Invalid)) {
14036     if (TemplateParams->size() > 0) {
14037       // This is a declaration of a class template.
14038       if (Invalid)
14039         return nullptr;
14040 
14041       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14042                                 NameLoc, Attr, TemplateParams, AS_public,
14043                                 /*ModulePrivateLoc=*/SourceLocation(),
14044                                 FriendLoc, TempParamLists.size() - 1,
14045                                 TempParamLists.data()).get();
14046     } else {
14047       // The "template<>" header is extraneous.
14048       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14049         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14050       IsMemberSpecialization = true;
14051     }
14052   }
14053 
14054   if (Invalid) return nullptr;
14055 
14056   bool isAllExplicitSpecializations = true;
14057   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14058     if (TempParamLists[I]->size()) {
14059       isAllExplicitSpecializations = false;
14060       break;
14061     }
14062   }
14063 
14064   // FIXME: don't ignore attributes.
14065 
14066   // If it's explicit specializations all the way down, just forget
14067   // about the template header and build an appropriate non-templated
14068   // friend.  TODO: for source fidelity, remember the headers.
14069   if (isAllExplicitSpecializations) {
14070     if (SS.isEmpty()) {
14071       bool Owned = false;
14072       bool IsDependent = false;
14073       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14074                       Attr, AS_public,
14075                       /*ModulePrivateLoc=*/SourceLocation(),
14076                       MultiTemplateParamsArg(), Owned, IsDependent,
14077                       /*ScopedEnumKWLoc=*/SourceLocation(),
14078                       /*ScopedEnumUsesClassTag=*/false,
14079                       /*UnderlyingType=*/TypeResult(),
14080                       /*IsTypeSpecifier=*/false,
14081                       /*IsTemplateParamOrArg=*/false);
14082     }
14083 
14084     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14085     ElaboratedTypeKeyword Keyword
14086       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14087     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14088                                    *Name, NameLoc);
14089     if (T.isNull())
14090       return nullptr;
14091 
14092     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14093     if (isa<DependentNameType>(T)) {
14094       DependentNameTypeLoc TL =
14095           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14096       TL.setElaboratedKeywordLoc(TagLoc);
14097       TL.setQualifierLoc(QualifierLoc);
14098       TL.setNameLoc(NameLoc);
14099     } else {
14100       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14101       TL.setElaboratedKeywordLoc(TagLoc);
14102       TL.setQualifierLoc(QualifierLoc);
14103       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14104     }
14105 
14106     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14107                                             TSI, FriendLoc, TempParamLists);
14108     Friend->setAccess(AS_public);
14109     CurContext->addDecl(Friend);
14110     return Friend;
14111   }
14112 
14113   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14114 
14115 
14116 
14117   // Handle the case of a templated-scope friend class.  e.g.
14118   //   template <class T> class A<T>::B;
14119   // FIXME: we don't support these right now.
14120   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14121     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14122   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14123   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14124   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14125   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14126   TL.setElaboratedKeywordLoc(TagLoc);
14127   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14128   TL.setNameLoc(NameLoc);
14129 
14130   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14131                                           TSI, FriendLoc, TempParamLists);
14132   Friend->setAccess(AS_public);
14133   Friend->setUnsupportedFriend(true);
14134   CurContext->addDecl(Friend);
14135   return Friend;
14136 }
14137 
14138 /// Handle a friend type declaration.  This works in tandem with
14139 /// ActOnTag.
14140 ///
14141 /// Notes on friend class templates:
14142 ///
14143 /// We generally treat friend class declarations as if they were
14144 /// declaring a class.  So, for example, the elaborated type specifier
14145 /// in a friend declaration is required to obey the restrictions of a
14146 /// class-head (i.e. no typedefs in the scope chain), template
14147 /// parameters are required to match up with simple template-ids, &c.
14148 /// However, unlike when declaring a template specialization, it's
14149 /// okay to refer to a template specialization without an empty
14150 /// template parameter declaration, e.g.
14151 ///   friend class A<T>::B<unsigned>;
14152 /// We permit this as a special case; if there are any template
14153 /// parameters present at all, require proper matching, i.e.
14154 ///   template <> template \<class T> friend class A<int>::B;
14155 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14156                                 MultiTemplateParamsArg TempParams) {
14157   SourceLocation Loc = DS.getBeginLoc();
14158 
14159   assert(DS.isFriendSpecified());
14160   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14161 
14162   // C++ [class.friend]p3:
14163   // A friend declaration that does not declare a function shall have one of
14164   // the following forms:
14165   //     friend elaborated-type-specifier ;
14166   //     friend simple-type-specifier ;
14167   //     friend typename-specifier ;
14168   //
14169   // Any declaration with a type qualifier does not have that form. (It's
14170   // legal to specify a qualified type as a friend, you just can't write the
14171   // keywords.)
14172   if (DS.getTypeQualifiers()) {
14173     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14174       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14175     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14176       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14177     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14178       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14179     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14180       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14181     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14182       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14183   }
14184 
14185   // Try to convert the decl specifier to a type.  This works for
14186   // friend templates because ActOnTag never produces a ClassTemplateDecl
14187   // for a TUK_Friend.
14188   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14189   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14190   QualType T = TSI->getType();
14191   if (TheDeclarator.isInvalidType())
14192     return nullptr;
14193 
14194   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14195     return nullptr;
14196 
14197   // This is definitely an error in C++98.  It's probably meant to
14198   // be forbidden in C++0x, too, but the specification is just
14199   // poorly written.
14200   //
14201   // The problem is with declarations like the following:
14202   //   template <T> friend A<T>::foo;
14203   // where deciding whether a class C is a friend or not now hinges
14204   // on whether there exists an instantiation of A that causes
14205   // 'foo' to equal C.  There are restrictions on class-heads
14206   // (which we declare (by fiat) elaborated friend declarations to
14207   // be) that makes this tractable.
14208   //
14209   // FIXME: handle "template <> friend class A<T>;", which
14210   // is possibly well-formed?  Who even knows?
14211   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14212     Diag(Loc, diag::err_tagless_friend_type_template)
14213       << DS.getSourceRange();
14214     return nullptr;
14215   }
14216 
14217   // C++98 [class.friend]p1: A friend of a class is a function
14218   //   or class that is not a member of the class . . .
14219   // This is fixed in DR77, which just barely didn't make the C++03
14220   // deadline.  It's also a very silly restriction that seriously
14221   // affects inner classes and which nobody else seems to implement;
14222   // thus we never diagnose it, not even in -pedantic.
14223   //
14224   // But note that we could warn about it: it's always useless to
14225   // friend one of your own members (it's not, however, worthless to
14226   // friend a member of an arbitrary specialization of your template).
14227 
14228   Decl *D;
14229   if (!TempParams.empty())
14230     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14231                                    TempParams,
14232                                    TSI,
14233                                    DS.getFriendSpecLoc());
14234   else
14235     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14236 
14237   if (!D)
14238     return nullptr;
14239 
14240   D->setAccess(AS_public);
14241   CurContext->addDecl(D);
14242 
14243   return D;
14244 }
14245 
14246 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14247                                         MultiTemplateParamsArg TemplateParams) {
14248   const DeclSpec &DS = D.getDeclSpec();
14249 
14250   assert(DS.isFriendSpecified());
14251   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14252 
14253   SourceLocation Loc = D.getIdentifierLoc();
14254   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14255 
14256   // C++ [class.friend]p1
14257   //   A friend of a class is a function or class....
14258   // Note that this sees through typedefs, which is intended.
14259   // It *doesn't* see through dependent types, which is correct
14260   // according to [temp.arg.type]p3:
14261   //   If a declaration acquires a function type through a
14262   //   type dependent on a template-parameter and this causes
14263   //   a declaration that does not use the syntactic form of a
14264   //   function declarator to have a function type, the program
14265   //   is ill-formed.
14266   if (!TInfo->getType()->isFunctionType()) {
14267     Diag(Loc, diag::err_unexpected_friend);
14268 
14269     // It might be worthwhile to try to recover by creating an
14270     // appropriate declaration.
14271     return nullptr;
14272   }
14273 
14274   // C++ [namespace.memdef]p3
14275   //  - If a friend declaration in a non-local class first declares a
14276   //    class or function, the friend class or function is a member
14277   //    of the innermost enclosing namespace.
14278   //  - The name of the friend is not found by simple name lookup
14279   //    until a matching declaration is provided in that namespace
14280   //    scope (either before or after the class declaration granting
14281   //    friendship).
14282   //  - If a friend function is called, its name may be found by the
14283   //    name lookup that considers functions from namespaces and
14284   //    classes associated with the types of the function arguments.
14285   //  - When looking for a prior declaration of a class or a function
14286   //    declared as a friend, scopes outside the innermost enclosing
14287   //    namespace scope are not considered.
14288 
14289   CXXScopeSpec &SS = D.getCXXScopeSpec();
14290   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14291   DeclarationName Name = NameInfo.getName();
14292   assert(Name);
14293 
14294   // Check for unexpanded parameter packs.
14295   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14296       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14297       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14298     return nullptr;
14299 
14300   // The context we found the declaration in, or in which we should
14301   // create the declaration.
14302   DeclContext *DC;
14303   Scope *DCScope = S;
14304   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14305                         ForExternalRedeclaration);
14306 
14307   // There are five cases here.
14308   //   - There's no scope specifier and we're in a local class. Only look
14309   //     for functions declared in the immediately-enclosing block scope.
14310   // We recover from invalid scope qualifiers as if they just weren't there.
14311   FunctionDecl *FunctionContainingLocalClass = nullptr;
14312   if ((SS.isInvalid() || !SS.isSet()) &&
14313       (FunctionContainingLocalClass =
14314            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14315     // C++11 [class.friend]p11:
14316     //   If a friend declaration appears in a local class and the name
14317     //   specified is an unqualified name, a prior declaration is
14318     //   looked up without considering scopes that are outside the
14319     //   innermost enclosing non-class scope. For a friend function
14320     //   declaration, if there is no prior declaration, the program is
14321     //   ill-formed.
14322 
14323     // Find the innermost enclosing non-class scope. This is the block
14324     // scope containing the local class definition (or for a nested class,
14325     // the outer local class).
14326     DCScope = S->getFnParent();
14327 
14328     // Look up the function name in the scope.
14329     Previous.clear(LookupLocalFriendName);
14330     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14331 
14332     if (!Previous.empty()) {
14333       // All possible previous declarations must have the same context:
14334       // either they were declared at block scope or they are members of
14335       // one of the enclosing local classes.
14336       DC = Previous.getRepresentativeDecl()->getDeclContext();
14337     } else {
14338       // This is ill-formed, but provide the context that we would have
14339       // declared the function in, if we were permitted to, for error recovery.
14340       DC = FunctionContainingLocalClass;
14341     }
14342     adjustContextForLocalExternDecl(DC);
14343 
14344     // C++ [class.friend]p6:
14345     //   A function can be defined in a friend declaration of a class if and
14346     //   only if the class is a non-local class (9.8), the function name is
14347     //   unqualified, and the function has namespace scope.
14348     if (D.isFunctionDefinition()) {
14349       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14350     }
14351 
14352   //   - There's no scope specifier, in which case we just go to the
14353   //     appropriate scope and look for a function or function template
14354   //     there as appropriate.
14355   } else if (SS.isInvalid() || !SS.isSet()) {
14356     // C++11 [namespace.memdef]p3:
14357     //   If the name in a friend declaration is neither qualified nor
14358     //   a template-id and the declaration is a function or an
14359     //   elaborated-type-specifier, the lookup to determine whether
14360     //   the entity has been previously declared shall not consider
14361     //   any scopes outside the innermost enclosing namespace.
14362     bool isTemplateId =
14363         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14364 
14365     // Find the appropriate context according to the above.
14366     DC = CurContext;
14367 
14368     // Skip class contexts.  If someone can cite chapter and verse
14369     // for this behavior, that would be nice --- it's what GCC and
14370     // EDG do, and it seems like a reasonable intent, but the spec
14371     // really only says that checks for unqualified existing
14372     // declarations should stop at the nearest enclosing namespace,
14373     // not that they should only consider the nearest enclosing
14374     // namespace.
14375     while (DC->isRecord())
14376       DC = DC->getParent();
14377 
14378     DeclContext *LookupDC = DC;
14379     while (LookupDC->isTransparentContext())
14380       LookupDC = LookupDC->getParent();
14381 
14382     while (true) {
14383       LookupQualifiedName(Previous, LookupDC);
14384 
14385       if (!Previous.empty()) {
14386         DC = LookupDC;
14387         break;
14388       }
14389 
14390       if (isTemplateId) {
14391         if (isa<TranslationUnitDecl>(LookupDC)) break;
14392       } else {
14393         if (LookupDC->isFileContext()) break;
14394       }
14395       LookupDC = LookupDC->getParent();
14396     }
14397 
14398     DCScope = getScopeForDeclContext(S, DC);
14399 
14400   //   - There's a non-dependent scope specifier, in which case we
14401   //     compute it and do a previous lookup there for a function
14402   //     or function template.
14403   } else if (!SS.getScopeRep()->isDependent()) {
14404     DC = computeDeclContext(SS);
14405     if (!DC) return nullptr;
14406 
14407     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14408 
14409     LookupQualifiedName(Previous, DC);
14410 
14411     // Ignore things found implicitly in the wrong scope.
14412     // TODO: better diagnostics for this case.  Suggesting the right
14413     // qualified scope would be nice...
14414     LookupResult::Filter F = Previous.makeFilter();
14415     while (F.hasNext()) {
14416       NamedDecl *D = F.next();
14417       if (!DC->InEnclosingNamespaceSetOf(
14418               D->getDeclContext()->getRedeclContext()))
14419         F.erase();
14420     }
14421     F.done();
14422 
14423     if (Previous.empty()) {
14424       D.setInvalidType();
14425       Diag(Loc, diag::err_qualified_friend_not_found)
14426           << Name << TInfo->getType();
14427       return nullptr;
14428     }
14429 
14430     // C++ [class.friend]p1: A friend of a class is a function or
14431     //   class that is not a member of the class . . .
14432     if (DC->Equals(CurContext))
14433       Diag(DS.getFriendSpecLoc(),
14434            getLangOpts().CPlusPlus11 ?
14435              diag::warn_cxx98_compat_friend_is_member :
14436              diag::err_friend_is_member);
14437 
14438     if (D.isFunctionDefinition()) {
14439       // C++ [class.friend]p6:
14440       //   A function can be defined in a friend declaration of a class if and
14441       //   only if the class is a non-local class (9.8), the function name is
14442       //   unqualified, and the function has namespace scope.
14443       SemaDiagnosticBuilder DB
14444         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14445 
14446       DB << SS.getScopeRep();
14447       if (DC->isFileContext())
14448         DB << FixItHint::CreateRemoval(SS.getRange());
14449       SS.clear();
14450     }
14451 
14452   //   - There's a scope specifier that does not match any template
14453   //     parameter lists, in which case we use some arbitrary context,
14454   //     create a method or method template, and wait for instantiation.
14455   //   - There's a scope specifier that does match some template
14456   //     parameter lists, which we don't handle right now.
14457   } else {
14458     if (D.isFunctionDefinition()) {
14459       // C++ [class.friend]p6:
14460       //   A function can be defined in a friend declaration of a class if and
14461       //   only if the class is a non-local class (9.8), the function name is
14462       //   unqualified, and the function has namespace scope.
14463       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14464         << SS.getScopeRep();
14465     }
14466 
14467     DC = CurContext;
14468     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14469   }
14470 
14471   if (!DC->isRecord()) {
14472     int DiagArg = -1;
14473     switch (D.getName().getKind()) {
14474     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14475     case UnqualifiedIdKind::IK_ConstructorName:
14476       DiagArg = 0;
14477       break;
14478     case UnqualifiedIdKind::IK_DestructorName:
14479       DiagArg = 1;
14480       break;
14481     case UnqualifiedIdKind::IK_ConversionFunctionId:
14482       DiagArg = 2;
14483       break;
14484     case UnqualifiedIdKind::IK_DeductionGuideName:
14485       DiagArg = 3;
14486       break;
14487     case UnqualifiedIdKind::IK_Identifier:
14488     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14489     case UnqualifiedIdKind::IK_LiteralOperatorId:
14490     case UnqualifiedIdKind::IK_OperatorFunctionId:
14491     case UnqualifiedIdKind::IK_TemplateId:
14492       break;
14493     }
14494     // This implies that it has to be an operator or function.
14495     if (DiagArg >= 0) {
14496       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14497       return nullptr;
14498     }
14499   }
14500 
14501   // FIXME: This is an egregious hack to cope with cases where the scope stack
14502   // does not contain the declaration context, i.e., in an out-of-line
14503   // definition of a class.
14504   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14505   if (!DCScope) {
14506     FakeDCScope.setEntity(DC);
14507     DCScope = &FakeDCScope;
14508   }
14509 
14510   bool AddToScope = true;
14511   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14512                                           TemplateParams, AddToScope);
14513   if (!ND) return nullptr;
14514 
14515   assert(ND->getLexicalDeclContext() == CurContext);
14516 
14517   // If we performed typo correction, we might have added a scope specifier
14518   // and changed the decl context.
14519   DC = ND->getDeclContext();
14520 
14521   // Add the function declaration to the appropriate lookup tables,
14522   // adjusting the redeclarations list as necessary.  We don't
14523   // want to do this yet if the friending class is dependent.
14524   //
14525   // Also update the scope-based lookup if the target context's
14526   // lookup context is in lexical scope.
14527   if (!CurContext->isDependentContext()) {
14528     DC = DC->getRedeclContext();
14529     DC->makeDeclVisibleInContext(ND);
14530     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14531       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14532   }
14533 
14534   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14535                                        D.getIdentifierLoc(), ND,
14536                                        DS.getFriendSpecLoc());
14537   FrD->setAccess(AS_public);
14538   CurContext->addDecl(FrD);
14539 
14540   if (ND->isInvalidDecl()) {
14541     FrD->setInvalidDecl();
14542   } else {
14543     if (DC->isRecord()) CheckFriendAccess(ND);
14544 
14545     FunctionDecl *FD;
14546     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14547       FD = FTD->getTemplatedDecl();
14548     else
14549       FD = cast<FunctionDecl>(ND);
14550 
14551     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14552     // default argument expression, that declaration shall be a definition
14553     // and shall be the only declaration of the function or function
14554     // template in the translation unit.
14555     if (functionDeclHasDefaultArgument(FD)) {
14556       // We can't look at FD->getPreviousDecl() because it may not have been set
14557       // if we're in a dependent context. If the function is known to be a
14558       // redeclaration, we will have narrowed Previous down to the right decl.
14559       if (D.isRedeclaration()) {
14560         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14561         Diag(Previous.getRepresentativeDecl()->getLocation(),
14562              diag::note_previous_declaration);
14563       } else if (!D.isFunctionDefinition())
14564         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14565     }
14566 
14567     // Mark templated-scope function declarations as unsupported.
14568     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14569       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14570         << SS.getScopeRep() << SS.getRange()
14571         << cast<CXXRecordDecl>(CurContext);
14572       FrD->setUnsupportedFriend(true);
14573     }
14574   }
14575 
14576   return ND;
14577 }
14578 
14579 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14580   AdjustDeclIfTemplate(Dcl);
14581 
14582   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14583   if (!Fn) {
14584     Diag(DelLoc, diag::err_deleted_non_function);
14585     return;
14586   }
14587 
14588   // Deleted function does not have a body.
14589   Fn->setWillHaveBody(false);
14590 
14591   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14592     // Don't consider the implicit declaration we generate for explicit
14593     // specializations. FIXME: Do not generate these implicit declarations.
14594     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14595          Prev->getPreviousDecl()) &&
14596         !Prev->isDefined()) {
14597       Diag(DelLoc, diag::err_deleted_decl_not_first);
14598       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14599            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14600                               : diag::note_previous_declaration);
14601     }
14602     // If the declaration wasn't the first, we delete the function anyway for
14603     // recovery.
14604     Fn = Fn->getCanonicalDecl();
14605   }
14606 
14607   // dllimport/dllexport cannot be deleted.
14608   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14609     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14610     Fn->setInvalidDecl();
14611   }
14612 
14613   if (Fn->isDeleted())
14614     return;
14615 
14616   // See if we're deleting a function which is already known to override a
14617   // non-deleted virtual function.
14618   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14619     bool IssuedDiagnostic = false;
14620     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14621       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14622         if (!IssuedDiagnostic) {
14623           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14624           IssuedDiagnostic = true;
14625         }
14626         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14627       }
14628     }
14629     // If this function was implicitly deleted because it was defaulted,
14630     // explain why it was deleted.
14631     if (IssuedDiagnostic && MD->isDefaulted())
14632       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14633                                 /*Diagnose*/true);
14634   }
14635 
14636   // C++11 [basic.start.main]p3:
14637   //   A program that defines main as deleted [...] is ill-formed.
14638   if (Fn->isMain())
14639     Diag(DelLoc, diag::err_deleted_main);
14640 
14641   // C++11 [dcl.fct.def.delete]p4:
14642   //  A deleted function is implicitly inline.
14643   Fn->setImplicitlyInline();
14644   Fn->setDeletedAsWritten();
14645 }
14646 
14647 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14648   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14649 
14650   if (MD) {
14651     if (MD->getParent()->isDependentType()) {
14652       MD->setDefaulted();
14653       MD->setExplicitlyDefaulted();
14654       return;
14655     }
14656 
14657     CXXSpecialMember Member = getSpecialMember(MD);
14658     if (Member == CXXInvalid) {
14659       if (!MD->isInvalidDecl())
14660         Diag(DefaultLoc, diag::err_default_special_members);
14661       return;
14662     }
14663 
14664     MD->setDefaulted();
14665     MD->setExplicitlyDefaulted();
14666 
14667     // Unset that we will have a body for this function. We might not,
14668     // if it turns out to be trivial, and we don't need this marking now
14669     // that we've marked it as defaulted.
14670     MD->setWillHaveBody(false);
14671 
14672     // If this definition appears within the record, do the checking when
14673     // the record is complete.
14674     const FunctionDecl *Primary = MD;
14675     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14676       // Ask the template instantiation pattern that actually had the
14677       // '= default' on it.
14678       Primary = Pattern;
14679 
14680     // If the method was defaulted on its first declaration, we will have
14681     // already performed the checking in CheckCompletedCXXClass. Such a
14682     // declaration doesn't trigger an implicit definition.
14683     if (Primary->getCanonicalDecl()->isDefaulted())
14684       return;
14685 
14686     CheckExplicitlyDefaultedSpecialMember(MD);
14687 
14688     if (!MD->isInvalidDecl())
14689       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14690   } else {
14691     Diag(DefaultLoc, diag::err_default_special_members);
14692   }
14693 }
14694 
14695 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14696   for (Stmt *SubStmt : S->children()) {
14697     if (!SubStmt)
14698       continue;
14699     if (isa<ReturnStmt>(SubStmt))
14700       Self.Diag(SubStmt->getBeginLoc(),
14701                 diag::err_return_in_constructor_handler);
14702     if (!isa<Expr>(SubStmt))
14703       SearchForReturnInStmt(Self, SubStmt);
14704   }
14705 }
14706 
14707 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14708   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14709     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14710     SearchForReturnInStmt(*this, Handler);
14711   }
14712 }
14713 
14714 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14715                                              const CXXMethodDecl *Old) {
14716   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14717   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14718 
14719   if (OldFT->hasExtParameterInfos()) {
14720     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14721       // A parameter of the overriding method should be annotated with noescape
14722       // if the corresponding parameter of the overridden method is annotated.
14723       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14724           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14725         Diag(New->getParamDecl(I)->getLocation(),
14726              diag::warn_overriding_method_missing_noescape);
14727         Diag(Old->getParamDecl(I)->getLocation(),
14728              diag::note_overridden_marked_noescape);
14729       }
14730   }
14731 
14732   // Virtual overrides must have the same code_seg.
14733   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14734   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14735   if ((NewCSA || OldCSA) &&
14736       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14737     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14738     Diag(Old->getLocation(), diag::note_previous_declaration);
14739     return true;
14740   }
14741 
14742   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14743 
14744   // If the calling conventions match, everything is fine
14745   if (NewCC == OldCC)
14746     return false;
14747 
14748   // If the calling conventions mismatch because the new function is static,
14749   // suppress the calling convention mismatch error; the error about static
14750   // function override (err_static_overrides_virtual from
14751   // Sema::CheckFunctionDeclaration) is more clear.
14752   if (New->getStorageClass() == SC_Static)
14753     return false;
14754 
14755   Diag(New->getLocation(),
14756        diag::err_conflicting_overriding_cc_attributes)
14757     << New->getDeclName() << New->getType() << Old->getType();
14758   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14759   return true;
14760 }
14761 
14762 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14763                                              const CXXMethodDecl *Old) {
14764   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14765   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14766 
14767   if (Context.hasSameType(NewTy, OldTy) ||
14768       NewTy->isDependentType() || OldTy->isDependentType())
14769     return false;
14770 
14771   // Check if the return types are covariant
14772   QualType NewClassTy, OldClassTy;
14773 
14774   /// Both types must be pointers or references to classes.
14775   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14776     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14777       NewClassTy = NewPT->getPointeeType();
14778       OldClassTy = OldPT->getPointeeType();
14779     }
14780   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14781     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14782       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14783         NewClassTy = NewRT->getPointeeType();
14784         OldClassTy = OldRT->getPointeeType();
14785       }
14786     }
14787   }
14788 
14789   // The return types aren't either both pointers or references to a class type.
14790   if (NewClassTy.isNull()) {
14791     Diag(New->getLocation(),
14792          diag::err_different_return_type_for_overriding_virtual_function)
14793         << New->getDeclName() << NewTy << OldTy
14794         << New->getReturnTypeSourceRange();
14795     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14796         << Old->getReturnTypeSourceRange();
14797 
14798     return true;
14799   }
14800 
14801   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14802     // C++14 [class.virtual]p8:
14803     //   If the class type in the covariant return type of D::f differs from
14804     //   that of B::f, the class type in the return type of D::f shall be
14805     //   complete at the point of declaration of D::f or shall be the class
14806     //   type D.
14807     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14808       if (!RT->isBeingDefined() &&
14809           RequireCompleteType(New->getLocation(), NewClassTy,
14810                               diag::err_covariant_return_incomplete,
14811                               New->getDeclName()))
14812         return true;
14813     }
14814 
14815     // Check if the new class derives from the old class.
14816     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14817       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14818           << New->getDeclName() << NewTy << OldTy
14819           << New->getReturnTypeSourceRange();
14820       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14821           << Old->getReturnTypeSourceRange();
14822       return true;
14823     }
14824 
14825     // Check if we the conversion from derived to base is valid.
14826     if (CheckDerivedToBaseConversion(
14827             NewClassTy, OldClassTy,
14828             diag::err_covariant_return_inaccessible_base,
14829             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14830             New->getLocation(), New->getReturnTypeSourceRange(),
14831             New->getDeclName(), nullptr)) {
14832       // FIXME: this note won't trigger for delayed access control
14833       // diagnostics, and it's impossible to get an undelayed error
14834       // here from access control during the original parse because
14835       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14836       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14837           << Old->getReturnTypeSourceRange();
14838       return true;
14839     }
14840   }
14841 
14842   // The qualifiers of the return types must be the same.
14843   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14844     Diag(New->getLocation(),
14845          diag::err_covariant_return_type_different_qualifications)
14846         << New->getDeclName() << NewTy << OldTy
14847         << New->getReturnTypeSourceRange();
14848     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14849         << Old->getReturnTypeSourceRange();
14850     return true;
14851   }
14852 
14853 
14854   // The new class type must have the same or less qualifiers as the old type.
14855   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14856     Diag(New->getLocation(),
14857          diag::err_covariant_return_type_class_type_more_qualified)
14858         << New->getDeclName() << NewTy << OldTy
14859         << New->getReturnTypeSourceRange();
14860     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14861         << Old->getReturnTypeSourceRange();
14862     return true;
14863   }
14864 
14865   return false;
14866 }
14867 
14868 /// Mark the given method pure.
14869 ///
14870 /// \param Method the method to be marked pure.
14871 ///
14872 /// \param InitRange the source range that covers the "0" initializer.
14873 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14874   SourceLocation EndLoc = InitRange.getEnd();
14875   if (EndLoc.isValid())
14876     Method->setRangeEnd(EndLoc);
14877 
14878   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14879     Method->setPure();
14880     return false;
14881   }
14882 
14883   if (!Method->isInvalidDecl())
14884     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14885       << Method->getDeclName() << InitRange;
14886   return true;
14887 }
14888 
14889 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14890   if (D->getFriendObjectKind())
14891     Diag(D->getLocation(), diag::err_pure_friend);
14892   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14893     CheckPureMethod(M, ZeroLoc);
14894   else
14895     Diag(D->getLocation(), diag::err_illegal_initializer);
14896 }
14897 
14898 /// Determine whether the given declaration is a global variable or
14899 /// static data member.
14900 static bool isNonlocalVariable(const Decl *D) {
14901   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14902     return Var->hasGlobalStorage();
14903 
14904   return false;
14905 }
14906 
14907 /// Invoked when we are about to parse an initializer for the declaration
14908 /// 'Dcl'.
14909 ///
14910 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14911 /// static data member of class X, names should be looked up in the scope of
14912 /// class X. If the declaration had a scope specifier, a scope will have
14913 /// been created and passed in for this purpose. Otherwise, S will be null.
14914 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14915   // If there is no declaration, there was an error parsing it.
14916   if (!D || D->isInvalidDecl())
14917     return;
14918 
14919   // We will always have a nested name specifier here, but this declaration
14920   // might not be out of line if the specifier names the current namespace:
14921   //   extern int n;
14922   //   int ::n = 0;
14923   if (S && D->isOutOfLine())
14924     EnterDeclaratorContext(S, D->getDeclContext());
14925 
14926   // If we are parsing the initializer for a static data member, push a
14927   // new expression evaluation context that is associated with this static
14928   // data member.
14929   if (isNonlocalVariable(D))
14930     PushExpressionEvaluationContext(
14931         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14932 }
14933 
14934 /// Invoked after we are finished parsing an initializer for the declaration D.
14935 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14936   // If there is no declaration, there was an error parsing it.
14937   if (!D || D->isInvalidDecl())
14938     return;
14939 
14940   if (isNonlocalVariable(D))
14941     PopExpressionEvaluationContext();
14942 
14943   if (S && D->isOutOfLine())
14944     ExitDeclaratorContext(S);
14945 }
14946 
14947 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14948 /// C++ if/switch/while/for statement.
14949 /// e.g: "if (int x = f()) {...}"
14950 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14951   // C++ 6.4p2:
14952   // The declarator shall not specify a function or an array.
14953   // The type-specifier-seq shall not contain typedef and shall not declare a
14954   // new class or enumeration.
14955   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14956          "Parser allowed 'typedef' as storage class of condition decl.");
14957 
14958   Decl *Dcl = ActOnDeclarator(S, D);
14959   if (!Dcl)
14960     return true;
14961 
14962   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14963     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14964       << D.getSourceRange();
14965     return true;
14966   }
14967 
14968   return Dcl;
14969 }
14970 
14971 void Sema::LoadExternalVTableUses() {
14972   if (!ExternalSource)
14973     return;
14974 
14975   SmallVector<ExternalVTableUse, 4> VTables;
14976   ExternalSource->ReadUsedVTables(VTables);
14977   SmallVector<VTableUse, 4> NewUses;
14978   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14979     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14980       = VTablesUsed.find(VTables[I].Record);
14981     // Even if a definition wasn't required before, it may be required now.
14982     if (Pos != VTablesUsed.end()) {
14983       if (!Pos->second && VTables[I].DefinitionRequired)
14984         Pos->second = true;
14985       continue;
14986     }
14987 
14988     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14989     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14990   }
14991 
14992   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14993 }
14994 
14995 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14996                           bool DefinitionRequired) {
14997   // Ignore any vtable uses in unevaluated operands or for classes that do
14998   // not have a vtable.
14999   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15000       CurContext->isDependentContext() || isUnevaluatedContext())
15001     return;
15002   // Do not mark as used if compiling for the device outside of the target
15003   // region.
15004   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15005       !isInOpenMPDeclareTargetContext() &&
15006       !isInOpenMPTargetExecutionDirective()) {
15007     if (!DefinitionRequired)
15008       MarkVirtualMembersReferenced(Loc, Class);
15009     return;
15010   }
15011 
15012   // Try to insert this class into the map.
15013   LoadExternalVTableUses();
15014   Class = Class->getCanonicalDecl();
15015   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15016     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15017   if (!Pos.second) {
15018     // If we already had an entry, check to see if we are promoting this vtable
15019     // to require a definition. If so, we need to reappend to the VTableUses
15020     // list, since we may have already processed the first entry.
15021     if (DefinitionRequired && !Pos.first->second) {
15022       Pos.first->second = true;
15023     } else {
15024       // Otherwise, we can early exit.
15025       return;
15026     }
15027   } else {
15028     // The Microsoft ABI requires that we perform the destructor body
15029     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15030     // the deleting destructor is emitted with the vtable, not with the
15031     // destructor definition as in the Itanium ABI.
15032     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15033       CXXDestructorDecl *DD = Class->getDestructor();
15034       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15035         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15036           // If this is an out-of-line declaration, marking it referenced will
15037           // not do anything. Manually call CheckDestructor to look up operator
15038           // delete().
15039           ContextRAII SavedContext(*this, DD);
15040           CheckDestructor(DD);
15041         } else {
15042           MarkFunctionReferenced(Loc, Class->getDestructor());
15043         }
15044       }
15045     }
15046   }
15047 
15048   // Local classes need to have their virtual members marked
15049   // immediately. For all other classes, we mark their virtual members
15050   // at the end of the translation unit.
15051   if (Class->isLocalClass())
15052     MarkVirtualMembersReferenced(Loc, Class);
15053   else
15054     VTableUses.push_back(std::make_pair(Class, Loc));
15055 }
15056 
15057 bool Sema::DefineUsedVTables() {
15058   LoadExternalVTableUses();
15059   if (VTableUses.empty())
15060     return false;
15061 
15062   // Note: The VTableUses vector could grow as a result of marking
15063   // the members of a class as "used", so we check the size each
15064   // time through the loop and prefer indices (which are stable) to
15065   // iterators (which are not).
15066   bool DefinedAnything = false;
15067   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15068     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15069     if (!Class)
15070       continue;
15071     TemplateSpecializationKind ClassTSK =
15072         Class->getTemplateSpecializationKind();
15073 
15074     SourceLocation Loc = VTableUses[I].second;
15075 
15076     bool DefineVTable = true;
15077 
15078     // If this class has a key function, but that key function is
15079     // defined in another translation unit, we don't need to emit the
15080     // vtable even though we're using it.
15081     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15082     if (KeyFunction && !KeyFunction->hasBody()) {
15083       // The key function is in another translation unit.
15084       DefineVTable = false;
15085       TemplateSpecializationKind TSK =
15086           KeyFunction->getTemplateSpecializationKind();
15087       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15088              TSK != TSK_ImplicitInstantiation &&
15089              "Instantiations don't have key functions");
15090       (void)TSK;
15091     } else if (!KeyFunction) {
15092       // If we have a class with no key function that is the subject
15093       // of an explicit instantiation declaration, suppress the
15094       // vtable; it will live with the explicit instantiation
15095       // definition.
15096       bool IsExplicitInstantiationDeclaration =
15097           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15098       for (auto R : Class->redecls()) {
15099         TemplateSpecializationKind TSK
15100           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15101         if (TSK == TSK_ExplicitInstantiationDeclaration)
15102           IsExplicitInstantiationDeclaration = true;
15103         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15104           IsExplicitInstantiationDeclaration = false;
15105           break;
15106         }
15107       }
15108 
15109       if (IsExplicitInstantiationDeclaration)
15110         DefineVTable = false;
15111     }
15112 
15113     // The exception specifications for all virtual members may be needed even
15114     // if we are not providing an authoritative form of the vtable in this TU.
15115     // We may choose to emit it available_externally anyway.
15116     if (!DefineVTable) {
15117       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15118       continue;
15119     }
15120 
15121     // Mark all of the virtual members of this class as referenced, so
15122     // that we can build a vtable. Then, tell the AST consumer that a
15123     // vtable for this class is required.
15124     DefinedAnything = true;
15125     MarkVirtualMembersReferenced(Loc, Class);
15126     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15127     if (VTablesUsed[Canonical])
15128       Consumer.HandleVTable(Class);
15129 
15130     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15131     // no key function or the key function is inlined. Don't warn in C++ ABIs
15132     // that lack key functions, since the user won't be able to make one.
15133     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15134         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15135       const FunctionDecl *KeyFunctionDef = nullptr;
15136       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15137                            KeyFunctionDef->isInlined())) {
15138         Diag(Class->getLocation(),
15139              ClassTSK == TSK_ExplicitInstantiationDefinition
15140                  ? diag::warn_weak_template_vtable
15141                  : diag::warn_weak_vtable)
15142             << Class;
15143       }
15144     }
15145   }
15146   VTableUses.clear();
15147 
15148   return DefinedAnything;
15149 }
15150 
15151 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15152                                                  const CXXRecordDecl *RD) {
15153   for (const auto *I : RD->methods())
15154     if (I->isVirtual() && !I->isPure())
15155       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15156 }
15157 
15158 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15159                                         const CXXRecordDecl *RD) {
15160   // Mark all functions which will appear in RD's vtable as used.
15161   CXXFinalOverriderMap FinalOverriders;
15162   RD->getFinalOverriders(FinalOverriders);
15163   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15164                                             E = FinalOverriders.end();
15165        I != E; ++I) {
15166     for (OverridingMethods::const_iterator OI = I->second.begin(),
15167                                            OE = I->second.end();
15168          OI != OE; ++OI) {
15169       assert(OI->second.size() > 0 && "no final overrider");
15170       CXXMethodDecl *Overrider = OI->second.front().Method;
15171 
15172       // C++ [basic.def.odr]p2:
15173       //   [...] A virtual member function is used if it is not pure. [...]
15174       if (!Overrider->isPure())
15175         MarkFunctionReferenced(Loc, Overrider);
15176     }
15177   }
15178 
15179   // Only classes that have virtual bases need a VTT.
15180   if (RD->getNumVBases() == 0)
15181     return;
15182 
15183   for (const auto &I : RD->bases()) {
15184     const CXXRecordDecl *Base =
15185         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15186     if (Base->getNumVBases() == 0)
15187       continue;
15188     MarkVirtualMembersReferenced(Loc, Base);
15189   }
15190 }
15191 
15192 /// SetIvarInitializers - This routine builds initialization ASTs for the
15193 /// Objective-C implementation whose ivars need be initialized.
15194 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15195   if (!getLangOpts().CPlusPlus)
15196     return;
15197   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15198     SmallVector<ObjCIvarDecl*, 8> ivars;
15199     CollectIvarsToConstructOrDestruct(OID, ivars);
15200     if (ivars.empty())
15201       return;
15202     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15203     for (unsigned i = 0; i < ivars.size(); i++) {
15204       FieldDecl *Field = ivars[i];
15205       if (Field->isInvalidDecl())
15206         continue;
15207 
15208       CXXCtorInitializer *Member;
15209       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15210       InitializationKind InitKind =
15211         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15212 
15213       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15214       ExprResult MemberInit =
15215         InitSeq.Perform(*this, InitEntity, InitKind, None);
15216       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15217       // Note, MemberInit could actually come back empty if no initialization
15218       // is required (e.g., because it would call a trivial default constructor)
15219       if (!MemberInit.get() || MemberInit.isInvalid())
15220         continue;
15221 
15222       Member =
15223         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15224                                          SourceLocation(),
15225                                          MemberInit.getAs<Expr>(),
15226                                          SourceLocation());
15227       AllToInit.push_back(Member);
15228 
15229       // Be sure that the destructor is accessible and is marked as referenced.
15230       if (const RecordType *RecordTy =
15231               Context.getBaseElementType(Field->getType())
15232                   ->getAs<RecordType>()) {
15233         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15234         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15235           MarkFunctionReferenced(Field->getLocation(), Destructor);
15236           CheckDestructorAccess(Field->getLocation(), Destructor,
15237                             PDiag(diag::err_access_dtor_ivar)
15238                               << Context.getBaseElementType(Field->getType()));
15239         }
15240       }
15241     }
15242     ObjCImplementation->setIvarInitializers(Context,
15243                                             AllToInit.data(), AllToInit.size());
15244   }
15245 }
15246 
15247 static
15248 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15249                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15250                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15251                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15252                            Sema &S) {
15253   if (Ctor->isInvalidDecl())
15254     return;
15255 
15256   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15257 
15258   // Target may not be determinable yet, for instance if this is a dependent
15259   // call in an uninstantiated template.
15260   if (Target) {
15261     const FunctionDecl *FNTarget = nullptr;
15262     (void)Target->hasBody(FNTarget);
15263     Target = const_cast<CXXConstructorDecl*>(
15264       cast_or_null<CXXConstructorDecl>(FNTarget));
15265   }
15266 
15267   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15268                      // Avoid dereferencing a null pointer here.
15269                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15270 
15271   if (!Current.insert(Canonical).second)
15272     return;
15273 
15274   // We know that beyond here, we aren't chaining into a cycle.
15275   if (!Target || !Target->isDelegatingConstructor() ||
15276       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15277     Valid.insert(Current.begin(), Current.end());
15278     Current.clear();
15279   // We've hit a cycle.
15280   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15281              Current.count(TCanonical)) {
15282     // If we haven't diagnosed this cycle yet, do so now.
15283     if (!Invalid.count(TCanonical)) {
15284       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15285              diag::warn_delegating_ctor_cycle)
15286         << Ctor;
15287 
15288       // Don't add a note for a function delegating directly to itself.
15289       if (TCanonical != Canonical)
15290         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15291 
15292       CXXConstructorDecl *C = Target;
15293       while (C->getCanonicalDecl() != Canonical) {
15294         const FunctionDecl *FNTarget = nullptr;
15295         (void)C->getTargetConstructor()->hasBody(FNTarget);
15296         assert(FNTarget && "Ctor cycle through bodiless function");
15297 
15298         C = const_cast<CXXConstructorDecl*>(
15299           cast<CXXConstructorDecl>(FNTarget));
15300         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15301       }
15302     }
15303 
15304     Invalid.insert(Current.begin(), Current.end());
15305     Current.clear();
15306   } else {
15307     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15308   }
15309 }
15310 
15311 
15312 void Sema::CheckDelegatingCtorCycles() {
15313   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15314 
15315   for (DelegatingCtorDeclsType::iterator
15316          I = DelegatingCtorDecls.begin(ExternalSource),
15317          E = DelegatingCtorDecls.end();
15318        I != E; ++I)
15319     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15320 
15321   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15322     (*CI)->setInvalidDecl();
15323 }
15324 
15325 namespace {
15326   /// AST visitor that finds references to the 'this' expression.
15327   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15328     Sema &S;
15329 
15330   public:
15331     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15332 
15333     bool VisitCXXThisExpr(CXXThisExpr *E) {
15334       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15335         << E->isImplicit();
15336       return false;
15337     }
15338   };
15339 }
15340 
15341 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15342   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15343   if (!TSInfo)
15344     return false;
15345 
15346   TypeLoc TL = TSInfo->getTypeLoc();
15347   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15348   if (!ProtoTL)
15349     return false;
15350 
15351   // C++11 [expr.prim.general]p3:
15352   //   [The expression this] shall not appear before the optional
15353   //   cv-qualifier-seq and it shall not appear within the declaration of a
15354   //   static member function (although its type and value category are defined
15355   //   within a static member function as they are within a non-static member
15356   //   function). [ Note: this is because declaration matching does not occur
15357   //  until the complete declarator is known. - end note ]
15358   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15359   FindCXXThisExpr Finder(*this);
15360 
15361   // If the return type came after the cv-qualifier-seq, check it now.
15362   if (Proto->hasTrailingReturn() &&
15363       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15364     return true;
15365 
15366   // Check the exception specification.
15367   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15368     return true;
15369 
15370   return checkThisInStaticMemberFunctionAttributes(Method);
15371 }
15372 
15373 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15374   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15375   if (!TSInfo)
15376     return false;
15377 
15378   TypeLoc TL = TSInfo->getTypeLoc();
15379   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15380   if (!ProtoTL)
15381     return false;
15382 
15383   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15384   FindCXXThisExpr Finder(*this);
15385 
15386   switch (Proto->getExceptionSpecType()) {
15387   case EST_Unparsed:
15388   case EST_Uninstantiated:
15389   case EST_Unevaluated:
15390   case EST_BasicNoexcept:
15391   case EST_DynamicNone:
15392   case EST_MSAny:
15393   case EST_None:
15394     break;
15395 
15396   case EST_DependentNoexcept:
15397   case EST_NoexceptFalse:
15398   case EST_NoexceptTrue:
15399     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15400       return true;
15401     LLVM_FALLTHROUGH;
15402 
15403   case EST_Dynamic:
15404     for (const auto &E : Proto->exceptions()) {
15405       if (!Finder.TraverseType(E))
15406         return true;
15407     }
15408     break;
15409   }
15410 
15411   return false;
15412 }
15413 
15414 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15415   FindCXXThisExpr Finder(*this);
15416 
15417   // Check attributes.
15418   for (const auto *A : Method->attrs()) {
15419     // FIXME: This should be emitted by tblgen.
15420     Expr *Arg = nullptr;
15421     ArrayRef<Expr *> Args;
15422     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15423       Arg = G->getArg();
15424     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15425       Arg = G->getArg();
15426     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15427       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15428     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15429       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15430     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15431       Arg = ETLF->getSuccessValue();
15432       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15433     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15434       Arg = STLF->getSuccessValue();
15435       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15436     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15437       Arg = LR->getArg();
15438     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15439       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15440     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15441       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15442     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15443       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15444     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15445       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15446     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15447       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15448 
15449     if (Arg && !Finder.TraverseStmt(Arg))
15450       return true;
15451 
15452     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15453       if (!Finder.TraverseStmt(Args[I]))
15454         return true;
15455     }
15456   }
15457 
15458   return false;
15459 }
15460 
15461 void Sema::checkExceptionSpecification(
15462     bool IsTopLevel, ExceptionSpecificationType EST,
15463     ArrayRef<ParsedType> DynamicExceptions,
15464     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15465     SmallVectorImpl<QualType> &Exceptions,
15466     FunctionProtoType::ExceptionSpecInfo &ESI) {
15467   Exceptions.clear();
15468   ESI.Type = EST;
15469   if (EST == EST_Dynamic) {
15470     Exceptions.reserve(DynamicExceptions.size());
15471     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15472       // FIXME: Preserve type source info.
15473       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15474 
15475       if (IsTopLevel) {
15476         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15477         collectUnexpandedParameterPacks(ET, Unexpanded);
15478         if (!Unexpanded.empty()) {
15479           DiagnoseUnexpandedParameterPacks(
15480               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15481               Unexpanded);
15482           continue;
15483         }
15484       }
15485 
15486       // Check that the type is valid for an exception spec, and
15487       // drop it if not.
15488       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15489         Exceptions.push_back(ET);
15490     }
15491     ESI.Exceptions = Exceptions;
15492     return;
15493   }
15494 
15495   if (isComputedNoexcept(EST)) {
15496     assert((NoexceptExpr->isTypeDependent() ||
15497             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15498             Context.BoolTy) &&
15499            "Parser should have made sure that the expression is boolean");
15500     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15501       ESI.Type = EST_BasicNoexcept;
15502       return;
15503     }
15504 
15505     ESI.NoexceptExpr = NoexceptExpr;
15506     return;
15507   }
15508 }
15509 
15510 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15511              ExceptionSpecificationType EST,
15512              SourceRange SpecificationRange,
15513              ArrayRef<ParsedType> DynamicExceptions,
15514              ArrayRef<SourceRange> DynamicExceptionRanges,
15515              Expr *NoexceptExpr) {
15516   if (!MethodD)
15517     return;
15518 
15519   // Dig out the method we're referring to.
15520   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15521     MethodD = FunTmpl->getTemplatedDecl();
15522 
15523   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15524   if (!Method)
15525     return;
15526 
15527   // Check the exception specification.
15528   llvm::SmallVector<QualType, 4> Exceptions;
15529   FunctionProtoType::ExceptionSpecInfo ESI;
15530   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15531                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15532                               ESI);
15533 
15534   // Update the exception specification on the function type.
15535   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15536 
15537   if (Method->isStatic())
15538     checkThisInStaticMemberFunctionExceptionSpec(Method);
15539 
15540   if (Method->isVirtual()) {
15541     // Check overrides, which we previously had to delay.
15542     for (const CXXMethodDecl *O : Method->overridden_methods())
15543       CheckOverridingFunctionExceptionSpec(Method, O);
15544   }
15545 }
15546 
15547 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15548 ///
15549 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15550                                        SourceLocation DeclStart, Declarator &D,
15551                                        Expr *BitWidth,
15552                                        InClassInitStyle InitStyle,
15553                                        AccessSpecifier AS,
15554                                        const ParsedAttr &MSPropertyAttr) {
15555   IdentifierInfo *II = D.getIdentifier();
15556   if (!II) {
15557     Diag(DeclStart, diag::err_anonymous_property);
15558     return nullptr;
15559   }
15560   SourceLocation Loc = D.getIdentifierLoc();
15561 
15562   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15563   QualType T = TInfo->getType();
15564   if (getLangOpts().CPlusPlus) {
15565     CheckExtraCXXDefaultArguments(D);
15566 
15567     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15568                                         UPPC_DataMemberType)) {
15569       D.setInvalidType();
15570       T = Context.IntTy;
15571       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15572     }
15573   }
15574 
15575   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15576 
15577   if (D.getDeclSpec().isInlineSpecified())
15578     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15579         << getLangOpts().CPlusPlus17;
15580   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15581     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15582          diag::err_invalid_thread)
15583       << DeclSpec::getSpecifierName(TSCS);
15584 
15585   // Check to see if this name was declared as a member previously
15586   NamedDecl *PrevDecl = nullptr;
15587   LookupResult Previous(*this, II, Loc, LookupMemberName,
15588                         ForVisibleRedeclaration);
15589   LookupName(Previous, S);
15590   switch (Previous.getResultKind()) {
15591   case LookupResult::Found:
15592   case LookupResult::FoundUnresolvedValue:
15593     PrevDecl = Previous.getAsSingle<NamedDecl>();
15594     break;
15595 
15596   case LookupResult::FoundOverloaded:
15597     PrevDecl = Previous.getRepresentativeDecl();
15598     break;
15599 
15600   case LookupResult::NotFound:
15601   case LookupResult::NotFoundInCurrentInstantiation:
15602   case LookupResult::Ambiguous:
15603     break;
15604   }
15605 
15606   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15607     // Maybe we will complain about the shadowed template parameter.
15608     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15609     // Just pretend that we didn't see the previous declaration.
15610     PrevDecl = nullptr;
15611   }
15612 
15613   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15614     PrevDecl = nullptr;
15615 
15616   SourceLocation TSSL = D.getBeginLoc();
15617   MSPropertyDecl *NewPD =
15618       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15619                              MSPropertyAttr.getPropertyDataGetter(),
15620                              MSPropertyAttr.getPropertyDataSetter());
15621   ProcessDeclAttributes(TUScope, NewPD, D);
15622   NewPD->setAccess(AS);
15623 
15624   if (NewPD->isInvalidDecl())
15625     Record->setInvalidDecl();
15626 
15627   if (D.getDeclSpec().isModulePrivateSpecified())
15628     NewPD->setModulePrivate();
15629 
15630   if (NewPD->isInvalidDecl() && PrevDecl) {
15631     // Don't introduce NewFD into scope; there's already something
15632     // with the same name in the same scope.
15633   } else if (II) {
15634     PushOnScopeChains(NewPD, S);
15635   } else
15636     Record->addDecl(NewPD);
15637 
15638   return NewPD;
15639 }
15640