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 const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1231                                                       SourceLocation Loc,
1232                                                       const CXXRecordDecl *RD,
1233                                                       CXXCastPath &BasePath) {
1234   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1235                           CXXBasePath &Path) {
1236     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1237   };
1238 
1239   const CXXRecordDecl *ClassWithFields = nullptr;
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 RD;
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 nullptr;
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 nullptr;
1277     }
1278 
1279     //   ... public base class of E.
1280     if (BestPath->Access != AS_public) {
1281       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1282         << RD << BaseType;
1283       for (auto &BS : *BestPath) {
1284         if (BS.Base->getAccessSpecifier() != AS_public) {
1285           S.Diag(BS.Base->getBeginLoc(), diag::note_access_constrained_by_path)
1286               << (BS.Base->getAccessSpecifier() == AS_protected)
1287               << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1288           break;
1289         }
1290       }
1291       return nullptr;
1292     }
1293 
1294     ClassWithFields = BaseType->getAsCXXRecordDecl();
1295     S.BuildBasePathArray(Paths, BasePath);
1296   }
1297 
1298   // The above search did not check whether the selected class itself has base
1299   // classes with fields, so check that now.
1300   CXXBasePaths Paths;
1301   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1302     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1303       << (ClassWithFields == RD) << RD << ClassWithFields
1304       << Paths.front().back().Base->getType();
1305     return nullptr;
1306   }
1307 
1308   return ClassWithFields;
1309 }
1310 
1311 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1312                                      ValueDecl *Src, QualType DecompType,
1313                                      const CXXRecordDecl *RD) {
1314   CXXCastPath BasePath;
1315   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1316   if (!RD)
1317     return true;
1318   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1319                                                  DecompType.getQualifiers());
1320 
1321   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1322     unsigned NumFields =
1323         std::count_if(RD->field_begin(), RD->field_end(),
1324                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1325     assert(Bindings.size() != NumFields);
1326     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1327         << DecompType << (unsigned)Bindings.size() << NumFields
1328         << (NumFields < Bindings.size());
1329     return true;
1330   };
1331 
1332   //   all of E's non-static data members shall be public [...] members,
1333   //   E shall not have an anonymous union member, ...
1334   unsigned I = 0;
1335   for (auto *FD : RD->fields()) {
1336     if (FD->isUnnamedBitfield())
1337       continue;
1338 
1339     if (FD->isAnonymousStructOrUnion()) {
1340       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1341         << DecompType << FD->getType()->isUnionType();
1342       S.Diag(FD->getLocation(), diag::note_declared_at);
1343       return true;
1344     }
1345 
1346     // We have a real field to bind.
1347     if (I >= Bindings.size())
1348       return DiagnoseBadNumberOfBindings();
1349     auto *B = Bindings[I++];
1350 
1351     SourceLocation Loc = B->getLocation();
1352     if (FD->getAccess() != AS_public) {
1353       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1354 
1355       // Determine whether the access specifier was explicit.
1356       bool Implicit = true;
1357       for (const auto *D : RD->decls()) {
1358         if (declaresSameEntity(D, FD))
1359           break;
1360         if (isa<AccessSpecDecl>(D)) {
1361           Implicit = false;
1362           break;
1363         }
1364       }
1365 
1366       S.Diag(FD->getLocation(), diag::note_access_natural)
1367         << (FD->getAccess() == AS_protected) << Implicit;
1368       return true;
1369     }
1370 
1371     // Initialize the binding to Src.FD.
1372     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1373     if (E.isInvalid())
1374       return true;
1375     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1376                             VK_LValue, &BasePath);
1377     if (E.isInvalid())
1378       return true;
1379     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1380                                   CXXScopeSpec(), FD,
1381                                   DeclAccessPair::make(FD, FD->getAccess()),
1382                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1383     if (E.isInvalid())
1384       return true;
1385 
1386     // If the type of the member is T, the referenced type is cv T, where cv is
1387     // the cv-qualification of the decomposition expression.
1388     //
1389     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1390     // 'const' to the type of the field.
1391     Qualifiers Q = DecompType.getQualifiers();
1392     if (FD->isMutable())
1393       Q.removeConst();
1394     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1395   }
1396 
1397   if (I != Bindings.size())
1398     return DiagnoseBadNumberOfBindings();
1399 
1400   return false;
1401 }
1402 
1403 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1404   QualType DecompType = DD->getType();
1405 
1406   // If the type of the decomposition is dependent, then so is the type of
1407   // each binding.
1408   if (DecompType->isDependentType()) {
1409     for (auto *B : DD->bindings())
1410       B->setType(Context.DependentTy);
1411     return;
1412   }
1413 
1414   DecompType = DecompType.getNonReferenceType();
1415   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1416 
1417   // C++1z [dcl.decomp]/2:
1418   //   If E is an array type [...]
1419   // As an extension, we also support decomposition of built-in complex and
1420   // vector types.
1421   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1422     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1423       DD->setInvalidDecl();
1424     return;
1425   }
1426   if (auto *VT = DecompType->getAs<VectorType>()) {
1427     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1428       DD->setInvalidDecl();
1429     return;
1430   }
1431   if (auto *CT = DecompType->getAs<ComplexType>()) {
1432     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1433       DD->setInvalidDecl();
1434     return;
1435   }
1436 
1437   // C++1z [dcl.decomp]/3:
1438   //   if the expression std::tuple_size<E>::value is a well-formed integral
1439   //   constant expression, [...]
1440   llvm::APSInt TupleSize(32);
1441   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1442   case IsTupleLike::Error:
1443     DD->setInvalidDecl();
1444     return;
1445 
1446   case IsTupleLike::TupleLike:
1447     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1448       DD->setInvalidDecl();
1449     return;
1450 
1451   case IsTupleLike::NotTupleLike:
1452     break;
1453   }
1454 
1455   // C++1z [dcl.dcl]/8:
1456   //   [E shall be of array or non-union class type]
1457   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1458   if (!RD || RD->isUnion()) {
1459     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1460         << DD << !RD << DecompType;
1461     DD->setInvalidDecl();
1462     return;
1463   }
1464 
1465   // C++1z [dcl.decomp]/4:
1466   //   all of E's non-static data members shall be [...] direct members of
1467   //   E or of the same unambiguous public base class of E, ...
1468   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1469     DD->setInvalidDecl();
1470 }
1471 
1472 /// Merge the exception specifications of two variable declarations.
1473 ///
1474 /// This is called when there's a redeclaration of a VarDecl. The function
1475 /// checks if the redeclaration might have an exception specification and
1476 /// validates compatibility and merges the specs if necessary.
1477 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1478   // Shortcut if exceptions are disabled.
1479   if (!getLangOpts().CXXExceptions)
1480     return;
1481 
1482   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1483          "Should only be called if types are otherwise the same.");
1484 
1485   QualType NewType = New->getType();
1486   QualType OldType = Old->getType();
1487 
1488   // We're only interested in pointers and references to functions, as well
1489   // as pointers to member functions.
1490   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1491     NewType = R->getPointeeType();
1492     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1493   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1494     NewType = P->getPointeeType();
1495     OldType = OldType->getAs<PointerType>()->getPointeeType();
1496   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1497     NewType = M->getPointeeType();
1498     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1499   }
1500 
1501   if (!NewType->isFunctionProtoType())
1502     return;
1503 
1504   // There's lots of special cases for functions. For function pointers, system
1505   // libraries are hopefully not as broken so that we don't need these
1506   // workarounds.
1507   if (CheckEquivalentExceptionSpec(
1508         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1509         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1510     New->setInvalidDecl();
1511   }
1512 }
1513 
1514 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1515 /// function declaration are well-formed according to C++
1516 /// [dcl.fct.default].
1517 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1518   unsigned NumParams = FD->getNumParams();
1519   unsigned p;
1520 
1521   // Find first parameter with a default argument
1522   for (p = 0; p < NumParams; ++p) {
1523     ParmVarDecl *Param = FD->getParamDecl(p);
1524     if (Param->hasDefaultArg())
1525       break;
1526   }
1527 
1528   // C++11 [dcl.fct.default]p4:
1529   //   In a given function declaration, each parameter subsequent to a parameter
1530   //   with a default argument shall have a default argument supplied in this or
1531   //   a previous declaration or shall be a function parameter pack. A default
1532   //   argument shall not be redefined by a later declaration (not even to the
1533   //   same value).
1534   unsigned LastMissingDefaultArg = 0;
1535   for (; p < NumParams; ++p) {
1536     ParmVarDecl *Param = FD->getParamDecl(p);
1537     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1538       if (Param->isInvalidDecl())
1539         /* We already complained about this parameter. */;
1540       else if (Param->getIdentifier())
1541         Diag(Param->getLocation(),
1542              diag::err_param_default_argument_missing_name)
1543           << Param->getIdentifier();
1544       else
1545         Diag(Param->getLocation(),
1546              diag::err_param_default_argument_missing);
1547 
1548       LastMissingDefaultArg = p;
1549     }
1550   }
1551 
1552   if (LastMissingDefaultArg > 0) {
1553     // Some default arguments were missing. Clear out all of the
1554     // default arguments up to (and including) the last missing
1555     // default argument, so that we leave the function parameters
1556     // in a semantically valid state.
1557     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1558       ParmVarDecl *Param = FD->getParamDecl(p);
1559       if (Param->hasDefaultArg()) {
1560         Param->setDefaultArg(nullptr);
1561       }
1562     }
1563   }
1564 }
1565 
1566 // CheckConstexprParameterTypes - Check whether a function's parameter types
1567 // are all literal types. If so, return true. If not, produce a suitable
1568 // diagnostic and return false.
1569 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1570                                          const FunctionDecl *FD) {
1571   unsigned ArgIndex = 0;
1572   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1573   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1574                                               e = FT->param_type_end();
1575        i != e; ++i, ++ArgIndex) {
1576     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1577     SourceLocation ParamLoc = PD->getLocation();
1578     if (!(*i)->isDependentType() &&
1579         SemaRef.RequireLiteralType(ParamLoc, *i,
1580                                    diag::err_constexpr_non_literal_param,
1581                                    ArgIndex+1, PD->getSourceRange(),
1582                                    isa<CXXConstructorDecl>(FD)))
1583       return false;
1584   }
1585   return true;
1586 }
1587 
1588 /// Get diagnostic %select index for tag kind for
1589 /// record diagnostic message.
1590 /// WARNING: Indexes apply to particular diagnostics only!
1591 ///
1592 /// \returns diagnostic %select index.
1593 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1594   switch (Tag) {
1595   case TTK_Struct: return 0;
1596   case TTK_Interface: return 1;
1597   case TTK_Class:  return 2;
1598   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1599   }
1600 }
1601 
1602 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1603 // the requirements of a constexpr function definition or a constexpr
1604 // constructor definition. If so, return true. If not, produce appropriate
1605 // diagnostics and return false.
1606 //
1607 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1608 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1609   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1610   if (MD && MD->isInstance()) {
1611     // C++11 [dcl.constexpr]p4:
1612     //  The definition of a constexpr constructor shall satisfy the following
1613     //  constraints:
1614     //  - the class shall not have any virtual base classes;
1615     const CXXRecordDecl *RD = MD->getParent();
1616     if (RD->getNumVBases()) {
1617       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1618         << isa<CXXConstructorDecl>(NewFD)
1619         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1620       for (const auto &I : RD->vbases())
1621         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1622             << I.getSourceRange();
1623       return false;
1624     }
1625   }
1626 
1627   if (!isa<CXXConstructorDecl>(NewFD)) {
1628     // C++11 [dcl.constexpr]p3:
1629     //  The definition of a constexpr function shall satisfy the following
1630     //  constraints:
1631     // - it shall not be virtual;
1632     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1633     if (Method && Method->isVirtual()) {
1634       Method = Method->getCanonicalDecl();
1635       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1636 
1637       // If it's not obvious why this function is virtual, find an overridden
1638       // function which uses the 'virtual' keyword.
1639       const CXXMethodDecl *WrittenVirtual = Method;
1640       while (!WrittenVirtual->isVirtualAsWritten())
1641         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1642       if (WrittenVirtual != Method)
1643         Diag(WrittenVirtual->getLocation(),
1644              diag::note_overridden_virtual_function);
1645       return false;
1646     }
1647 
1648     // - its return type shall be a literal type;
1649     QualType RT = NewFD->getReturnType();
1650     if (!RT->isDependentType() &&
1651         RequireLiteralType(NewFD->getLocation(), RT,
1652                            diag::err_constexpr_non_literal_return))
1653       return false;
1654   }
1655 
1656   // - each of its parameter types shall be a literal type;
1657   if (!CheckConstexprParameterTypes(*this, NewFD))
1658     return false;
1659 
1660   return true;
1661 }
1662 
1663 /// Check the given declaration statement is legal within a constexpr function
1664 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1665 ///
1666 /// \return true if the body is OK (maybe only as an extension), false if we
1667 ///         have diagnosed a problem.
1668 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1669                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1670   // C++11 [dcl.constexpr]p3 and p4:
1671   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1672   //  contain only
1673   for (const auto *DclIt : DS->decls()) {
1674     switch (DclIt->getKind()) {
1675     case Decl::StaticAssert:
1676     case Decl::Using:
1677     case Decl::UsingShadow:
1678     case Decl::UsingDirective:
1679     case Decl::UnresolvedUsingTypename:
1680     case Decl::UnresolvedUsingValue:
1681       //   - static_assert-declarations
1682       //   - using-declarations,
1683       //   - using-directives,
1684       continue;
1685 
1686     case Decl::Typedef:
1687     case Decl::TypeAlias: {
1688       //   - typedef declarations and alias-declarations that do not define
1689       //     classes or enumerations,
1690       const auto *TN = cast<TypedefNameDecl>(DclIt);
1691       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1692         // Don't allow variably-modified types in constexpr functions.
1693         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1694         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1695           << TL.getSourceRange() << TL.getType()
1696           << isa<CXXConstructorDecl>(Dcl);
1697         return false;
1698       }
1699       continue;
1700     }
1701 
1702     case Decl::Enum:
1703     case Decl::CXXRecord:
1704       // C++1y allows types to be defined, not just declared.
1705       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1706         SemaRef.Diag(DS->getBeginLoc(),
1707                      SemaRef.getLangOpts().CPlusPlus14
1708                          ? diag::warn_cxx11_compat_constexpr_type_definition
1709                          : diag::ext_constexpr_type_definition)
1710             << isa<CXXConstructorDecl>(Dcl);
1711       continue;
1712 
1713     case Decl::EnumConstant:
1714     case Decl::IndirectField:
1715     case Decl::ParmVar:
1716       // These can only appear with other declarations which are banned in
1717       // C++11 and permitted in C++1y, so ignore them.
1718       continue;
1719 
1720     case Decl::Var:
1721     case Decl::Decomposition: {
1722       // C++1y [dcl.constexpr]p3 allows anything except:
1723       //   a definition of a variable of non-literal type or of static or
1724       //   thread storage duration or for which no initialization is performed.
1725       const auto *VD = cast<VarDecl>(DclIt);
1726       if (VD->isThisDeclarationADefinition()) {
1727         if (VD->isStaticLocal()) {
1728           SemaRef.Diag(VD->getLocation(),
1729                        diag::err_constexpr_local_var_static)
1730             << isa<CXXConstructorDecl>(Dcl)
1731             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1732           return false;
1733         }
1734         if (!VD->getType()->isDependentType() &&
1735             SemaRef.RequireLiteralType(
1736               VD->getLocation(), VD->getType(),
1737               diag::err_constexpr_local_var_non_literal_type,
1738               isa<CXXConstructorDecl>(Dcl)))
1739           return false;
1740         if (!VD->getType()->isDependentType() &&
1741             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1742           SemaRef.Diag(VD->getLocation(),
1743                        diag::err_constexpr_local_var_no_init)
1744             << isa<CXXConstructorDecl>(Dcl);
1745           return false;
1746         }
1747       }
1748       SemaRef.Diag(VD->getLocation(),
1749                    SemaRef.getLangOpts().CPlusPlus14
1750                     ? diag::warn_cxx11_compat_constexpr_local_var
1751                     : diag::ext_constexpr_local_var)
1752         << isa<CXXConstructorDecl>(Dcl);
1753       continue;
1754     }
1755 
1756     case Decl::NamespaceAlias:
1757     case Decl::Function:
1758       // These are disallowed in C++11 and permitted in C++1y. Allow them
1759       // everywhere as an extension.
1760       if (!Cxx1yLoc.isValid())
1761         Cxx1yLoc = DS->getBeginLoc();
1762       continue;
1763 
1764     default:
1765       SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1766           << isa<CXXConstructorDecl>(Dcl);
1767       return false;
1768     }
1769   }
1770 
1771   return true;
1772 }
1773 
1774 /// Check that the given field is initialized within a constexpr constructor.
1775 ///
1776 /// \param Dcl The constexpr constructor being checked.
1777 /// \param Field The field being checked. This may be a member of an anonymous
1778 ///        struct or union nested within the class being checked.
1779 /// \param Inits All declarations, including anonymous struct/union members and
1780 ///        indirect members, for which any initialization was provided.
1781 /// \param Diagnosed Set to true if an error is produced.
1782 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1783                                           const FunctionDecl *Dcl,
1784                                           FieldDecl *Field,
1785                                           llvm::SmallSet<Decl*, 16> &Inits,
1786                                           bool &Diagnosed) {
1787   if (Field->isInvalidDecl())
1788     return;
1789 
1790   if (Field->isUnnamedBitfield())
1791     return;
1792 
1793   // Anonymous unions with no variant members and empty anonymous structs do not
1794   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1795   // indirect fields don't need initializing.
1796   if (Field->isAnonymousStructOrUnion() &&
1797       (Field->getType()->isUnionType()
1798            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1799            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1800     return;
1801 
1802   if (!Inits.count(Field)) {
1803     if (!Diagnosed) {
1804       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1805       Diagnosed = true;
1806     }
1807     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1808   } else if (Field->isAnonymousStructOrUnion()) {
1809     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1810     for (auto *I : RD->fields())
1811       // If an anonymous union contains an anonymous struct of which any member
1812       // is initialized, all members must be initialized.
1813       if (!RD->isUnion() || Inits.count(I))
1814         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1815   }
1816 }
1817 
1818 /// Check the provided statement is allowed in a constexpr function
1819 /// definition.
1820 static bool
1821 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1822                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1823                            SourceLocation &Cxx1yLoc) {
1824   // - its function-body shall be [...] a compound-statement that contains only
1825   switch (S->getStmtClass()) {
1826   case Stmt::NullStmtClass:
1827     //   - null statements,
1828     return true;
1829 
1830   case Stmt::DeclStmtClass:
1831     //   - static_assert-declarations
1832     //   - using-declarations,
1833     //   - using-directives,
1834     //   - typedef declarations and alias-declarations that do not define
1835     //     classes or enumerations,
1836     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1837       return false;
1838     return true;
1839 
1840   case Stmt::ReturnStmtClass:
1841     //   - and exactly one return statement;
1842     if (isa<CXXConstructorDecl>(Dcl)) {
1843       // C++1y allows return statements in constexpr constructors.
1844       if (!Cxx1yLoc.isValid())
1845         Cxx1yLoc = S->getBeginLoc();
1846       return true;
1847     }
1848 
1849     ReturnStmts.push_back(S->getBeginLoc());
1850     return true;
1851 
1852   case Stmt::CompoundStmtClass: {
1853     // C++1y allows compound-statements.
1854     if (!Cxx1yLoc.isValid())
1855       Cxx1yLoc = S->getBeginLoc();
1856 
1857     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1858     for (auto *BodyIt : CompStmt->body()) {
1859       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1860                                       Cxx1yLoc))
1861         return false;
1862     }
1863     return true;
1864   }
1865 
1866   case Stmt::AttributedStmtClass:
1867     if (!Cxx1yLoc.isValid())
1868       Cxx1yLoc = S->getBeginLoc();
1869     return true;
1870 
1871   case Stmt::IfStmtClass: {
1872     // C++1y allows if-statements.
1873     if (!Cxx1yLoc.isValid())
1874       Cxx1yLoc = S->getBeginLoc();
1875 
1876     IfStmt *If = cast<IfStmt>(S);
1877     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1878                                     Cxx1yLoc))
1879       return false;
1880     if (If->getElse() &&
1881         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1882                                     Cxx1yLoc))
1883       return false;
1884     return true;
1885   }
1886 
1887   case Stmt::WhileStmtClass:
1888   case Stmt::DoStmtClass:
1889   case Stmt::ForStmtClass:
1890   case Stmt::CXXForRangeStmtClass:
1891   case Stmt::ContinueStmtClass:
1892     // C++1y allows all of these. We don't allow them as extensions in C++11,
1893     // because they don't make sense without variable mutation.
1894     if (!SemaRef.getLangOpts().CPlusPlus14)
1895       break;
1896     if (!Cxx1yLoc.isValid())
1897       Cxx1yLoc = S->getBeginLoc();
1898     for (Stmt *SubStmt : S->children())
1899       if (SubStmt &&
1900           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1901                                       Cxx1yLoc))
1902         return false;
1903     return true;
1904 
1905   case Stmt::SwitchStmtClass:
1906   case Stmt::CaseStmtClass:
1907   case Stmt::DefaultStmtClass:
1908   case Stmt::BreakStmtClass:
1909     // C++1y allows switch-statements, and since they don't need variable
1910     // mutation, we can reasonably allow them in C++11 as an extension.
1911     if (!Cxx1yLoc.isValid())
1912       Cxx1yLoc = S->getBeginLoc();
1913     for (Stmt *SubStmt : S->children())
1914       if (SubStmt &&
1915           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1916                                       Cxx1yLoc))
1917         return false;
1918     return true;
1919 
1920   default:
1921     if (!isa<Expr>(S))
1922       break;
1923 
1924     // C++1y allows expression-statements.
1925     if (!Cxx1yLoc.isValid())
1926       Cxx1yLoc = S->getBeginLoc();
1927     return true;
1928   }
1929 
1930   SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1931       << isa<CXXConstructorDecl>(Dcl);
1932   return false;
1933 }
1934 
1935 /// Check the body for the given constexpr function declaration only contains
1936 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1937 ///
1938 /// \return true if the body is OK, false if we have diagnosed a problem.
1939 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1940   if (isa<CXXTryStmt>(Body)) {
1941     // C++11 [dcl.constexpr]p3:
1942     //  The definition of a constexpr function shall satisfy the following
1943     //  constraints: [...]
1944     // - its function-body shall be = delete, = default, or a
1945     //   compound-statement
1946     //
1947     // C++11 [dcl.constexpr]p4:
1948     //  In the definition of a constexpr constructor, [...]
1949     // - its function-body shall not be a function-try-block;
1950     Diag(Body->getBeginLoc(), diag::err_constexpr_function_try_block)
1951         << isa<CXXConstructorDecl>(Dcl);
1952     return false;
1953   }
1954 
1955   SmallVector<SourceLocation, 4> ReturnStmts;
1956 
1957   // - its function-body shall be [...] a compound-statement that contains only
1958   //   [... list of cases ...]
1959   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1960   SourceLocation Cxx1yLoc;
1961   for (auto *BodyIt : CompBody->body()) {
1962     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1963       return false;
1964   }
1965 
1966   if (Cxx1yLoc.isValid())
1967     Diag(Cxx1yLoc,
1968          getLangOpts().CPlusPlus14
1969            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1970            : diag::ext_constexpr_body_invalid_stmt)
1971       << isa<CXXConstructorDecl>(Dcl);
1972 
1973   if (const CXXConstructorDecl *Constructor
1974         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1975     const CXXRecordDecl *RD = Constructor->getParent();
1976     // DR1359:
1977     // - every non-variant non-static data member and base class sub-object
1978     //   shall be initialized;
1979     // DR1460:
1980     // - if the class is a union having variant members, exactly one of them
1981     //   shall be initialized;
1982     if (RD->isUnion()) {
1983       if (Constructor->getNumCtorInitializers() == 0 &&
1984           RD->hasVariantMembers()) {
1985         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1986         return false;
1987       }
1988     } else if (!Constructor->isDependentContext() &&
1989                !Constructor->isDelegatingConstructor()) {
1990       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1991 
1992       // Skip detailed checking if we have enough initializers, and we would
1993       // allow at most one initializer per member.
1994       bool AnyAnonStructUnionMembers = false;
1995       unsigned Fields = 0;
1996       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1997            E = RD->field_end(); I != E; ++I, ++Fields) {
1998         if (I->isAnonymousStructOrUnion()) {
1999           AnyAnonStructUnionMembers = true;
2000           break;
2001         }
2002       }
2003       // DR1460:
2004       // - if the class is a union-like class, but is not a union, for each of
2005       //   its anonymous union members having variant members, exactly one of
2006       //   them shall be initialized;
2007       if (AnyAnonStructUnionMembers ||
2008           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2009         // Check initialization of non-static data members. Base classes are
2010         // always initialized so do not need to be checked. Dependent bases
2011         // might not have initializers in the member initializer list.
2012         llvm::SmallSet<Decl*, 16> Inits;
2013         for (const auto *I: Constructor->inits()) {
2014           if (FieldDecl *FD = I->getMember())
2015             Inits.insert(FD);
2016           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2017             Inits.insert(ID->chain_begin(), ID->chain_end());
2018         }
2019 
2020         bool Diagnosed = false;
2021         for (auto *I : RD->fields())
2022           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2023         if (Diagnosed)
2024           return false;
2025       }
2026     }
2027   } else {
2028     if (ReturnStmts.empty()) {
2029       // C++1y doesn't require constexpr functions to contain a 'return'
2030       // statement. We still do, unless the return type might be void, because
2031       // otherwise if there's no return statement, the function cannot
2032       // be used in a core constant expression.
2033       bool OK = getLangOpts().CPlusPlus14 &&
2034                 (Dcl->getReturnType()->isVoidType() ||
2035                  Dcl->getReturnType()->isDependentType());
2036       Diag(Dcl->getLocation(),
2037            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2038               : diag::err_constexpr_body_no_return);
2039       if (!OK)
2040         return false;
2041     } else if (ReturnStmts.size() > 1) {
2042       Diag(ReturnStmts.back(),
2043            getLangOpts().CPlusPlus14
2044              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2045              : diag::ext_constexpr_body_multiple_return);
2046       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2047         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2048     }
2049   }
2050 
2051   // C++11 [dcl.constexpr]p5:
2052   //   if no function argument values exist such that the function invocation
2053   //   substitution would produce a constant expression, the program is
2054   //   ill-formed; no diagnostic required.
2055   // C++11 [dcl.constexpr]p3:
2056   //   - every constructor call and implicit conversion used in initializing the
2057   //     return value shall be one of those allowed in a constant expression.
2058   // C++11 [dcl.constexpr]p4:
2059   //   - every constructor involved in initializing non-static data members and
2060   //     base class sub-objects shall be a constexpr constructor.
2061   SmallVector<PartialDiagnosticAt, 8> Diags;
2062   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2063     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2064       << isa<CXXConstructorDecl>(Dcl);
2065     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2066       Diag(Diags[I].first, Diags[I].second);
2067     // Don't return false here: we allow this for compatibility in
2068     // system headers.
2069   }
2070 
2071   return true;
2072 }
2073 
2074 /// Get the class that is directly named by the current context. This is the
2075 /// class for which an unqualified-id in this scope could name a constructor
2076 /// or destructor.
2077 ///
2078 /// If the scope specifier denotes a class, this will be that class.
2079 /// If the scope specifier is empty, this will be the class whose
2080 /// member-specification we are currently within. Otherwise, there
2081 /// is no such class.
2082 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2083   assert(getLangOpts().CPlusPlus && "No class names in C!");
2084 
2085   if (SS && SS->isInvalid())
2086     return nullptr;
2087 
2088   if (SS && SS->isNotEmpty()) {
2089     DeclContext *DC = computeDeclContext(*SS, true);
2090     return dyn_cast_or_null<CXXRecordDecl>(DC);
2091   }
2092 
2093   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2094 }
2095 
2096 /// isCurrentClassName - Determine whether the identifier II is the
2097 /// name of the class type currently being defined. In the case of
2098 /// nested classes, this will only return true if II is the name of
2099 /// the innermost class.
2100 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2101                               const CXXScopeSpec *SS) {
2102   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2103   return CurDecl && &II == CurDecl->getIdentifier();
2104 }
2105 
2106 /// Determine whether the identifier II is a typo for the name of
2107 /// the class type currently being defined. If so, update it to the identifier
2108 /// that should have been used.
2109 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2110   assert(getLangOpts().CPlusPlus && "No class names in C!");
2111 
2112   if (!getLangOpts().SpellChecking)
2113     return false;
2114 
2115   CXXRecordDecl *CurDecl;
2116   if (SS && SS->isSet() && !SS->isInvalid()) {
2117     DeclContext *DC = computeDeclContext(*SS, true);
2118     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2119   } else
2120     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2121 
2122   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2123       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2124           < II->getLength()) {
2125     II = CurDecl->getIdentifier();
2126     return true;
2127   }
2128 
2129   return false;
2130 }
2131 
2132 /// Determine whether the given class is a base class of the given
2133 /// class, including looking at dependent bases.
2134 static bool findCircularInheritance(const CXXRecordDecl *Class,
2135                                     const CXXRecordDecl *Current) {
2136   SmallVector<const CXXRecordDecl*, 8> Queue;
2137 
2138   Class = Class->getCanonicalDecl();
2139   while (true) {
2140     for (const auto &I : Current->bases()) {
2141       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2142       if (!Base)
2143         continue;
2144 
2145       Base = Base->getDefinition();
2146       if (!Base)
2147         continue;
2148 
2149       if (Base->getCanonicalDecl() == Class)
2150         return true;
2151 
2152       Queue.push_back(Base);
2153     }
2154 
2155     if (Queue.empty())
2156       return false;
2157 
2158     Current = Queue.pop_back_val();
2159   }
2160 
2161   return false;
2162 }
2163 
2164 /// Check the validity of a C++ base class specifier.
2165 ///
2166 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2167 /// and returns NULL otherwise.
2168 CXXBaseSpecifier *
2169 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2170                          SourceRange SpecifierRange,
2171                          bool Virtual, AccessSpecifier Access,
2172                          TypeSourceInfo *TInfo,
2173                          SourceLocation EllipsisLoc) {
2174   QualType BaseType = TInfo->getType();
2175 
2176   // C++ [class.union]p1:
2177   //   A union shall not have base classes.
2178   if (Class->isUnion()) {
2179     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2180       << SpecifierRange;
2181     return nullptr;
2182   }
2183 
2184   if (EllipsisLoc.isValid() &&
2185       !TInfo->getType()->containsUnexpandedParameterPack()) {
2186     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2187       << TInfo->getTypeLoc().getSourceRange();
2188     EllipsisLoc = SourceLocation();
2189   }
2190 
2191   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2192 
2193   if (BaseType->isDependentType()) {
2194     // Make sure that we don't have circular inheritance among our dependent
2195     // bases. For non-dependent bases, the check for completeness below handles
2196     // this.
2197     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2198       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2199           ((BaseDecl = BaseDecl->getDefinition()) &&
2200            findCircularInheritance(Class, BaseDecl))) {
2201         Diag(BaseLoc, diag::err_circular_inheritance)
2202           << BaseType << Context.getTypeDeclType(Class);
2203 
2204         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2205           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2206             << BaseType;
2207 
2208         return nullptr;
2209       }
2210     }
2211 
2212     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2213                                           Class->getTagKind() == TTK_Class,
2214                                           Access, TInfo, EllipsisLoc);
2215   }
2216 
2217   // Base specifiers must be record types.
2218   if (!BaseType->isRecordType()) {
2219     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2220     return nullptr;
2221   }
2222 
2223   // C++ [class.union]p1:
2224   //   A union shall not be used as a base class.
2225   if (BaseType->isUnionType()) {
2226     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2227     return nullptr;
2228   }
2229 
2230   // For the MS ABI, propagate DLL attributes to base class templates.
2231   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2232     if (Attr *ClassAttr = getDLLAttr(Class)) {
2233       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2234               BaseType->getAsCXXRecordDecl())) {
2235         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2236                                             BaseLoc);
2237       }
2238     }
2239   }
2240 
2241   // C++ [class.derived]p2:
2242   //   The class-name in a base-specifier shall not be an incompletely
2243   //   defined class.
2244   if (RequireCompleteType(BaseLoc, BaseType,
2245                           diag::err_incomplete_base_class, SpecifierRange)) {
2246     Class->setInvalidDecl();
2247     return nullptr;
2248   }
2249 
2250   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2251   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2252   assert(BaseDecl && "Record type has no declaration");
2253   BaseDecl = BaseDecl->getDefinition();
2254   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2255   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2256   assert(CXXBaseDecl && "Base type is not a C++ type");
2257 
2258   // Microsoft docs say:
2259   // "If a base-class has a code_seg attribute, derived classes must have the
2260   // same attribute."
2261   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2262   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2263   if ((DerivedCSA || BaseCSA) &&
2264       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2265     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2266     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2267       << CXXBaseDecl;
2268     return nullptr;
2269   }
2270 
2271   // A class which contains a flexible array member is not suitable for use as a
2272   // base class:
2273   //   - If the layout determines that a base comes before another base,
2274   //     the flexible array member would index into the subsequent base.
2275   //   - If the layout determines that base comes before the derived class,
2276   //     the flexible array member would index into the derived class.
2277   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2278     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2279       << CXXBaseDecl->getDeclName();
2280     return nullptr;
2281   }
2282 
2283   // C++ [class]p3:
2284   //   If a class is marked final and it appears as a base-type-specifier in
2285   //   base-clause, the program is ill-formed.
2286   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2287     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2288       << CXXBaseDecl->getDeclName()
2289       << FA->isSpelledAsSealed();
2290     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2291         << CXXBaseDecl->getDeclName() << FA->getRange();
2292     return nullptr;
2293   }
2294 
2295   if (BaseDecl->isInvalidDecl())
2296     Class->setInvalidDecl();
2297 
2298   // Create the base specifier.
2299   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2300                                         Class->getTagKind() == TTK_Class,
2301                                         Access, TInfo, EllipsisLoc);
2302 }
2303 
2304 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2305 /// one entry in the base class list of a class specifier, for
2306 /// example:
2307 ///    class foo : public bar, virtual private baz {
2308 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2309 BaseResult
2310 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2311                          ParsedAttributes &Attributes,
2312                          bool Virtual, AccessSpecifier Access,
2313                          ParsedType basetype, SourceLocation BaseLoc,
2314                          SourceLocation EllipsisLoc) {
2315   if (!classdecl)
2316     return true;
2317 
2318   AdjustDeclIfTemplate(classdecl);
2319   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2320   if (!Class)
2321     return true;
2322 
2323   // We haven't yet attached the base specifiers.
2324   Class->setIsParsingBaseSpecifiers();
2325 
2326   // We do not support any C++11 attributes on base-specifiers yet.
2327   // Diagnose any attributes we see.
2328   for (const ParsedAttr &AL : Attributes) {
2329     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2330       continue;
2331     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2332                           ? diag::warn_unknown_attribute_ignored
2333                           : diag::err_base_specifier_attribute)
2334         << AL.getName();
2335   }
2336 
2337   TypeSourceInfo *TInfo = nullptr;
2338   GetTypeFromParser(basetype, &TInfo);
2339 
2340   if (EllipsisLoc.isInvalid() &&
2341       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2342                                       UPPC_BaseType))
2343     return true;
2344 
2345   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2346                                                       Virtual, Access, TInfo,
2347                                                       EllipsisLoc))
2348     return BaseSpec;
2349   else
2350     Class->setInvalidDecl();
2351 
2352   return true;
2353 }
2354 
2355 /// Use small set to collect indirect bases.  As this is only used
2356 /// locally, there's no need to abstract the small size parameter.
2357 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2358 
2359 /// Recursively add the bases of Type.  Don't add Type itself.
2360 static void
2361 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2362                   const QualType &Type)
2363 {
2364   // Even though the incoming type is a base, it might not be
2365   // a class -- it could be a template parm, for instance.
2366   if (auto Rec = Type->getAs<RecordType>()) {
2367     auto Decl = Rec->getAsCXXRecordDecl();
2368 
2369     // Iterate over its bases.
2370     for (const auto &BaseSpec : Decl->bases()) {
2371       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2372         .getUnqualifiedType();
2373       if (Set.insert(Base).second)
2374         // If we've not already seen it, recurse.
2375         NoteIndirectBases(Context, Set, Base);
2376     }
2377   }
2378 }
2379 
2380 /// Performs the actual work of attaching the given base class
2381 /// specifiers to a C++ class.
2382 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2383                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2384  if (Bases.empty())
2385     return false;
2386 
2387   // Used to keep track of which base types we have already seen, so
2388   // that we can properly diagnose redundant direct base types. Note
2389   // that the key is always the unqualified canonical type of the base
2390   // class.
2391   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2392 
2393   // Used to track indirect bases so we can see if a direct base is
2394   // ambiguous.
2395   IndirectBaseSet IndirectBaseTypes;
2396 
2397   // Copy non-redundant base specifiers into permanent storage.
2398   unsigned NumGoodBases = 0;
2399   bool Invalid = false;
2400   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2401     QualType NewBaseType
2402       = Context.getCanonicalType(Bases[idx]->getType());
2403     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2404 
2405     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2406     if (KnownBase) {
2407       // C++ [class.mi]p3:
2408       //   A class shall not be specified as a direct base class of a
2409       //   derived class more than once.
2410       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2411           << KnownBase->getType() << Bases[idx]->getSourceRange();
2412 
2413       // Delete the duplicate base class specifier; we're going to
2414       // overwrite its pointer later.
2415       Context.Deallocate(Bases[idx]);
2416 
2417       Invalid = true;
2418     } else {
2419       // Okay, add this new base class.
2420       KnownBase = Bases[idx];
2421       Bases[NumGoodBases++] = Bases[idx];
2422 
2423       // Note this base's direct & indirect bases, if there could be ambiguity.
2424       if (Bases.size() > 1)
2425         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2426 
2427       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2428         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2429         if (Class->isInterface() &&
2430               (!RD->isInterfaceLike() ||
2431                KnownBase->getAccessSpecifier() != AS_public)) {
2432           // The Microsoft extension __interface does not permit bases that
2433           // are not themselves public interfaces.
2434           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2435               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2436               << RD->getSourceRange();
2437           Invalid = true;
2438         }
2439         if (RD->hasAttr<WeakAttr>())
2440           Class->addAttr(WeakAttr::CreateImplicit(Context));
2441       }
2442     }
2443   }
2444 
2445   // Attach the remaining base class specifiers to the derived class.
2446   Class->setBases(Bases.data(), NumGoodBases);
2447 
2448   // Check that the only base classes that are duplicate are virtual.
2449   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2450     // Check whether this direct base is inaccessible due to ambiguity.
2451     QualType BaseType = Bases[idx]->getType();
2452 
2453     // Skip all dependent types in templates being used as base specifiers.
2454     // Checks below assume that the base specifier is a CXXRecord.
2455     if (BaseType->isDependentType())
2456       continue;
2457 
2458     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2459       .getUnqualifiedType();
2460 
2461     if (IndirectBaseTypes.count(CanonicalBase)) {
2462       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2463                          /*DetectVirtual=*/true);
2464       bool found
2465         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2466       assert(found);
2467       (void)found;
2468 
2469       if (Paths.isAmbiguous(CanonicalBase))
2470         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2471             << BaseType << getAmbiguousPathsDisplayString(Paths)
2472             << Bases[idx]->getSourceRange();
2473       else
2474         assert(Bases[idx]->isVirtual());
2475     }
2476 
2477     // Delete the base class specifier, since its data has been copied
2478     // into the CXXRecordDecl.
2479     Context.Deallocate(Bases[idx]);
2480   }
2481 
2482   return Invalid;
2483 }
2484 
2485 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2486 /// class, after checking whether there are any duplicate base
2487 /// classes.
2488 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2489                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2490   if (!ClassDecl || Bases.empty())
2491     return;
2492 
2493   AdjustDeclIfTemplate(ClassDecl);
2494   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2495 }
2496 
2497 /// Determine whether the type \p Derived is a C++ class that is
2498 /// derived from the type \p Base.
2499 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2500   if (!getLangOpts().CPlusPlus)
2501     return false;
2502 
2503   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2504   if (!DerivedRD)
2505     return false;
2506 
2507   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2508   if (!BaseRD)
2509     return false;
2510 
2511   // If either the base or the derived type is invalid, don't try to
2512   // check whether one is derived from the other.
2513   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2514     return false;
2515 
2516   // FIXME: In a modules build, do we need the entire path to be visible for us
2517   // to be able to use the inheritance relationship?
2518   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2519     return false;
2520 
2521   return DerivedRD->isDerivedFrom(BaseRD);
2522 }
2523 
2524 /// Determine whether the type \p Derived is a C++ class that is
2525 /// derived from the type \p Base.
2526 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2527                          CXXBasePaths &Paths) {
2528   if (!getLangOpts().CPlusPlus)
2529     return false;
2530 
2531   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2532   if (!DerivedRD)
2533     return false;
2534 
2535   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2536   if (!BaseRD)
2537     return false;
2538 
2539   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2540     return false;
2541 
2542   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2543 }
2544 
2545 static void BuildBasePathArray(const CXXBasePath &Path,
2546                                CXXCastPath &BasePathArray) {
2547   // We first go backward and check if we have a virtual base.
2548   // FIXME: It would be better if CXXBasePath had the base specifier for
2549   // the nearest virtual base.
2550   unsigned Start = 0;
2551   for (unsigned I = Path.size(); I != 0; --I) {
2552     if (Path[I - 1].Base->isVirtual()) {
2553       Start = I - 1;
2554       break;
2555     }
2556   }
2557 
2558   // Now add all bases.
2559   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2560     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2561 }
2562 
2563 
2564 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2565                               CXXCastPath &BasePathArray) {
2566   assert(BasePathArray.empty() && "Base path array must be empty!");
2567   assert(Paths.isRecordingPaths() && "Must record paths!");
2568   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2569 }
2570 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2571 /// conversion (where Derived and Base are class types) is
2572 /// well-formed, meaning that the conversion is unambiguous (and
2573 /// that all of the base classes are accessible). Returns true
2574 /// and emits a diagnostic if the code is ill-formed, returns false
2575 /// otherwise. Loc is the location where this routine should point to
2576 /// if there is an error, and Range is the source range to highlight
2577 /// if there is an error.
2578 ///
2579 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2580 /// diagnostic for the respective type of error will be suppressed, but the
2581 /// check for ill-formed code will still be performed.
2582 bool
2583 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2584                                    unsigned InaccessibleBaseID,
2585                                    unsigned AmbigiousBaseConvID,
2586                                    SourceLocation Loc, SourceRange Range,
2587                                    DeclarationName Name,
2588                                    CXXCastPath *BasePath,
2589                                    bool IgnoreAccess) {
2590   // First, determine whether the path from Derived to Base is
2591   // ambiguous. This is slightly more expensive than checking whether
2592   // the Derived to Base conversion exists, because here we need to
2593   // explore multiple paths to determine if there is an ambiguity.
2594   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2595                      /*DetectVirtual=*/false);
2596   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2597   if (!DerivationOkay)
2598     return true;
2599 
2600   const CXXBasePath *Path = nullptr;
2601   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2602     Path = &Paths.front();
2603 
2604   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2605   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2606   // user to access such bases.
2607   if (!Path && getLangOpts().MSVCCompat) {
2608     for (const CXXBasePath &PossiblePath : Paths) {
2609       if (PossiblePath.size() == 1) {
2610         Path = &PossiblePath;
2611         if (AmbigiousBaseConvID)
2612           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2613               << Base << Derived << Range;
2614         break;
2615       }
2616     }
2617   }
2618 
2619   if (Path) {
2620     if (!IgnoreAccess) {
2621       // Check that the base class can be accessed.
2622       switch (
2623           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2624       case AR_inaccessible:
2625         return true;
2626       case AR_accessible:
2627       case AR_dependent:
2628       case AR_delayed:
2629         break;
2630       }
2631     }
2632 
2633     // Build a base path if necessary.
2634     if (BasePath)
2635       ::BuildBasePathArray(*Path, *BasePath);
2636     return false;
2637   }
2638 
2639   if (AmbigiousBaseConvID) {
2640     // We know that the derived-to-base conversion is ambiguous, and
2641     // we're going to produce a diagnostic. Perform the derived-to-base
2642     // search just one more time to compute all of the possible paths so
2643     // that we can print them out. This is more expensive than any of
2644     // the previous derived-to-base checks we've done, but at this point
2645     // performance isn't as much of an issue.
2646     Paths.clear();
2647     Paths.setRecordingPaths(true);
2648     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2649     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2650     (void)StillOkay;
2651 
2652     // Build up a textual representation of the ambiguous paths, e.g.,
2653     // D -> B -> A, that will be used to illustrate the ambiguous
2654     // conversions in the diagnostic. We only print one of the paths
2655     // to each base class subobject.
2656     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2657 
2658     Diag(Loc, AmbigiousBaseConvID)
2659     << Derived << Base << PathDisplayStr << Range << Name;
2660   }
2661   return true;
2662 }
2663 
2664 bool
2665 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2666                                    SourceLocation Loc, SourceRange Range,
2667                                    CXXCastPath *BasePath,
2668                                    bool IgnoreAccess) {
2669   return CheckDerivedToBaseConversion(
2670       Derived, Base, diag::err_upcast_to_inaccessible_base,
2671       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2672       BasePath, IgnoreAccess);
2673 }
2674 
2675 
2676 /// Builds a string representing ambiguous paths from a
2677 /// specific derived class to different subobjects of the same base
2678 /// class.
2679 ///
2680 /// This function builds a string that can be used in error messages
2681 /// to show the different paths that one can take through the
2682 /// inheritance hierarchy to go from the derived class to different
2683 /// subobjects of a base class. The result looks something like this:
2684 /// @code
2685 /// struct D -> struct B -> struct A
2686 /// struct D -> struct C -> struct A
2687 /// @endcode
2688 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2689   std::string PathDisplayStr;
2690   std::set<unsigned> DisplayedPaths;
2691   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2692        Path != Paths.end(); ++Path) {
2693     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2694       // We haven't displayed a path to this particular base
2695       // class subobject yet.
2696       PathDisplayStr += "\n    ";
2697       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2698       for (CXXBasePath::const_iterator Element = Path->begin();
2699            Element != Path->end(); ++Element)
2700         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2701     }
2702   }
2703 
2704   return PathDisplayStr;
2705 }
2706 
2707 //===----------------------------------------------------------------------===//
2708 // C++ class member Handling
2709 //===----------------------------------------------------------------------===//
2710 
2711 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2712 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2713                                 SourceLocation ColonLoc,
2714                                 const ParsedAttributesView &Attrs) {
2715   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2716   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2717                                                   ASLoc, ColonLoc);
2718   CurContext->addHiddenDecl(ASDecl);
2719   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2720 }
2721 
2722 /// CheckOverrideControl - Check C++11 override control semantics.
2723 void Sema::CheckOverrideControl(NamedDecl *D) {
2724   if (D->isInvalidDecl())
2725     return;
2726 
2727   // We only care about "override" and "final" declarations.
2728   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2729     return;
2730 
2731   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2732 
2733   // We can't check dependent instance methods.
2734   if (MD && MD->isInstance() &&
2735       (MD->getParent()->hasAnyDependentBases() ||
2736        MD->getType()->isDependentType()))
2737     return;
2738 
2739   if (MD && !MD->isVirtual()) {
2740     // If we have a non-virtual method, check if if hides a virtual method.
2741     // (In that case, it's most likely the method has the wrong type.)
2742     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2743     FindHiddenVirtualMethods(MD, OverloadedMethods);
2744 
2745     if (!OverloadedMethods.empty()) {
2746       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2747         Diag(OA->getLocation(),
2748              diag::override_keyword_hides_virtual_member_function)
2749           << "override" << (OverloadedMethods.size() > 1);
2750       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2751         Diag(FA->getLocation(),
2752              diag::override_keyword_hides_virtual_member_function)
2753           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2754           << (OverloadedMethods.size() > 1);
2755       }
2756       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2757       MD->setInvalidDecl();
2758       return;
2759     }
2760     // Fall through into the general case diagnostic.
2761     // FIXME: We might want to attempt typo correction here.
2762   }
2763 
2764   if (!MD || !MD->isVirtual()) {
2765     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2766       Diag(OA->getLocation(),
2767            diag::override_keyword_only_allowed_on_virtual_member_functions)
2768         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2769       D->dropAttr<OverrideAttr>();
2770     }
2771     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2772       Diag(FA->getLocation(),
2773            diag::override_keyword_only_allowed_on_virtual_member_functions)
2774         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2775         << FixItHint::CreateRemoval(FA->getLocation());
2776       D->dropAttr<FinalAttr>();
2777     }
2778     return;
2779   }
2780 
2781   // C++11 [class.virtual]p5:
2782   //   If a function is marked with the virt-specifier override and
2783   //   does not override a member function of a base class, the program is
2784   //   ill-formed.
2785   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2786   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2787     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2788       << MD->getDeclName();
2789 }
2790 
2791 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2792   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2793     return;
2794   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2795   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2796     return;
2797 
2798   SourceLocation Loc = MD->getLocation();
2799   SourceLocation SpellingLoc = Loc;
2800   if (getSourceManager().isMacroArgExpansion(Loc))
2801     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2802   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2803   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2804       return;
2805 
2806   if (MD->size_overridden_methods() > 0) {
2807     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2808                           ? diag::warn_destructor_marked_not_override_overriding
2809                           : diag::warn_function_marked_not_override_overriding;
2810     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2811     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2812     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2813   }
2814 }
2815 
2816 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2817 /// function overrides a virtual member function marked 'final', according to
2818 /// C++11 [class.virtual]p4.
2819 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2820                                                   const CXXMethodDecl *Old) {
2821   FinalAttr *FA = Old->getAttr<FinalAttr>();
2822   if (!FA)
2823     return false;
2824 
2825   Diag(New->getLocation(), diag::err_final_function_overridden)
2826     << New->getDeclName()
2827     << FA->isSpelledAsSealed();
2828   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2829   return true;
2830 }
2831 
2832 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2833   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2834   // FIXME: Destruction of ObjC lifetime types has side-effects.
2835   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2836     return !RD->isCompleteDefinition() ||
2837            !RD->hasTrivialDefaultConstructor() ||
2838            !RD->hasTrivialDestructor();
2839   return false;
2840 }
2841 
2842 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2843   ParsedAttributesView::const_iterator Itr =
2844       llvm::find_if(list, [](const ParsedAttr &AL) {
2845         return AL.isDeclspecPropertyAttribute();
2846       });
2847   if (Itr != list.end())
2848     return &*Itr;
2849   return nullptr;
2850 }
2851 
2852 // Check if there is a field shadowing.
2853 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2854                                       DeclarationName FieldName,
2855                                       const CXXRecordDecl *RD) {
2856   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2857     return;
2858 
2859   // To record a shadowed field in a base
2860   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2861   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2862                            CXXBasePath &Path) {
2863     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2864     // Record an ambiguous path directly
2865     if (Bases.find(Base) != Bases.end())
2866       return true;
2867     for (const auto Field : Base->lookup(FieldName)) {
2868       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2869           Field->getAccess() != AS_private) {
2870         assert(Field->getAccess() != AS_none);
2871         assert(Bases.find(Base) == Bases.end());
2872         Bases[Base] = Field;
2873         return true;
2874       }
2875     }
2876     return false;
2877   };
2878 
2879   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2880                      /*DetectVirtual=*/true);
2881   if (!RD->lookupInBases(FieldShadowed, Paths))
2882     return;
2883 
2884   for (const auto &P : Paths) {
2885     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2886     auto It = Bases.find(Base);
2887     // Skip duplicated bases
2888     if (It == Bases.end())
2889       continue;
2890     auto BaseField = It->second;
2891     assert(BaseField->getAccess() != AS_private);
2892     if (AS_none !=
2893         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2894       Diag(Loc, diag::warn_shadow_field)
2895         << FieldName << RD << Base;
2896       Diag(BaseField->getLocation(), diag::note_shadow_field);
2897       Bases.erase(It);
2898     }
2899   }
2900 }
2901 
2902 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2903 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2904 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2905 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2906 /// present (but parsing it has been deferred).
2907 NamedDecl *
2908 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2909                                MultiTemplateParamsArg TemplateParameterLists,
2910                                Expr *BW, const VirtSpecifiers &VS,
2911                                InClassInitStyle InitStyle) {
2912   const DeclSpec &DS = D.getDeclSpec();
2913   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2914   DeclarationName Name = NameInfo.getName();
2915   SourceLocation Loc = NameInfo.getLoc();
2916 
2917   // For anonymous bitfields, the location should point to the type.
2918   if (Loc.isInvalid())
2919     Loc = D.getBeginLoc();
2920 
2921   Expr *BitWidth = static_cast<Expr*>(BW);
2922 
2923   assert(isa<CXXRecordDecl>(CurContext));
2924   assert(!DS.isFriendSpecified());
2925 
2926   bool isFunc = D.isDeclarationOfFunction();
2927   const ParsedAttr *MSPropertyAttr =
2928       getMSPropertyAttr(D.getDeclSpec().getAttributes());
2929 
2930   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2931     // The Microsoft extension __interface only permits public member functions
2932     // and prohibits constructors, destructors, operators, non-public member
2933     // functions, static methods and data members.
2934     unsigned InvalidDecl;
2935     bool ShowDeclName = true;
2936     if (!isFunc &&
2937         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2938       InvalidDecl = 0;
2939     else if (!isFunc)
2940       InvalidDecl = 1;
2941     else if (AS != AS_public)
2942       InvalidDecl = 2;
2943     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2944       InvalidDecl = 3;
2945     else switch (Name.getNameKind()) {
2946       case DeclarationName::CXXConstructorName:
2947         InvalidDecl = 4;
2948         ShowDeclName = false;
2949         break;
2950 
2951       case DeclarationName::CXXDestructorName:
2952         InvalidDecl = 5;
2953         ShowDeclName = false;
2954         break;
2955 
2956       case DeclarationName::CXXOperatorName:
2957       case DeclarationName::CXXConversionFunctionName:
2958         InvalidDecl = 6;
2959         break;
2960 
2961       default:
2962         InvalidDecl = 0;
2963         break;
2964     }
2965 
2966     if (InvalidDecl) {
2967       if (ShowDeclName)
2968         Diag(Loc, diag::err_invalid_member_in_interface)
2969           << (InvalidDecl-1) << Name;
2970       else
2971         Diag(Loc, diag::err_invalid_member_in_interface)
2972           << (InvalidDecl-1) << "";
2973       return nullptr;
2974     }
2975   }
2976 
2977   // C++ 9.2p6: A member shall not be declared to have automatic storage
2978   // duration (auto, register) or with the extern storage-class-specifier.
2979   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2980   // data members and cannot be applied to names declared const or static,
2981   // and cannot be applied to reference members.
2982   switch (DS.getStorageClassSpec()) {
2983   case DeclSpec::SCS_unspecified:
2984   case DeclSpec::SCS_typedef:
2985   case DeclSpec::SCS_static:
2986     break;
2987   case DeclSpec::SCS_mutable:
2988     if (isFunc) {
2989       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2990 
2991       // FIXME: It would be nicer if the keyword was ignored only for this
2992       // declarator. Otherwise we could get follow-up errors.
2993       D.getMutableDeclSpec().ClearStorageClassSpecs();
2994     }
2995     break;
2996   default:
2997     Diag(DS.getStorageClassSpecLoc(),
2998          diag::err_storageclass_invalid_for_member);
2999     D.getMutableDeclSpec().ClearStorageClassSpecs();
3000     break;
3001   }
3002 
3003   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3004                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3005                       !isFunc);
3006 
3007   if (DS.isConstexprSpecified() && isInstField) {
3008     SemaDiagnosticBuilder B =
3009         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3010     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3011     if (InitStyle == ICIS_NoInit) {
3012       B << 0 << 0;
3013       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3014         B << FixItHint::CreateRemoval(ConstexprLoc);
3015       else {
3016         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3017         D.getMutableDeclSpec().ClearConstexprSpec();
3018         const char *PrevSpec;
3019         unsigned DiagID;
3020         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3021             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3022         (void)Failed;
3023         assert(!Failed && "Making a constexpr member const shouldn't fail");
3024       }
3025     } else {
3026       B << 1;
3027       const char *PrevSpec;
3028       unsigned DiagID;
3029       if (D.getMutableDeclSpec().SetStorageClassSpec(
3030           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3031           Context.getPrintingPolicy())) {
3032         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3033                "This is the only DeclSpec that should fail to be applied");
3034         B << 1;
3035       } else {
3036         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3037         isInstField = false;
3038       }
3039     }
3040   }
3041 
3042   NamedDecl *Member;
3043   if (isInstField) {
3044     CXXScopeSpec &SS = D.getCXXScopeSpec();
3045 
3046     // Data members must have identifiers for names.
3047     if (!Name.isIdentifier()) {
3048       Diag(Loc, diag::err_bad_variable_name)
3049         << Name;
3050       return nullptr;
3051     }
3052 
3053     IdentifierInfo *II = Name.getAsIdentifierInfo();
3054 
3055     // Member field could not be with "template" keyword.
3056     // So TemplateParameterLists should be empty in this case.
3057     if (TemplateParameterLists.size()) {
3058       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3059       if (TemplateParams->size()) {
3060         // There is no such thing as a member field template.
3061         Diag(D.getIdentifierLoc(), diag::err_template_member)
3062             << II
3063             << SourceRange(TemplateParams->getTemplateLoc(),
3064                 TemplateParams->getRAngleLoc());
3065       } else {
3066         // There is an extraneous 'template<>' for this member.
3067         Diag(TemplateParams->getTemplateLoc(),
3068             diag::err_template_member_noparams)
3069             << II
3070             << SourceRange(TemplateParams->getTemplateLoc(),
3071                 TemplateParams->getRAngleLoc());
3072       }
3073       return nullptr;
3074     }
3075 
3076     if (SS.isSet() && !SS.isInvalid()) {
3077       // The user provided a superfluous scope specifier inside a class
3078       // definition:
3079       //
3080       // class X {
3081       //   int X::member;
3082       // };
3083       if (DeclContext *DC = computeDeclContext(SS, false))
3084         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3085                                      D.getName().getKind() ==
3086                                          UnqualifiedIdKind::IK_TemplateId);
3087       else
3088         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3089           << Name << SS.getRange();
3090 
3091       SS.clear();
3092     }
3093 
3094     if (MSPropertyAttr) {
3095       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3096                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3097       if (!Member)
3098         return nullptr;
3099       isInstField = false;
3100     } else {
3101       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3102                                 BitWidth, InitStyle, AS);
3103       if (!Member)
3104         return nullptr;
3105     }
3106 
3107     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3108   } else {
3109     Member = HandleDeclarator(S, D, TemplateParameterLists);
3110     if (!Member)
3111       return nullptr;
3112 
3113     // Non-instance-fields can't have a bitfield.
3114     if (BitWidth) {
3115       if (Member->isInvalidDecl()) {
3116         // don't emit another diagnostic.
3117       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3118         // C++ 9.6p3: A bit-field shall not be a static member.
3119         // "static member 'A' cannot be a bit-field"
3120         Diag(Loc, diag::err_static_not_bitfield)
3121           << Name << BitWidth->getSourceRange();
3122       } else if (isa<TypedefDecl>(Member)) {
3123         // "typedef member 'x' cannot be a bit-field"
3124         Diag(Loc, diag::err_typedef_not_bitfield)
3125           << Name << BitWidth->getSourceRange();
3126       } else {
3127         // A function typedef ("typedef int f(); f a;").
3128         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3129         Diag(Loc, diag::err_not_integral_type_bitfield)
3130           << Name << cast<ValueDecl>(Member)->getType()
3131           << BitWidth->getSourceRange();
3132       }
3133 
3134       BitWidth = nullptr;
3135       Member->setInvalidDecl();
3136     }
3137 
3138     NamedDecl *NonTemplateMember = Member;
3139     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3140       NonTemplateMember = FunTmpl->getTemplatedDecl();
3141     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3142       NonTemplateMember = VarTmpl->getTemplatedDecl();
3143 
3144     Member->setAccess(AS);
3145 
3146     // If we have declared a member function template or static data member
3147     // template, set the access of the templated declaration as well.
3148     if (NonTemplateMember != Member)
3149       NonTemplateMember->setAccess(AS);
3150 
3151     // C++ [temp.deduct.guide]p3:
3152     //   A deduction guide [...] for a member class template [shall be
3153     //   declared] with the same access [as the template].
3154     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3155       auto *TD = DG->getDeducedTemplate();
3156       if (AS != TD->getAccess()) {
3157         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3158         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3159             << TD->getAccess();
3160         const AccessSpecDecl *LastAccessSpec = nullptr;
3161         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3162           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3163             LastAccessSpec = AccessSpec;
3164         }
3165         assert(LastAccessSpec && "differing access with no access specifier");
3166         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3167             << AS;
3168       }
3169     }
3170   }
3171 
3172   if (VS.isOverrideSpecified())
3173     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3174   if (VS.isFinalSpecified())
3175     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3176                                             VS.isFinalSpelledSealed()));
3177 
3178   if (VS.getLastLocation().isValid()) {
3179     // Update the end location of a method that has a virt-specifiers.
3180     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3181       MD->setRangeEnd(VS.getLastLocation());
3182   }
3183 
3184   CheckOverrideControl(Member);
3185 
3186   assert((Name || isInstField) && "No identifier for non-field ?");
3187 
3188   if (isInstField) {
3189     FieldDecl *FD = cast<FieldDecl>(Member);
3190     FieldCollector->Add(FD);
3191 
3192     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3193       // Remember all explicit private FieldDecls that have a name, no side
3194       // effects and are not part of a dependent type declaration.
3195       if (!FD->isImplicit() && FD->getDeclName() &&
3196           FD->getAccess() == AS_private &&
3197           !FD->hasAttr<UnusedAttr>() &&
3198           !FD->getParent()->isDependentContext() &&
3199           !InitializationHasSideEffects(*FD))
3200         UnusedPrivateFields.insert(FD);
3201     }
3202   }
3203 
3204   return Member;
3205 }
3206 
3207 namespace {
3208   class UninitializedFieldVisitor
3209       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3210     Sema &S;
3211     // List of Decls to generate a warning on.  Also remove Decls that become
3212     // initialized.
3213     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3214     // List of base classes of the record.  Classes are removed after their
3215     // initializers.
3216     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3217     // Vector of decls to be removed from the Decl set prior to visiting the
3218     // nodes.  These Decls may have been initialized in the prior initializer.
3219     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3220     // If non-null, add a note to the warning pointing back to the constructor.
3221     const CXXConstructorDecl *Constructor;
3222     // Variables to hold state when processing an initializer list.  When
3223     // InitList is true, special case initialization of FieldDecls matching
3224     // InitListFieldDecl.
3225     bool InitList;
3226     FieldDecl *InitListFieldDecl;
3227     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3228 
3229   public:
3230     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3231     UninitializedFieldVisitor(Sema &S,
3232                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3233                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3234       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3235         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3236 
3237     // Returns true if the use of ME is not an uninitialized use.
3238     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3239                                          bool CheckReferenceOnly) {
3240       llvm::SmallVector<FieldDecl*, 4> Fields;
3241       bool ReferenceField = false;
3242       while (ME) {
3243         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3244         if (!FD)
3245           return false;
3246         Fields.push_back(FD);
3247         if (FD->getType()->isReferenceType())
3248           ReferenceField = true;
3249         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3250       }
3251 
3252       // Binding a reference to an unintialized field is not an
3253       // uninitialized use.
3254       if (CheckReferenceOnly && !ReferenceField)
3255         return true;
3256 
3257       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3258       // Discard the first field since it is the field decl that is being
3259       // initialized.
3260       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3261         UsedFieldIndex.push_back((*I)->getFieldIndex());
3262       }
3263 
3264       for (auto UsedIter = UsedFieldIndex.begin(),
3265                 UsedEnd = UsedFieldIndex.end(),
3266                 OrigIter = InitFieldIndex.begin(),
3267                 OrigEnd = InitFieldIndex.end();
3268            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3269         if (*UsedIter < *OrigIter)
3270           return true;
3271         if (*UsedIter > *OrigIter)
3272           break;
3273       }
3274 
3275       return false;
3276     }
3277 
3278     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3279                           bool AddressOf) {
3280       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3281         return;
3282 
3283       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3284       // or union.
3285       MemberExpr *FieldME = ME;
3286 
3287       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3288 
3289       Expr *Base = ME;
3290       while (MemberExpr *SubME =
3291                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3292 
3293         if (isa<VarDecl>(SubME->getMemberDecl()))
3294           return;
3295 
3296         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3297           if (!FD->isAnonymousStructOrUnion())
3298             FieldME = SubME;
3299 
3300         if (!FieldME->getType().isPODType(S.Context))
3301           AllPODFields = false;
3302 
3303         Base = SubME->getBase();
3304       }
3305 
3306       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3307         return;
3308 
3309       if (AddressOf && AllPODFields)
3310         return;
3311 
3312       ValueDecl* FoundVD = FieldME->getMemberDecl();
3313 
3314       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3315         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3316           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3317         }
3318 
3319         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3320           QualType T = BaseCast->getType();
3321           if (T->isPointerType() &&
3322               BaseClasses.count(T->getPointeeType())) {
3323             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3324                 << T->getPointeeType() << FoundVD;
3325           }
3326         }
3327       }
3328 
3329       if (!Decls.count(FoundVD))
3330         return;
3331 
3332       const bool IsReference = FoundVD->getType()->isReferenceType();
3333 
3334       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3335         // Special checking for initializer lists.
3336         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3337           return;
3338         }
3339       } else {
3340         // Prevent double warnings on use of unbounded references.
3341         if (CheckReferenceOnly && !IsReference)
3342           return;
3343       }
3344 
3345       unsigned diag = IsReference
3346           ? diag::warn_reference_field_is_uninit
3347           : diag::warn_field_is_uninit;
3348       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3349       if (Constructor)
3350         S.Diag(Constructor->getLocation(),
3351                diag::note_uninit_in_this_constructor)
3352           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3353 
3354     }
3355 
3356     void HandleValue(Expr *E, bool AddressOf) {
3357       E = E->IgnoreParens();
3358 
3359       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3360         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3361                          AddressOf /*AddressOf*/);
3362         return;
3363       }
3364 
3365       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3366         Visit(CO->getCond());
3367         HandleValue(CO->getTrueExpr(), AddressOf);
3368         HandleValue(CO->getFalseExpr(), AddressOf);
3369         return;
3370       }
3371 
3372       if (BinaryConditionalOperator *BCO =
3373               dyn_cast<BinaryConditionalOperator>(E)) {
3374         Visit(BCO->getCond());
3375         HandleValue(BCO->getFalseExpr(), AddressOf);
3376         return;
3377       }
3378 
3379       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3380         HandleValue(OVE->getSourceExpr(), AddressOf);
3381         return;
3382       }
3383 
3384       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3385         switch (BO->getOpcode()) {
3386         default:
3387           break;
3388         case(BO_PtrMemD):
3389         case(BO_PtrMemI):
3390           HandleValue(BO->getLHS(), AddressOf);
3391           Visit(BO->getRHS());
3392           return;
3393         case(BO_Comma):
3394           Visit(BO->getLHS());
3395           HandleValue(BO->getRHS(), AddressOf);
3396           return;
3397         }
3398       }
3399 
3400       Visit(E);
3401     }
3402 
3403     void CheckInitListExpr(InitListExpr *ILE) {
3404       InitFieldIndex.push_back(0);
3405       for (auto Child : ILE->children()) {
3406         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3407           CheckInitListExpr(SubList);
3408         } else {
3409           Visit(Child);
3410         }
3411         ++InitFieldIndex.back();
3412       }
3413       InitFieldIndex.pop_back();
3414     }
3415 
3416     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3417                           FieldDecl *Field, const Type *BaseClass) {
3418       // Remove Decls that may have been initialized in the previous
3419       // initializer.
3420       for (ValueDecl* VD : DeclsToRemove)
3421         Decls.erase(VD);
3422       DeclsToRemove.clear();
3423 
3424       Constructor = FieldConstructor;
3425       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3426 
3427       if (ILE && Field) {
3428         InitList = true;
3429         InitListFieldDecl = Field;
3430         InitFieldIndex.clear();
3431         CheckInitListExpr(ILE);
3432       } else {
3433         InitList = false;
3434         Visit(E);
3435       }
3436 
3437       if (Field)
3438         Decls.erase(Field);
3439       if (BaseClass)
3440         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3441     }
3442 
3443     void VisitMemberExpr(MemberExpr *ME) {
3444       // All uses of unbounded reference fields will warn.
3445       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3446     }
3447 
3448     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3449       if (E->getCastKind() == CK_LValueToRValue) {
3450         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3451         return;
3452       }
3453 
3454       Inherited::VisitImplicitCastExpr(E);
3455     }
3456 
3457     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3458       if (E->getConstructor()->isCopyConstructor()) {
3459         Expr *ArgExpr = E->getArg(0);
3460         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3461           if (ILE->getNumInits() == 1)
3462             ArgExpr = ILE->getInit(0);
3463         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3464           if (ICE->getCastKind() == CK_NoOp)
3465             ArgExpr = ICE->getSubExpr();
3466         HandleValue(ArgExpr, false /*AddressOf*/);
3467         return;
3468       }
3469       Inherited::VisitCXXConstructExpr(E);
3470     }
3471 
3472     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3473       Expr *Callee = E->getCallee();
3474       if (isa<MemberExpr>(Callee)) {
3475         HandleValue(Callee, false /*AddressOf*/);
3476         for (auto Arg : E->arguments())
3477           Visit(Arg);
3478         return;
3479       }
3480 
3481       Inherited::VisitCXXMemberCallExpr(E);
3482     }
3483 
3484     void VisitCallExpr(CallExpr *E) {
3485       // Treat std::move as a use.
3486       if (E->isCallToStdMove()) {
3487         HandleValue(E->getArg(0), /*AddressOf=*/false);
3488         return;
3489       }
3490 
3491       Inherited::VisitCallExpr(E);
3492     }
3493 
3494     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3495       Expr *Callee = E->getCallee();
3496 
3497       if (isa<UnresolvedLookupExpr>(Callee))
3498         return Inherited::VisitCXXOperatorCallExpr(E);
3499 
3500       Visit(Callee);
3501       for (auto Arg : E->arguments())
3502         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3503     }
3504 
3505     void VisitBinaryOperator(BinaryOperator *E) {
3506       // If a field assignment is detected, remove the field from the
3507       // uninitiailized field set.
3508       if (E->getOpcode() == BO_Assign)
3509         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3510           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3511             if (!FD->getType()->isReferenceType())
3512               DeclsToRemove.push_back(FD);
3513 
3514       if (E->isCompoundAssignmentOp()) {
3515         HandleValue(E->getLHS(), false /*AddressOf*/);
3516         Visit(E->getRHS());
3517         return;
3518       }
3519 
3520       Inherited::VisitBinaryOperator(E);
3521     }
3522 
3523     void VisitUnaryOperator(UnaryOperator *E) {
3524       if (E->isIncrementDecrementOp()) {
3525         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3526         return;
3527       }
3528       if (E->getOpcode() == UO_AddrOf) {
3529         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3530           HandleValue(ME->getBase(), true /*AddressOf*/);
3531           return;
3532         }
3533       }
3534 
3535       Inherited::VisitUnaryOperator(E);
3536     }
3537   };
3538 
3539   // Diagnose value-uses of fields to initialize themselves, e.g.
3540   //   foo(foo)
3541   // where foo is not also a parameter to the constructor.
3542   // Also diagnose across field uninitialized use such as
3543   //   x(y), y(x)
3544   // TODO: implement -Wuninitialized and fold this into that framework.
3545   static void DiagnoseUninitializedFields(
3546       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3547 
3548     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3549                                            Constructor->getLocation())) {
3550       return;
3551     }
3552 
3553     if (Constructor->isInvalidDecl())
3554       return;
3555 
3556     const CXXRecordDecl *RD = Constructor->getParent();
3557 
3558     if (RD->getDescribedClassTemplate())
3559       return;
3560 
3561     // Holds fields that are uninitialized.
3562     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3563 
3564     // At the beginning, all fields are uninitialized.
3565     for (auto *I : RD->decls()) {
3566       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3567         UninitializedFields.insert(FD);
3568       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3569         UninitializedFields.insert(IFD->getAnonField());
3570       }
3571     }
3572 
3573     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3574     for (auto I : RD->bases())
3575       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3576 
3577     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3578       return;
3579 
3580     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3581                                                    UninitializedFields,
3582                                                    UninitializedBaseClasses);
3583 
3584     for (const auto *FieldInit : Constructor->inits()) {
3585       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3586         break;
3587 
3588       Expr *InitExpr = FieldInit->getInit();
3589       if (!InitExpr)
3590         continue;
3591 
3592       if (CXXDefaultInitExpr *Default =
3593               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3594         InitExpr = Default->getExpr();
3595         if (!InitExpr)
3596           continue;
3597         // In class initializers will point to the constructor.
3598         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3599                                               FieldInit->getAnyMember(),
3600                                               FieldInit->getBaseClass());
3601       } else {
3602         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3603                                               FieldInit->getAnyMember(),
3604                                               FieldInit->getBaseClass());
3605       }
3606     }
3607   }
3608 } // namespace
3609 
3610 /// Enter a new C++ default initializer scope. After calling this, the
3611 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3612 /// parsing or instantiating the initializer failed.
3613 void Sema::ActOnStartCXXInClassMemberInitializer() {
3614   // Create a synthetic function scope to represent the call to the constructor
3615   // that notionally surrounds a use of this initializer.
3616   PushFunctionScope();
3617 }
3618 
3619 /// This is invoked after parsing an in-class initializer for a
3620 /// non-static C++ class member, and after instantiating an in-class initializer
3621 /// in a class template. Such actions are deferred until the class is complete.
3622 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3623                                                   SourceLocation InitLoc,
3624                                                   Expr *InitExpr) {
3625   // Pop the notional constructor scope we created earlier.
3626   PopFunctionScopeInfo(nullptr, D);
3627 
3628   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3629   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3630          "must set init style when field is created");
3631 
3632   if (!InitExpr) {
3633     D->setInvalidDecl();
3634     if (FD)
3635       FD->removeInClassInitializer();
3636     return;
3637   }
3638 
3639   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3640     FD->setInvalidDecl();
3641     FD->removeInClassInitializer();
3642     return;
3643   }
3644 
3645   ExprResult Init = InitExpr;
3646   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3647     InitializedEntity Entity =
3648         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3649     InitializationKind Kind =
3650         FD->getInClassInitStyle() == ICIS_ListInit
3651             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3652                                                    InitExpr->getBeginLoc(),
3653                                                    InitExpr->getEndLoc())
3654             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3655     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3656     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3657     if (Init.isInvalid()) {
3658       FD->setInvalidDecl();
3659       return;
3660     }
3661   }
3662 
3663   // C++11 [class.base.init]p7:
3664   //   The initialization of each base and member constitutes a
3665   //   full-expression.
3666   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3667   if (Init.isInvalid()) {
3668     FD->setInvalidDecl();
3669     return;
3670   }
3671 
3672   InitExpr = Init.get();
3673 
3674   FD->setInClassInitializer(InitExpr);
3675 }
3676 
3677 /// Find the direct and/or virtual base specifiers that
3678 /// correspond to the given base type, for use in base initialization
3679 /// within a constructor.
3680 static bool FindBaseInitializer(Sema &SemaRef,
3681                                 CXXRecordDecl *ClassDecl,
3682                                 QualType BaseType,
3683                                 const CXXBaseSpecifier *&DirectBaseSpec,
3684                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3685   // First, check for a direct base class.
3686   DirectBaseSpec = nullptr;
3687   for (const auto &Base : ClassDecl->bases()) {
3688     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3689       // We found a direct base of this type. That's what we're
3690       // initializing.
3691       DirectBaseSpec = &Base;
3692       break;
3693     }
3694   }
3695 
3696   // Check for a virtual base class.
3697   // FIXME: We might be able to short-circuit this if we know in advance that
3698   // there are no virtual bases.
3699   VirtualBaseSpec = nullptr;
3700   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3701     // We haven't found a base yet; search the class hierarchy for a
3702     // virtual base class.
3703     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3704                        /*DetectVirtual=*/false);
3705     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3706                               SemaRef.Context.getTypeDeclType(ClassDecl),
3707                               BaseType, Paths)) {
3708       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3709            Path != Paths.end(); ++Path) {
3710         if (Path->back().Base->isVirtual()) {
3711           VirtualBaseSpec = Path->back().Base;
3712           break;
3713         }
3714       }
3715     }
3716   }
3717 
3718   return DirectBaseSpec || VirtualBaseSpec;
3719 }
3720 
3721 /// Handle a C++ member initializer using braced-init-list syntax.
3722 MemInitResult
3723 Sema::ActOnMemInitializer(Decl *ConstructorD,
3724                           Scope *S,
3725                           CXXScopeSpec &SS,
3726                           IdentifierInfo *MemberOrBase,
3727                           ParsedType TemplateTypeTy,
3728                           const DeclSpec &DS,
3729                           SourceLocation IdLoc,
3730                           Expr *InitList,
3731                           SourceLocation EllipsisLoc) {
3732   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3733                              DS, IdLoc, InitList,
3734                              EllipsisLoc);
3735 }
3736 
3737 /// Handle a C++ member initializer using parentheses syntax.
3738 MemInitResult
3739 Sema::ActOnMemInitializer(Decl *ConstructorD,
3740                           Scope *S,
3741                           CXXScopeSpec &SS,
3742                           IdentifierInfo *MemberOrBase,
3743                           ParsedType TemplateTypeTy,
3744                           const DeclSpec &DS,
3745                           SourceLocation IdLoc,
3746                           SourceLocation LParenLoc,
3747                           ArrayRef<Expr *> Args,
3748                           SourceLocation RParenLoc,
3749                           SourceLocation EllipsisLoc) {
3750   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3751                                            Args, RParenLoc);
3752   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3753                              DS, IdLoc, List, EllipsisLoc);
3754 }
3755 
3756 namespace {
3757 
3758 // Callback to only accept typo corrections that can be a valid C++ member
3759 // intializer: either a non-static field member or a base class.
3760 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3761 public:
3762   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3763       : ClassDecl(ClassDecl) {}
3764 
3765   bool ValidateCandidate(const TypoCorrection &candidate) override {
3766     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3767       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3768         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3769       return isa<TypeDecl>(ND);
3770     }
3771     return false;
3772   }
3773 
3774 private:
3775   CXXRecordDecl *ClassDecl;
3776 };
3777 
3778 }
3779 
3780 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3781                                              CXXScopeSpec &SS,
3782                                              ParsedType TemplateTypeTy,
3783                                              IdentifierInfo *MemberOrBase) {
3784   if (SS.getScopeRep() || TemplateTypeTy)
3785     return nullptr;
3786   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3787   if (Result.empty())
3788     return nullptr;
3789   ValueDecl *Member;
3790   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3791       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3792     return Member;
3793   return nullptr;
3794 }
3795 
3796 /// Handle a C++ member initializer.
3797 MemInitResult
3798 Sema::BuildMemInitializer(Decl *ConstructorD,
3799                           Scope *S,
3800                           CXXScopeSpec &SS,
3801                           IdentifierInfo *MemberOrBase,
3802                           ParsedType TemplateTypeTy,
3803                           const DeclSpec &DS,
3804                           SourceLocation IdLoc,
3805                           Expr *Init,
3806                           SourceLocation EllipsisLoc) {
3807   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3808   if (!Res.isUsable())
3809     return true;
3810   Init = Res.get();
3811 
3812   if (!ConstructorD)
3813     return true;
3814 
3815   AdjustDeclIfTemplate(ConstructorD);
3816 
3817   CXXConstructorDecl *Constructor
3818     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3819   if (!Constructor) {
3820     // The user wrote a constructor initializer on a function that is
3821     // not a C++ constructor. Ignore the error for now, because we may
3822     // have more member initializers coming; we'll diagnose it just
3823     // once in ActOnMemInitializers.
3824     return true;
3825   }
3826 
3827   CXXRecordDecl *ClassDecl = Constructor->getParent();
3828 
3829   // C++ [class.base.init]p2:
3830   //   Names in a mem-initializer-id are looked up in the scope of the
3831   //   constructor's class and, if not found in that scope, are looked
3832   //   up in the scope containing the constructor's definition.
3833   //   [Note: if the constructor's class contains a member with the
3834   //   same name as a direct or virtual base class of the class, a
3835   //   mem-initializer-id naming the member or base class and composed
3836   //   of a single identifier refers to the class member. A
3837   //   mem-initializer-id for the hidden base class may be specified
3838   //   using a qualified name. ]
3839 
3840   // Look for a member, first.
3841   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3842           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3843     if (EllipsisLoc.isValid())
3844       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3845           << MemberOrBase
3846           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3847 
3848     return BuildMemberInitializer(Member, Init, IdLoc);
3849   }
3850   // It didn't name a member, so see if it names a class.
3851   QualType BaseType;
3852   TypeSourceInfo *TInfo = nullptr;
3853 
3854   if (TemplateTypeTy) {
3855     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3856   } else if (DS.getTypeSpecType() == TST_decltype) {
3857     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3858   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3859     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3860     return true;
3861   } else {
3862     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3863     LookupParsedName(R, S, &SS);
3864 
3865     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3866     if (!TyD) {
3867       if (R.isAmbiguous()) return true;
3868 
3869       // We don't want access-control diagnostics here.
3870       R.suppressDiagnostics();
3871 
3872       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3873         bool NotUnknownSpecialization = false;
3874         DeclContext *DC = computeDeclContext(SS, false);
3875         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3876           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3877 
3878         if (!NotUnknownSpecialization) {
3879           // When the scope specifier can refer to a member of an unknown
3880           // specialization, we take it as a type name.
3881           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3882                                        SS.getWithLocInContext(Context),
3883                                        *MemberOrBase, IdLoc);
3884           if (BaseType.isNull())
3885             return true;
3886 
3887           TInfo = Context.CreateTypeSourceInfo(BaseType);
3888           DependentNameTypeLoc TL =
3889               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3890           if (!TL.isNull()) {
3891             TL.setNameLoc(IdLoc);
3892             TL.setElaboratedKeywordLoc(SourceLocation());
3893             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3894           }
3895 
3896           R.clear();
3897           R.setLookupName(MemberOrBase);
3898         }
3899       }
3900 
3901       // If no results were found, try to correct typos.
3902       TypoCorrection Corr;
3903       if (R.empty() && BaseType.isNull() &&
3904           (Corr = CorrectTypo(
3905                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3906                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3907                CTK_ErrorRecovery, ClassDecl))) {
3908         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3909           // We have found a non-static data member with a similar
3910           // name to what was typed; complain and initialize that
3911           // member.
3912           diagnoseTypo(Corr,
3913                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3914                          << MemberOrBase << true);
3915           return BuildMemberInitializer(Member, Init, IdLoc);
3916         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3917           const CXXBaseSpecifier *DirectBaseSpec;
3918           const CXXBaseSpecifier *VirtualBaseSpec;
3919           if (FindBaseInitializer(*this, ClassDecl,
3920                                   Context.getTypeDeclType(Type),
3921                                   DirectBaseSpec, VirtualBaseSpec)) {
3922             // We have found a direct or virtual base class with a
3923             // similar name to what was typed; complain and initialize
3924             // that base class.
3925             diagnoseTypo(Corr,
3926                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3927                            << MemberOrBase << false,
3928                          PDiag() /*Suppress note, we provide our own.*/);
3929 
3930             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3931                                                               : VirtualBaseSpec;
3932             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3933                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3934 
3935             TyD = Type;
3936           }
3937         }
3938       }
3939 
3940       if (!TyD && BaseType.isNull()) {
3941         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3942           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3943         return true;
3944       }
3945     }
3946 
3947     if (BaseType.isNull()) {
3948       BaseType = Context.getTypeDeclType(TyD);
3949       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3950       if (SS.isSet()) {
3951         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3952                                              BaseType);
3953         TInfo = Context.CreateTypeSourceInfo(BaseType);
3954         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3955         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3956         TL.setElaboratedKeywordLoc(SourceLocation());
3957         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3958       }
3959     }
3960   }
3961 
3962   if (!TInfo)
3963     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3964 
3965   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3966 }
3967 
3968 MemInitResult
3969 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3970                              SourceLocation IdLoc) {
3971   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3972   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3973   assert((DirectMember || IndirectMember) &&
3974          "Member must be a FieldDecl or IndirectFieldDecl");
3975 
3976   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3977     return true;
3978 
3979   if (Member->isInvalidDecl())
3980     return true;
3981 
3982   MultiExprArg Args;
3983   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3984     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3985   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3986     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3987   } else {
3988     // Template instantiation doesn't reconstruct ParenListExprs for us.
3989     Args = Init;
3990   }
3991 
3992   SourceRange InitRange = Init->getSourceRange();
3993 
3994   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3995     // Can't check initialization for a member of dependent type or when
3996     // any of the arguments are type-dependent expressions.
3997     DiscardCleanupsInEvaluationContext();
3998   } else {
3999     bool InitList = false;
4000     if (isa<InitListExpr>(Init)) {
4001       InitList = true;
4002       Args = Init;
4003     }
4004 
4005     // Initialize the member.
4006     InitializedEntity MemberEntity =
4007       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4008                    : InitializedEntity::InitializeMember(IndirectMember,
4009                                                          nullptr);
4010     InitializationKind Kind =
4011         InitList ? InitializationKind::CreateDirectList(
4012                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4013                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4014                                                     InitRange.getEnd());
4015 
4016     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4017     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4018                                             nullptr);
4019     if (MemberInit.isInvalid())
4020       return true;
4021 
4022     // C++11 [class.base.init]p7:
4023     //   The initialization of each base and member constitutes a
4024     //   full-expression.
4025     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4026     if (MemberInit.isInvalid())
4027       return true;
4028 
4029     Init = MemberInit.get();
4030   }
4031 
4032   if (DirectMember) {
4033     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4034                                             InitRange.getBegin(), Init,
4035                                             InitRange.getEnd());
4036   } else {
4037     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4038                                             InitRange.getBegin(), Init,
4039                                             InitRange.getEnd());
4040   }
4041 }
4042 
4043 MemInitResult
4044 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4045                                  CXXRecordDecl *ClassDecl) {
4046   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4047   if (!LangOpts.CPlusPlus11)
4048     return Diag(NameLoc, diag::err_delegating_ctor)
4049       << TInfo->getTypeLoc().getLocalSourceRange();
4050   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4051 
4052   bool InitList = true;
4053   MultiExprArg Args = Init;
4054   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4055     InitList = false;
4056     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4057   }
4058 
4059   SourceRange InitRange = Init->getSourceRange();
4060   // Initialize the object.
4061   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4062                                      QualType(ClassDecl->getTypeForDecl(), 0));
4063   InitializationKind Kind =
4064       InitList ? InitializationKind::CreateDirectList(
4065                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4066                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4067                                                   InitRange.getEnd());
4068   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4069   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4070                                               Args, nullptr);
4071   if (DelegationInit.isInvalid())
4072     return true;
4073 
4074   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4075          "Delegating constructor with no target?");
4076 
4077   // C++11 [class.base.init]p7:
4078   //   The initialization of each base and member constitutes a
4079   //   full-expression.
4080   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4081                                        InitRange.getBegin());
4082   if (DelegationInit.isInvalid())
4083     return true;
4084 
4085   // If we are in a dependent context, template instantiation will
4086   // perform this type-checking again. Just save the arguments that we
4087   // received in a ParenListExpr.
4088   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4089   // of the information that we have about the base
4090   // initializer. However, deconstructing the ASTs is a dicey process,
4091   // and this approach is far more likely to get the corner cases right.
4092   if (CurContext->isDependentContext())
4093     DelegationInit = Init;
4094 
4095   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4096                                           DelegationInit.getAs<Expr>(),
4097                                           InitRange.getEnd());
4098 }
4099 
4100 MemInitResult
4101 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4102                            Expr *Init, CXXRecordDecl *ClassDecl,
4103                            SourceLocation EllipsisLoc) {
4104   SourceLocation BaseLoc
4105     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4106 
4107   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4108     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4109              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4110 
4111   // C++ [class.base.init]p2:
4112   //   [...] Unless the mem-initializer-id names a nonstatic data
4113   //   member of the constructor's class or a direct or virtual base
4114   //   of that class, the mem-initializer is ill-formed. A
4115   //   mem-initializer-list can initialize a base class using any
4116   //   name that denotes that base class type.
4117   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4118 
4119   SourceRange InitRange = Init->getSourceRange();
4120   if (EllipsisLoc.isValid()) {
4121     // This is a pack expansion.
4122     if (!BaseType->containsUnexpandedParameterPack())  {
4123       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4124         << SourceRange(BaseLoc, InitRange.getEnd());
4125 
4126       EllipsisLoc = SourceLocation();
4127     }
4128   } else {
4129     // Check for any unexpanded parameter packs.
4130     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4131       return true;
4132 
4133     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4134       return true;
4135   }
4136 
4137   // Check for direct and virtual base classes.
4138   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4139   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4140   if (!Dependent) {
4141     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4142                                        BaseType))
4143       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4144 
4145     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4146                         VirtualBaseSpec);
4147 
4148     // C++ [base.class.init]p2:
4149     // Unless the mem-initializer-id names a nonstatic data member of the
4150     // constructor's class or a direct or virtual base of that class, the
4151     // mem-initializer is ill-formed.
4152     if (!DirectBaseSpec && !VirtualBaseSpec) {
4153       // If the class has any dependent bases, then it's possible that
4154       // one of those types will resolve to the same type as
4155       // BaseType. Therefore, just treat this as a dependent base
4156       // class initialization.  FIXME: Should we try to check the
4157       // initialization anyway? It seems odd.
4158       if (ClassDecl->hasAnyDependentBases())
4159         Dependent = true;
4160       else
4161         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4162           << BaseType << Context.getTypeDeclType(ClassDecl)
4163           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4164     }
4165   }
4166 
4167   if (Dependent) {
4168     DiscardCleanupsInEvaluationContext();
4169 
4170     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4171                                             /*IsVirtual=*/false,
4172                                             InitRange.getBegin(), Init,
4173                                             InitRange.getEnd(), EllipsisLoc);
4174   }
4175 
4176   // C++ [base.class.init]p2:
4177   //   If a mem-initializer-id is ambiguous because it designates both
4178   //   a direct non-virtual base class and an inherited virtual base
4179   //   class, the mem-initializer is ill-formed.
4180   if (DirectBaseSpec && VirtualBaseSpec)
4181     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4182       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4183 
4184   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4185   if (!BaseSpec)
4186     BaseSpec = VirtualBaseSpec;
4187 
4188   // Initialize the base.
4189   bool InitList = true;
4190   MultiExprArg Args = Init;
4191   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4192     InitList = false;
4193     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4194   }
4195 
4196   InitializedEntity BaseEntity =
4197     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4198   InitializationKind Kind =
4199       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4200                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4201                                                   InitRange.getEnd());
4202   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4203   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4204   if (BaseInit.isInvalid())
4205     return true;
4206 
4207   // C++11 [class.base.init]p7:
4208   //   The initialization of each base and member constitutes a
4209   //   full-expression.
4210   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4211   if (BaseInit.isInvalid())
4212     return true;
4213 
4214   // If we are in a dependent context, template instantiation will
4215   // perform this type-checking again. Just save the arguments that we
4216   // received in a ParenListExpr.
4217   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4218   // of the information that we have about the base
4219   // initializer. However, deconstructing the ASTs is a dicey process,
4220   // and this approach is far more likely to get the corner cases right.
4221   if (CurContext->isDependentContext())
4222     BaseInit = Init;
4223 
4224   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4225                                           BaseSpec->isVirtual(),
4226                                           InitRange.getBegin(),
4227                                           BaseInit.getAs<Expr>(),
4228                                           InitRange.getEnd(), EllipsisLoc);
4229 }
4230 
4231 // Create a static_cast\<T&&>(expr).
4232 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4233   if (T.isNull()) T = E->getType();
4234   QualType TargetType = SemaRef.BuildReferenceType(
4235       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4236   SourceLocation ExprLoc = E->getBeginLoc();
4237   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4238       TargetType, ExprLoc);
4239 
4240   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4241                                    SourceRange(ExprLoc, ExprLoc),
4242                                    E->getSourceRange()).get();
4243 }
4244 
4245 /// ImplicitInitializerKind - How an implicit base or member initializer should
4246 /// initialize its base or member.
4247 enum ImplicitInitializerKind {
4248   IIK_Default,
4249   IIK_Copy,
4250   IIK_Move,
4251   IIK_Inherit
4252 };
4253 
4254 static bool
4255 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4256                              ImplicitInitializerKind ImplicitInitKind,
4257                              CXXBaseSpecifier *BaseSpec,
4258                              bool IsInheritedVirtualBase,
4259                              CXXCtorInitializer *&CXXBaseInit) {
4260   InitializedEntity InitEntity
4261     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4262                                         IsInheritedVirtualBase);
4263 
4264   ExprResult BaseInit;
4265 
4266   switch (ImplicitInitKind) {
4267   case IIK_Inherit:
4268   case IIK_Default: {
4269     InitializationKind InitKind
4270       = InitializationKind::CreateDefault(Constructor->getLocation());
4271     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4272     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4273     break;
4274   }
4275 
4276   case IIK_Move:
4277   case IIK_Copy: {
4278     bool Moving = ImplicitInitKind == IIK_Move;
4279     ParmVarDecl *Param = Constructor->getParamDecl(0);
4280     QualType ParamType = Param->getType().getNonReferenceType();
4281 
4282     Expr *CopyCtorArg =
4283       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4284                           SourceLocation(), Param, false,
4285                           Constructor->getLocation(), ParamType,
4286                           VK_LValue, nullptr);
4287 
4288     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4289 
4290     // Cast to the base class to avoid ambiguities.
4291     QualType ArgTy =
4292       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4293                                        ParamType.getQualifiers());
4294 
4295     if (Moving) {
4296       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4297     }
4298 
4299     CXXCastPath BasePath;
4300     BasePath.push_back(BaseSpec);
4301     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4302                                             CK_UncheckedDerivedToBase,
4303                                             Moving ? VK_XValue : VK_LValue,
4304                                             &BasePath).get();
4305 
4306     InitializationKind InitKind
4307       = InitializationKind::CreateDirect(Constructor->getLocation(),
4308                                          SourceLocation(), SourceLocation());
4309     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4310     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4311     break;
4312   }
4313   }
4314 
4315   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4316   if (BaseInit.isInvalid())
4317     return true;
4318 
4319   CXXBaseInit =
4320     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4321                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4322                                                         SourceLocation()),
4323                                              BaseSpec->isVirtual(),
4324                                              SourceLocation(),
4325                                              BaseInit.getAs<Expr>(),
4326                                              SourceLocation(),
4327                                              SourceLocation());
4328 
4329   return false;
4330 }
4331 
4332 static bool RefersToRValueRef(Expr *MemRef) {
4333   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4334   return Referenced->getType()->isRValueReferenceType();
4335 }
4336 
4337 static bool
4338 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4339                                ImplicitInitializerKind ImplicitInitKind,
4340                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4341                                CXXCtorInitializer *&CXXMemberInit) {
4342   if (Field->isInvalidDecl())
4343     return true;
4344 
4345   SourceLocation Loc = Constructor->getLocation();
4346 
4347   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4348     bool Moving = ImplicitInitKind == IIK_Move;
4349     ParmVarDecl *Param = Constructor->getParamDecl(0);
4350     QualType ParamType = Param->getType().getNonReferenceType();
4351 
4352     // Suppress copying zero-width bitfields.
4353     if (Field->isZeroLengthBitField(SemaRef.Context))
4354       return false;
4355 
4356     Expr *MemberExprBase =
4357       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4358                           SourceLocation(), Param, false,
4359                           Loc, ParamType, VK_LValue, nullptr);
4360 
4361     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4362 
4363     if (Moving) {
4364       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4365     }
4366 
4367     // Build a reference to this field within the parameter.
4368     CXXScopeSpec SS;
4369     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4370                               Sema::LookupMemberName);
4371     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4372                                   : cast<ValueDecl>(Field), AS_public);
4373     MemberLookup.resolveKind();
4374     ExprResult CtorArg
4375       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4376                                          ParamType, Loc,
4377                                          /*IsArrow=*/false,
4378                                          SS,
4379                                          /*TemplateKWLoc=*/SourceLocation(),
4380                                          /*FirstQualifierInScope=*/nullptr,
4381                                          MemberLookup,
4382                                          /*TemplateArgs=*/nullptr,
4383                                          /*S*/nullptr);
4384     if (CtorArg.isInvalid())
4385       return true;
4386 
4387     // C++11 [class.copy]p15:
4388     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4389     //     with static_cast<T&&>(x.m);
4390     if (RefersToRValueRef(CtorArg.get())) {
4391       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4392     }
4393 
4394     InitializedEntity Entity =
4395         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4396                                                        /*Implicit*/ true)
4397                  : InitializedEntity::InitializeMember(Field, nullptr,
4398                                                        /*Implicit*/ true);
4399 
4400     // Direct-initialize to use the copy constructor.
4401     InitializationKind InitKind =
4402       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4403 
4404     Expr *CtorArgE = CtorArg.getAs<Expr>();
4405     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4406     ExprResult MemberInit =
4407         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4408     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4409     if (MemberInit.isInvalid())
4410       return true;
4411 
4412     if (Indirect)
4413       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4414           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4415     else
4416       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4417           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4418     return false;
4419   }
4420 
4421   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4422          "Unhandled implicit init kind!");
4423 
4424   QualType FieldBaseElementType =
4425     SemaRef.Context.getBaseElementType(Field->getType());
4426 
4427   if (FieldBaseElementType->isRecordType()) {
4428     InitializedEntity InitEntity =
4429         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4430                                                        /*Implicit*/ true)
4431                  : InitializedEntity::InitializeMember(Field, nullptr,
4432                                                        /*Implicit*/ true);
4433     InitializationKind InitKind =
4434       InitializationKind::CreateDefault(Loc);
4435 
4436     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4437     ExprResult MemberInit =
4438       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4439 
4440     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4441     if (MemberInit.isInvalid())
4442       return true;
4443 
4444     if (Indirect)
4445       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4446                                                                Indirect, Loc,
4447                                                                Loc,
4448                                                                MemberInit.get(),
4449                                                                Loc);
4450     else
4451       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4452                                                                Field, Loc, Loc,
4453                                                                MemberInit.get(),
4454                                                                Loc);
4455     return false;
4456   }
4457 
4458   if (!Field->getParent()->isUnion()) {
4459     if (FieldBaseElementType->isReferenceType()) {
4460       SemaRef.Diag(Constructor->getLocation(),
4461                    diag::err_uninitialized_member_in_ctor)
4462       << (int)Constructor->isImplicit()
4463       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4464       << 0 << Field->getDeclName();
4465       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4466       return true;
4467     }
4468 
4469     if (FieldBaseElementType.isConstQualified()) {
4470       SemaRef.Diag(Constructor->getLocation(),
4471                    diag::err_uninitialized_member_in_ctor)
4472       << (int)Constructor->isImplicit()
4473       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4474       << 1 << Field->getDeclName();
4475       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4476       return true;
4477     }
4478   }
4479 
4480   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4481     // ARC and Weak:
4482     //   Default-initialize Objective-C pointers to NULL.
4483     CXXMemberInit
4484       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4485                                                  Loc, Loc,
4486                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4487                                                  Loc);
4488     return false;
4489   }
4490 
4491   // Nothing to initialize.
4492   CXXMemberInit = nullptr;
4493   return false;
4494 }
4495 
4496 namespace {
4497 struct BaseAndFieldInfo {
4498   Sema &S;
4499   CXXConstructorDecl *Ctor;
4500   bool AnyErrorsInInits;
4501   ImplicitInitializerKind IIK;
4502   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4503   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4504   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4505 
4506   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4507     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4508     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4509     if (Ctor->getInheritedConstructor())
4510       IIK = IIK_Inherit;
4511     else if (Generated && Ctor->isCopyConstructor())
4512       IIK = IIK_Copy;
4513     else if (Generated && Ctor->isMoveConstructor())
4514       IIK = IIK_Move;
4515     else
4516       IIK = IIK_Default;
4517   }
4518 
4519   bool isImplicitCopyOrMove() const {
4520     switch (IIK) {
4521     case IIK_Copy:
4522     case IIK_Move:
4523       return true;
4524 
4525     case IIK_Default:
4526     case IIK_Inherit:
4527       return false;
4528     }
4529 
4530     llvm_unreachable("Invalid ImplicitInitializerKind!");
4531   }
4532 
4533   bool addFieldInitializer(CXXCtorInitializer *Init) {
4534     AllToInit.push_back(Init);
4535 
4536     // Check whether this initializer makes the field "used".
4537     if (Init->getInit()->HasSideEffects(S.Context))
4538       S.UnusedPrivateFields.remove(Init->getAnyMember());
4539 
4540     return false;
4541   }
4542 
4543   bool isInactiveUnionMember(FieldDecl *Field) {
4544     RecordDecl *Record = Field->getParent();
4545     if (!Record->isUnion())
4546       return false;
4547 
4548     if (FieldDecl *Active =
4549             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4550       return Active != Field->getCanonicalDecl();
4551 
4552     // In an implicit copy or move constructor, ignore any in-class initializer.
4553     if (isImplicitCopyOrMove())
4554       return true;
4555 
4556     // If there's no explicit initialization, the field is active only if it
4557     // has an in-class initializer...
4558     if (Field->hasInClassInitializer())
4559       return false;
4560     // ... or it's an anonymous struct or union whose class has an in-class
4561     // initializer.
4562     if (!Field->isAnonymousStructOrUnion())
4563       return true;
4564     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4565     return !FieldRD->hasInClassInitializer();
4566   }
4567 
4568   /// Determine whether the given field is, or is within, a union member
4569   /// that is inactive (because there was an initializer given for a different
4570   /// member of the union, or because the union was not initialized at all).
4571   bool isWithinInactiveUnionMember(FieldDecl *Field,
4572                                    IndirectFieldDecl *Indirect) {
4573     if (!Indirect)
4574       return isInactiveUnionMember(Field);
4575 
4576     for (auto *C : Indirect->chain()) {
4577       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4578       if (Field && isInactiveUnionMember(Field))
4579         return true;
4580     }
4581     return false;
4582   }
4583 };
4584 }
4585 
4586 /// Determine whether the given type is an incomplete or zero-lenfgth
4587 /// array type.
4588 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4589   if (T->isIncompleteArrayType())
4590     return true;
4591 
4592   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4593     if (!ArrayT->getSize())
4594       return true;
4595 
4596     T = ArrayT->getElementType();
4597   }
4598 
4599   return false;
4600 }
4601 
4602 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4603                                     FieldDecl *Field,
4604                                     IndirectFieldDecl *Indirect = nullptr) {
4605   if (Field->isInvalidDecl())
4606     return false;
4607 
4608   // Overwhelmingly common case: we have a direct initializer for this field.
4609   if (CXXCtorInitializer *Init =
4610           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4611     return Info.addFieldInitializer(Init);
4612 
4613   // C++11 [class.base.init]p8:
4614   //   if the entity is a non-static data member that has a
4615   //   brace-or-equal-initializer and either
4616   //   -- the constructor's class is a union and no other variant member of that
4617   //      union is designated by a mem-initializer-id or
4618   //   -- the constructor's class is not a union, and, if the entity is a member
4619   //      of an anonymous union, no other member of that union is designated by
4620   //      a mem-initializer-id,
4621   //   the entity is initialized as specified in [dcl.init].
4622   //
4623   // We also apply the same rules to handle anonymous structs within anonymous
4624   // unions.
4625   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4626     return false;
4627 
4628   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4629     ExprResult DIE =
4630         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4631     if (DIE.isInvalid())
4632       return true;
4633 
4634     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4635     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4636 
4637     CXXCtorInitializer *Init;
4638     if (Indirect)
4639       Init = new (SemaRef.Context)
4640           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4641                              SourceLocation(), DIE.get(), SourceLocation());
4642     else
4643       Init = new (SemaRef.Context)
4644           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4645                              SourceLocation(), DIE.get(), SourceLocation());
4646     return Info.addFieldInitializer(Init);
4647   }
4648 
4649   // Don't initialize incomplete or zero-length arrays.
4650   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4651     return false;
4652 
4653   // Don't try to build an implicit initializer if there were semantic
4654   // errors in any of the initializers (and therefore we might be
4655   // missing some that the user actually wrote).
4656   if (Info.AnyErrorsInInits)
4657     return false;
4658 
4659   CXXCtorInitializer *Init = nullptr;
4660   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4661                                      Indirect, Init))
4662     return true;
4663 
4664   if (!Init)
4665     return false;
4666 
4667   return Info.addFieldInitializer(Init);
4668 }
4669 
4670 bool
4671 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4672                                CXXCtorInitializer *Initializer) {
4673   assert(Initializer->isDelegatingInitializer());
4674   Constructor->setNumCtorInitializers(1);
4675   CXXCtorInitializer **initializer =
4676     new (Context) CXXCtorInitializer*[1];
4677   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4678   Constructor->setCtorInitializers(initializer);
4679 
4680   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4681     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4682     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4683   }
4684 
4685   DelegatingCtorDecls.push_back(Constructor);
4686 
4687   DiagnoseUninitializedFields(*this, Constructor);
4688 
4689   return false;
4690 }
4691 
4692 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4693                                ArrayRef<CXXCtorInitializer *> Initializers) {
4694   if (Constructor->isDependentContext()) {
4695     // Just store the initializers as written, they will be checked during
4696     // instantiation.
4697     if (!Initializers.empty()) {
4698       Constructor->setNumCtorInitializers(Initializers.size());
4699       CXXCtorInitializer **baseOrMemberInitializers =
4700         new (Context) CXXCtorInitializer*[Initializers.size()];
4701       memcpy(baseOrMemberInitializers, Initializers.data(),
4702              Initializers.size() * sizeof(CXXCtorInitializer*));
4703       Constructor->setCtorInitializers(baseOrMemberInitializers);
4704     }
4705 
4706     // Let template instantiation know whether we had errors.
4707     if (AnyErrors)
4708       Constructor->setInvalidDecl();
4709 
4710     return false;
4711   }
4712 
4713   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4714 
4715   // We need to build the initializer AST according to order of construction
4716   // and not what user specified in the Initializers list.
4717   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4718   if (!ClassDecl)
4719     return true;
4720 
4721   bool HadError = false;
4722 
4723   for (unsigned i = 0; i < Initializers.size(); i++) {
4724     CXXCtorInitializer *Member = Initializers[i];
4725 
4726     if (Member->isBaseInitializer())
4727       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4728     else {
4729       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4730 
4731       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4732         for (auto *C : F->chain()) {
4733           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4734           if (FD && FD->getParent()->isUnion())
4735             Info.ActiveUnionMember.insert(std::make_pair(
4736                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4737         }
4738       } else if (FieldDecl *FD = Member->getMember()) {
4739         if (FD->getParent()->isUnion())
4740           Info.ActiveUnionMember.insert(std::make_pair(
4741               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4742       }
4743     }
4744   }
4745 
4746   // Keep track of the direct virtual bases.
4747   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4748   for (auto &I : ClassDecl->bases()) {
4749     if (I.isVirtual())
4750       DirectVBases.insert(&I);
4751   }
4752 
4753   // Push virtual bases before others.
4754   for (auto &VBase : ClassDecl->vbases()) {
4755     if (CXXCtorInitializer *Value
4756         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4757       // [class.base.init]p7, per DR257:
4758       //   A mem-initializer where the mem-initializer-id names a virtual base
4759       //   class is ignored during execution of a constructor of any class that
4760       //   is not the most derived class.
4761       if (ClassDecl->isAbstract()) {
4762         // FIXME: Provide a fixit to remove the base specifier. This requires
4763         // tracking the location of the associated comma for a base specifier.
4764         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4765           << VBase.getType() << ClassDecl;
4766         DiagnoseAbstractType(ClassDecl);
4767       }
4768 
4769       Info.AllToInit.push_back(Value);
4770     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4771       // [class.base.init]p8, per DR257:
4772       //   If a given [...] base class is not named by a mem-initializer-id
4773       //   [...] and the entity is not a virtual base class of an abstract
4774       //   class, then [...] the entity is default-initialized.
4775       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4776       CXXCtorInitializer *CXXBaseInit;
4777       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4778                                        &VBase, IsInheritedVirtualBase,
4779                                        CXXBaseInit)) {
4780         HadError = true;
4781         continue;
4782       }
4783 
4784       Info.AllToInit.push_back(CXXBaseInit);
4785     }
4786   }
4787 
4788   // Non-virtual bases.
4789   for (auto &Base : ClassDecl->bases()) {
4790     // Virtuals are in the virtual base list and already constructed.
4791     if (Base.isVirtual())
4792       continue;
4793 
4794     if (CXXCtorInitializer *Value
4795           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4796       Info.AllToInit.push_back(Value);
4797     } else if (!AnyErrors) {
4798       CXXCtorInitializer *CXXBaseInit;
4799       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4800                                        &Base, /*IsInheritedVirtualBase=*/false,
4801                                        CXXBaseInit)) {
4802         HadError = true;
4803         continue;
4804       }
4805 
4806       Info.AllToInit.push_back(CXXBaseInit);
4807     }
4808   }
4809 
4810   // Fields.
4811   for (auto *Mem : ClassDecl->decls()) {
4812     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4813       // C++ [class.bit]p2:
4814       //   A declaration for a bit-field that omits the identifier declares an
4815       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4816       //   initialized.
4817       if (F->isUnnamedBitfield())
4818         continue;
4819 
4820       // If we're not generating the implicit copy/move constructor, then we'll
4821       // handle anonymous struct/union fields based on their individual
4822       // indirect fields.
4823       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4824         continue;
4825 
4826       if (CollectFieldInitializer(*this, Info, F))
4827         HadError = true;
4828       continue;
4829     }
4830 
4831     // Beyond this point, we only consider default initialization.
4832     if (Info.isImplicitCopyOrMove())
4833       continue;
4834 
4835     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4836       if (F->getType()->isIncompleteArrayType()) {
4837         assert(ClassDecl->hasFlexibleArrayMember() &&
4838                "Incomplete array type is not valid");
4839         continue;
4840       }
4841 
4842       // Initialize each field of an anonymous struct individually.
4843       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4844         HadError = true;
4845 
4846       continue;
4847     }
4848   }
4849 
4850   unsigned NumInitializers = Info.AllToInit.size();
4851   if (NumInitializers > 0) {
4852     Constructor->setNumCtorInitializers(NumInitializers);
4853     CXXCtorInitializer **baseOrMemberInitializers =
4854       new (Context) CXXCtorInitializer*[NumInitializers];
4855     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4856            NumInitializers * sizeof(CXXCtorInitializer*));
4857     Constructor->setCtorInitializers(baseOrMemberInitializers);
4858 
4859     // Constructors implicitly reference the base and member
4860     // destructors.
4861     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4862                                            Constructor->getParent());
4863   }
4864 
4865   return HadError;
4866 }
4867 
4868 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4869   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4870     const RecordDecl *RD = RT->getDecl();
4871     if (RD->isAnonymousStructOrUnion()) {
4872       for (auto *Field : RD->fields())
4873         PopulateKeysForFields(Field, IdealInits);
4874       return;
4875     }
4876   }
4877   IdealInits.push_back(Field->getCanonicalDecl());
4878 }
4879 
4880 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4881   return Context.getCanonicalType(BaseType).getTypePtr();
4882 }
4883 
4884 static const void *GetKeyForMember(ASTContext &Context,
4885                                    CXXCtorInitializer *Member) {
4886   if (!Member->isAnyMemberInitializer())
4887     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4888 
4889   return Member->getAnyMember()->getCanonicalDecl();
4890 }
4891 
4892 static void DiagnoseBaseOrMemInitializerOrder(
4893     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4894     ArrayRef<CXXCtorInitializer *> Inits) {
4895   if (Constructor->getDeclContext()->isDependentContext())
4896     return;
4897 
4898   // Don't check initializers order unless the warning is enabled at the
4899   // location of at least one initializer.
4900   bool ShouldCheckOrder = false;
4901   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4902     CXXCtorInitializer *Init = Inits[InitIndex];
4903     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4904                                  Init->getSourceLocation())) {
4905       ShouldCheckOrder = true;
4906       break;
4907     }
4908   }
4909   if (!ShouldCheckOrder)
4910     return;
4911 
4912   // Build the list of bases and members in the order that they'll
4913   // actually be initialized.  The explicit initializers should be in
4914   // this same order but may be missing things.
4915   SmallVector<const void*, 32> IdealInitKeys;
4916 
4917   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4918 
4919   // 1. Virtual bases.
4920   for (const auto &VBase : ClassDecl->vbases())
4921     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4922 
4923   // 2. Non-virtual bases.
4924   for (const auto &Base : ClassDecl->bases()) {
4925     if (Base.isVirtual())
4926       continue;
4927     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4928   }
4929 
4930   // 3. Direct fields.
4931   for (auto *Field : ClassDecl->fields()) {
4932     if (Field->isUnnamedBitfield())
4933       continue;
4934 
4935     PopulateKeysForFields(Field, IdealInitKeys);
4936   }
4937 
4938   unsigned NumIdealInits = IdealInitKeys.size();
4939   unsigned IdealIndex = 0;
4940 
4941   CXXCtorInitializer *PrevInit = nullptr;
4942   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4943     CXXCtorInitializer *Init = Inits[InitIndex];
4944     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4945 
4946     // Scan forward to try to find this initializer in the idealized
4947     // initializers list.
4948     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4949       if (InitKey == IdealInitKeys[IdealIndex])
4950         break;
4951 
4952     // If we didn't find this initializer, it must be because we
4953     // scanned past it on a previous iteration.  That can only
4954     // happen if we're out of order;  emit a warning.
4955     if (IdealIndex == NumIdealInits && PrevInit) {
4956       Sema::SemaDiagnosticBuilder D =
4957         SemaRef.Diag(PrevInit->getSourceLocation(),
4958                      diag::warn_initializer_out_of_order);
4959 
4960       if (PrevInit->isAnyMemberInitializer())
4961         D << 0 << PrevInit->getAnyMember()->getDeclName();
4962       else
4963         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4964 
4965       if (Init->isAnyMemberInitializer())
4966         D << 0 << Init->getAnyMember()->getDeclName();
4967       else
4968         D << 1 << Init->getTypeSourceInfo()->getType();
4969 
4970       // Move back to the initializer's location in the ideal list.
4971       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4972         if (InitKey == IdealInitKeys[IdealIndex])
4973           break;
4974 
4975       assert(IdealIndex < NumIdealInits &&
4976              "initializer not found in initializer list");
4977     }
4978 
4979     PrevInit = Init;
4980   }
4981 }
4982 
4983 namespace {
4984 bool CheckRedundantInit(Sema &S,
4985                         CXXCtorInitializer *Init,
4986                         CXXCtorInitializer *&PrevInit) {
4987   if (!PrevInit) {
4988     PrevInit = Init;
4989     return false;
4990   }
4991 
4992   if (FieldDecl *Field = Init->getAnyMember())
4993     S.Diag(Init->getSourceLocation(),
4994            diag::err_multiple_mem_initialization)
4995       << Field->getDeclName()
4996       << Init->getSourceRange();
4997   else {
4998     const Type *BaseClass = Init->getBaseClass();
4999     assert(BaseClass && "neither field nor base");
5000     S.Diag(Init->getSourceLocation(),
5001            diag::err_multiple_base_initialization)
5002       << QualType(BaseClass, 0)
5003       << Init->getSourceRange();
5004   }
5005   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5006     << 0 << PrevInit->getSourceRange();
5007 
5008   return true;
5009 }
5010 
5011 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5012 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5013 
5014 bool CheckRedundantUnionInit(Sema &S,
5015                              CXXCtorInitializer *Init,
5016                              RedundantUnionMap &Unions) {
5017   FieldDecl *Field = Init->getAnyMember();
5018   RecordDecl *Parent = Field->getParent();
5019   NamedDecl *Child = Field;
5020 
5021   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5022     if (Parent->isUnion()) {
5023       UnionEntry &En = Unions[Parent];
5024       if (En.first && En.first != Child) {
5025         S.Diag(Init->getSourceLocation(),
5026                diag::err_multiple_mem_union_initialization)
5027           << Field->getDeclName()
5028           << Init->getSourceRange();
5029         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5030           << 0 << En.second->getSourceRange();
5031         return true;
5032       }
5033       if (!En.first) {
5034         En.first = Child;
5035         En.second = Init;
5036       }
5037       if (!Parent->isAnonymousStructOrUnion())
5038         return false;
5039     }
5040 
5041     Child = Parent;
5042     Parent = cast<RecordDecl>(Parent->getDeclContext());
5043   }
5044 
5045   return false;
5046 }
5047 }
5048 
5049 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5050 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5051                                 SourceLocation ColonLoc,
5052                                 ArrayRef<CXXCtorInitializer*> MemInits,
5053                                 bool AnyErrors) {
5054   if (!ConstructorDecl)
5055     return;
5056 
5057   AdjustDeclIfTemplate(ConstructorDecl);
5058 
5059   CXXConstructorDecl *Constructor
5060     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5061 
5062   if (!Constructor) {
5063     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5064     return;
5065   }
5066 
5067   // Mapping for the duplicate initializers check.
5068   // For member initializers, this is keyed with a FieldDecl*.
5069   // For base initializers, this is keyed with a Type*.
5070   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5071 
5072   // Mapping for the inconsistent anonymous-union initializers check.
5073   RedundantUnionMap MemberUnions;
5074 
5075   bool HadError = false;
5076   for (unsigned i = 0; i < MemInits.size(); i++) {
5077     CXXCtorInitializer *Init = MemInits[i];
5078 
5079     // Set the source order index.
5080     Init->setSourceOrder(i);
5081 
5082     if (Init->isAnyMemberInitializer()) {
5083       const void *Key = GetKeyForMember(Context, Init);
5084       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5085           CheckRedundantUnionInit(*this, Init, MemberUnions))
5086         HadError = true;
5087     } else if (Init->isBaseInitializer()) {
5088       const void *Key = GetKeyForMember(Context, Init);
5089       if (CheckRedundantInit(*this, Init, Members[Key]))
5090         HadError = true;
5091     } else {
5092       assert(Init->isDelegatingInitializer());
5093       // This must be the only initializer
5094       if (MemInits.size() != 1) {
5095         Diag(Init->getSourceLocation(),
5096              diag::err_delegating_initializer_alone)
5097           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5098         // We will treat this as being the only initializer.
5099       }
5100       SetDelegatingInitializer(Constructor, MemInits[i]);
5101       // Return immediately as the initializer is set.
5102       return;
5103     }
5104   }
5105 
5106   if (HadError)
5107     return;
5108 
5109   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5110 
5111   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5112 
5113   DiagnoseUninitializedFields(*this, Constructor);
5114 }
5115 
5116 void
5117 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5118                                              CXXRecordDecl *ClassDecl) {
5119   // Ignore dependent contexts. Also ignore unions, since their members never
5120   // have destructors implicitly called.
5121   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5122     return;
5123 
5124   // FIXME: all the access-control diagnostics are positioned on the
5125   // field/base declaration.  That's probably good; that said, the
5126   // user might reasonably want to know why the destructor is being
5127   // emitted, and we currently don't say.
5128 
5129   // Non-static data members.
5130   for (auto *Field : ClassDecl->fields()) {
5131     if (Field->isInvalidDecl())
5132       continue;
5133 
5134     // Don't destroy incomplete or zero-length arrays.
5135     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5136       continue;
5137 
5138     QualType FieldType = Context.getBaseElementType(Field->getType());
5139 
5140     const RecordType* RT = FieldType->getAs<RecordType>();
5141     if (!RT)
5142       continue;
5143 
5144     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5145     if (FieldClassDecl->isInvalidDecl())
5146       continue;
5147     if (FieldClassDecl->hasIrrelevantDestructor())
5148       continue;
5149     // The destructor for an implicit anonymous union member is never invoked.
5150     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5151       continue;
5152 
5153     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5154     assert(Dtor && "No dtor found for FieldClassDecl!");
5155     CheckDestructorAccess(Field->getLocation(), Dtor,
5156                           PDiag(diag::err_access_dtor_field)
5157                             << Field->getDeclName()
5158                             << FieldType);
5159 
5160     MarkFunctionReferenced(Location, Dtor);
5161     DiagnoseUseOfDecl(Dtor, Location);
5162   }
5163 
5164   // We only potentially invoke the destructors of potentially constructed
5165   // subobjects.
5166   bool VisitVirtualBases = !ClassDecl->isAbstract();
5167 
5168   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5169 
5170   // Bases.
5171   for (const auto &Base : ClassDecl->bases()) {
5172     // Bases are always records in a well-formed non-dependent class.
5173     const RecordType *RT = Base.getType()->getAs<RecordType>();
5174 
5175     // Remember direct virtual bases.
5176     if (Base.isVirtual()) {
5177       if (!VisitVirtualBases)
5178         continue;
5179       DirectVirtualBases.insert(RT);
5180     }
5181 
5182     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5183     // If our base class is invalid, we probably can't get its dtor anyway.
5184     if (BaseClassDecl->isInvalidDecl())
5185       continue;
5186     if (BaseClassDecl->hasIrrelevantDestructor())
5187       continue;
5188 
5189     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5190     assert(Dtor && "No dtor found for BaseClassDecl!");
5191 
5192     // FIXME: caret should be on the start of the class name
5193     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5194                           PDiag(diag::err_access_dtor_base)
5195                               << Base.getType() << Base.getSourceRange(),
5196                           Context.getTypeDeclType(ClassDecl));
5197 
5198     MarkFunctionReferenced(Location, Dtor);
5199     DiagnoseUseOfDecl(Dtor, Location);
5200   }
5201 
5202   if (!VisitVirtualBases)
5203     return;
5204 
5205   // Virtual bases.
5206   for (const auto &VBase : ClassDecl->vbases()) {
5207     // Bases are always records in a well-formed non-dependent class.
5208     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5209 
5210     // Ignore direct virtual bases.
5211     if (DirectVirtualBases.count(RT))
5212       continue;
5213 
5214     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5215     // If our base class is invalid, we probably can't get its dtor anyway.
5216     if (BaseClassDecl->isInvalidDecl())
5217       continue;
5218     if (BaseClassDecl->hasIrrelevantDestructor())
5219       continue;
5220 
5221     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5222     assert(Dtor && "No dtor found for BaseClassDecl!");
5223     if (CheckDestructorAccess(
5224             ClassDecl->getLocation(), Dtor,
5225             PDiag(diag::err_access_dtor_vbase)
5226                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5227             Context.getTypeDeclType(ClassDecl)) ==
5228         AR_accessible) {
5229       CheckDerivedToBaseConversion(
5230           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5231           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5232           SourceRange(), DeclarationName(), nullptr);
5233     }
5234 
5235     MarkFunctionReferenced(Location, Dtor);
5236     DiagnoseUseOfDecl(Dtor, Location);
5237   }
5238 }
5239 
5240 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5241   if (!CDtorDecl)
5242     return;
5243 
5244   if (CXXConstructorDecl *Constructor
5245       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5246     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5247     DiagnoseUninitializedFields(*this, Constructor);
5248   }
5249 }
5250 
5251 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5252   if (!getLangOpts().CPlusPlus)
5253     return false;
5254 
5255   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5256   if (!RD)
5257     return false;
5258 
5259   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5260   // class template specialization here, but doing so breaks a lot of code.
5261 
5262   // We can't answer whether something is abstract until it has a
5263   // definition. If it's currently being defined, we'll walk back
5264   // over all the declarations when we have a full definition.
5265   const CXXRecordDecl *Def = RD->getDefinition();
5266   if (!Def || Def->isBeingDefined())
5267     return false;
5268 
5269   return RD->isAbstract();
5270 }
5271 
5272 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5273                                   TypeDiagnoser &Diagnoser) {
5274   if (!isAbstractType(Loc, T))
5275     return false;
5276 
5277   T = Context.getBaseElementType(T);
5278   Diagnoser.diagnose(*this, Loc, T);
5279   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5280   return true;
5281 }
5282 
5283 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5284   // Check if we've already emitted the list of pure virtual functions
5285   // for this class.
5286   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5287     return;
5288 
5289   // If the diagnostic is suppressed, don't emit the notes. We're only
5290   // going to emit them once, so try to attach them to a diagnostic we're
5291   // actually going to show.
5292   if (Diags.isLastDiagnosticIgnored())
5293     return;
5294 
5295   CXXFinalOverriderMap FinalOverriders;
5296   RD->getFinalOverriders(FinalOverriders);
5297 
5298   // Keep a set of seen pure methods so we won't diagnose the same method
5299   // more than once.
5300   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5301 
5302   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5303                                    MEnd = FinalOverriders.end();
5304        M != MEnd;
5305        ++M) {
5306     for (OverridingMethods::iterator SO = M->second.begin(),
5307                                   SOEnd = M->second.end();
5308          SO != SOEnd; ++SO) {
5309       // C++ [class.abstract]p4:
5310       //   A class is abstract if it contains or inherits at least one
5311       //   pure virtual function for which the final overrider is pure
5312       //   virtual.
5313 
5314       //
5315       if (SO->second.size() != 1)
5316         continue;
5317 
5318       if (!SO->second.front().Method->isPure())
5319         continue;
5320 
5321       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5322         continue;
5323 
5324       Diag(SO->second.front().Method->getLocation(),
5325            diag::note_pure_virtual_function)
5326         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5327     }
5328   }
5329 
5330   if (!PureVirtualClassDiagSet)
5331     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5332   PureVirtualClassDiagSet->insert(RD);
5333 }
5334 
5335 namespace {
5336 struct AbstractUsageInfo {
5337   Sema &S;
5338   CXXRecordDecl *Record;
5339   CanQualType AbstractType;
5340   bool Invalid;
5341 
5342   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5343     : S(S), Record(Record),
5344       AbstractType(S.Context.getCanonicalType(
5345                    S.Context.getTypeDeclType(Record))),
5346       Invalid(false) {}
5347 
5348   void DiagnoseAbstractType() {
5349     if (Invalid) return;
5350     S.DiagnoseAbstractType(Record);
5351     Invalid = true;
5352   }
5353 
5354   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5355 };
5356 
5357 struct CheckAbstractUsage {
5358   AbstractUsageInfo &Info;
5359   const NamedDecl *Ctx;
5360 
5361   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5362     : Info(Info), Ctx(Ctx) {}
5363 
5364   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5365     switch (TL.getTypeLocClass()) {
5366 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5367 #define TYPELOC(CLASS, PARENT) \
5368     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5369 #include "clang/AST/TypeLocNodes.def"
5370     }
5371   }
5372 
5373   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5374     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5375     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5376       if (!TL.getParam(I))
5377         continue;
5378 
5379       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5380       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5381     }
5382   }
5383 
5384   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5385     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5386   }
5387 
5388   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5389     // Visit the type parameters from a permissive context.
5390     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5391       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5392       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5393         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5394           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5395       // TODO: other template argument types?
5396     }
5397   }
5398 
5399   // Visit pointee types from a permissive context.
5400 #define CheckPolymorphic(Type) \
5401   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5402     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5403   }
5404   CheckPolymorphic(PointerTypeLoc)
5405   CheckPolymorphic(ReferenceTypeLoc)
5406   CheckPolymorphic(MemberPointerTypeLoc)
5407   CheckPolymorphic(BlockPointerTypeLoc)
5408   CheckPolymorphic(AtomicTypeLoc)
5409 
5410   /// Handle all the types we haven't given a more specific
5411   /// implementation for above.
5412   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5413     // Every other kind of type that we haven't called out already
5414     // that has an inner type is either (1) sugar or (2) contains that
5415     // inner type in some way as a subobject.
5416     if (TypeLoc Next = TL.getNextTypeLoc())
5417       return Visit(Next, Sel);
5418 
5419     // If there's no inner type and we're in a permissive context,
5420     // don't diagnose.
5421     if (Sel == Sema::AbstractNone) return;
5422 
5423     // Check whether the type matches the abstract type.
5424     QualType T = TL.getType();
5425     if (T->isArrayType()) {
5426       Sel = Sema::AbstractArrayType;
5427       T = Info.S.Context.getBaseElementType(T);
5428     }
5429     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5430     if (CT != Info.AbstractType) return;
5431 
5432     // It matched; do some magic.
5433     if (Sel == Sema::AbstractArrayType) {
5434       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5435         << T << TL.getSourceRange();
5436     } else {
5437       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5438         << Sel << T << TL.getSourceRange();
5439     }
5440     Info.DiagnoseAbstractType();
5441   }
5442 };
5443 
5444 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5445                                   Sema::AbstractDiagSelID Sel) {
5446   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5447 }
5448 
5449 }
5450 
5451 /// Check for invalid uses of an abstract type in a method declaration.
5452 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5453                                     CXXMethodDecl *MD) {
5454   // No need to do the check on definitions, which require that
5455   // the return/param types be complete.
5456   if (MD->doesThisDeclarationHaveABody())
5457     return;
5458 
5459   // For safety's sake, just ignore it if we don't have type source
5460   // information.  This should never happen for non-implicit methods,
5461   // but...
5462   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5463     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5464 }
5465 
5466 /// Check for invalid uses of an abstract type within a class definition.
5467 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5468                                     CXXRecordDecl *RD) {
5469   for (auto *D : RD->decls()) {
5470     if (D->isImplicit()) continue;
5471 
5472     // Methods and method templates.
5473     if (isa<CXXMethodDecl>(D)) {
5474       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5475     } else if (isa<FunctionTemplateDecl>(D)) {
5476       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5477       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5478 
5479     // Fields and static variables.
5480     } else if (isa<FieldDecl>(D)) {
5481       FieldDecl *FD = cast<FieldDecl>(D);
5482       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5483         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5484     } else if (isa<VarDecl>(D)) {
5485       VarDecl *VD = cast<VarDecl>(D);
5486       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5487         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5488 
5489     // Nested classes and class templates.
5490     } else if (isa<CXXRecordDecl>(D)) {
5491       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5492     } else if (isa<ClassTemplateDecl>(D)) {
5493       CheckAbstractClassUsage(Info,
5494                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5495     }
5496   }
5497 }
5498 
5499 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5500   Attr *ClassAttr = getDLLAttr(Class);
5501   if (!ClassAttr)
5502     return;
5503 
5504   assert(ClassAttr->getKind() == attr::DLLExport);
5505 
5506   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5507 
5508   if (TSK == TSK_ExplicitInstantiationDeclaration)
5509     // Don't go any further if this is just an explicit instantiation
5510     // declaration.
5511     return;
5512 
5513   for (Decl *Member : Class->decls()) {
5514     // Defined static variables that are members of an exported base
5515     // class must be marked export too.
5516     auto *VD = dyn_cast<VarDecl>(Member);
5517     if (VD && Member->getAttr<DLLExportAttr>() &&
5518         VD->getStorageClass() == SC_Static &&
5519         TSK == TSK_ImplicitInstantiation)
5520       S.MarkVariableReferenced(VD->getLocation(), VD);
5521 
5522     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5523     if (!MD)
5524       continue;
5525 
5526     if (Member->getAttr<DLLExportAttr>()) {
5527       if (MD->isUserProvided()) {
5528         // Instantiate non-default class member functions ...
5529 
5530         // .. except for certain kinds of template specializations.
5531         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5532           continue;
5533 
5534         S.MarkFunctionReferenced(Class->getLocation(), MD);
5535 
5536         // The function will be passed to the consumer when its definition is
5537         // encountered.
5538       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5539                  MD->isCopyAssignmentOperator() ||
5540                  MD->isMoveAssignmentOperator()) {
5541         // Synthesize and instantiate non-trivial implicit methods, explicitly
5542         // defaulted methods, and the copy and move assignment operators. The
5543         // latter are exported even if they are trivial, because the address of
5544         // an operator can be taken and should compare equal across libraries.
5545         DiagnosticErrorTrap Trap(S.Diags);
5546         S.MarkFunctionReferenced(Class->getLocation(), MD);
5547         if (Trap.hasErrorOccurred()) {
5548           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5549               << Class << !S.getLangOpts().CPlusPlus11;
5550           break;
5551         }
5552 
5553         // There is no later point when we will see the definition of this
5554         // function, so pass it to the consumer now.
5555         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5556       }
5557     }
5558   }
5559 }
5560 
5561 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5562                                                         CXXRecordDecl *Class) {
5563   // Only the MS ABI has default constructor closures, so we don't need to do
5564   // this semantic checking anywhere else.
5565   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5566     return;
5567 
5568   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5569   for (Decl *Member : Class->decls()) {
5570     // Look for exported default constructors.
5571     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5572     if (!CD || !CD->isDefaultConstructor())
5573       continue;
5574     auto *Attr = CD->getAttr<DLLExportAttr>();
5575     if (!Attr)
5576       continue;
5577 
5578     // If the class is non-dependent, mark the default arguments as ODR-used so
5579     // that we can properly codegen the constructor closure.
5580     if (!Class->isDependentContext()) {
5581       for (ParmVarDecl *PD : CD->parameters()) {
5582         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5583         S.DiscardCleanupsInEvaluationContext();
5584       }
5585     }
5586 
5587     if (LastExportedDefaultCtor) {
5588       S.Diag(LastExportedDefaultCtor->getLocation(),
5589              diag::err_attribute_dll_ambiguous_default_ctor)
5590           << Class;
5591       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5592           << CD->getDeclName();
5593       return;
5594     }
5595     LastExportedDefaultCtor = CD;
5596   }
5597 }
5598 
5599 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5600   // Mark any compiler-generated routines with the implicit code_seg attribute.
5601   for (auto *Method : Class->methods()) {
5602     if (Method->isUserProvided())
5603       continue;
5604     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5605       Method->addAttr(A);
5606   }
5607 }
5608 
5609 /// Check class-level dllimport/dllexport attribute.
5610 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5611   Attr *ClassAttr = getDLLAttr(Class);
5612 
5613   // MSVC inherits DLL attributes to partial class template specializations.
5614   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5615     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5616       if (Attr *TemplateAttr =
5617               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5618         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5619         A->setInherited(true);
5620         ClassAttr = A;
5621       }
5622     }
5623   }
5624 
5625   if (!ClassAttr)
5626     return;
5627 
5628   if (!Class->isExternallyVisible()) {
5629     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5630         << Class << ClassAttr;
5631     return;
5632   }
5633 
5634   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5635       !ClassAttr->isInherited()) {
5636     // Diagnose dll attributes on members of class with dll attribute.
5637     for (Decl *Member : Class->decls()) {
5638       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5639         continue;
5640       InheritableAttr *MemberAttr = getDLLAttr(Member);
5641       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5642         continue;
5643 
5644       Diag(MemberAttr->getLocation(),
5645              diag::err_attribute_dll_member_of_dll_class)
5646           << MemberAttr << ClassAttr;
5647       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5648       Member->setInvalidDecl();
5649     }
5650   }
5651 
5652   if (Class->getDescribedClassTemplate())
5653     // Don't inherit dll attribute until the template is instantiated.
5654     return;
5655 
5656   // The class is either imported or exported.
5657   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5658 
5659   // Check if this was a dllimport attribute propagated from a derived class to
5660   // a base class template specialization. We don't apply these attributes to
5661   // static data members.
5662   const bool PropagatedImport =
5663       !ClassExported &&
5664       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5665 
5666   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5667 
5668   // Ignore explicit dllexport on explicit class template instantiation declarations.
5669   if (ClassExported && !ClassAttr->isInherited() &&
5670       TSK == TSK_ExplicitInstantiationDeclaration) {
5671     Class->dropAttr<DLLExportAttr>();
5672     return;
5673   }
5674 
5675   // Force declaration of implicit members so they can inherit the attribute.
5676   ForceDeclarationOfImplicitMembers(Class);
5677 
5678   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5679   // seem to be true in practice?
5680 
5681   for (Decl *Member : Class->decls()) {
5682     VarDecl *VD = dyn_cast<VarDecl>(Member);
5683     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5684 
5685     // Only methods and static fields inherit the attributes.
5686     if (!VD && !MD)
5687       continue;
5688 
5689     if (MD) {
5690       // Don't process deleted methods.
5691       if (MD->isDeleted())
5692         continue;
5693 
5694       if (MD->isInlined()) {
5695         // MinGW does not import or export inline methods.
5696         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5697             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5698           continue;
5699 
5700         // MSVC versions before 2015 don't export the move assignment operators
5701         // and move constructor, so don't attempt to import/export them if
5702         // we have a definition.
5703         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5704         if ((MD->isMoveAssignmentOperator() ||
5705              (Ctor && Ctor->isMoveConstructor())) &&
5706             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5707           continue;
5708 
5709         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5710         // operator is exported anyway.
5711         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5712             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5713           continue;
5714       }
5715     }
5716 
5717     // Don't apply dllimport attributes to static data members of class template
5718     // instantiations when the attribute is propagated from a derived class.
5719     if (VD && PropagatedImport)
5720       continue;
5721 
5722     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5723       continue;
5724 
5725     if (!getDLLAttr(Member)) {
5726       auto *NewAttr =
5727           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5728       NewAttr->setInherited(true);
5729       Member->addAttr(NewAttr);
5730 
5731       if (MD) {
5732         // Propagate DLLAttr to friend re-declarations of MD that have already
5733         // been constructed.
5734         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5735              FD = FD->getPreviousDecl()) {
5736           if (FD->getFriendObjectKind() == Decl::FOK_None)
5737             continue;
5738           assert(!getDLLAttr(FD) &&
5739                  "friend re-decl should not already have a DLLAttr");
5740           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5741           NewAttr->setInherited(true);
5742           FD->addAttr(NewAttr);
5743         }
5744       }
5745     }
5746   }
5747 
5748   if (ClassExported)
5749     DelayedDllExportClasses.push_back(Class);
5750 }
5751 
5752 /// Perform propagation of DLL attributes from a derived class to a
5753 /// templated base class for MS compatibility.
5754 void Sema::propagateDLLAttrToBaseClassTemplate(
5755     CXXRecordDecl *Class, Attr *ClassAttr,
5756     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5757   if (getDLLAttr(
5758           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5759     // If the base class template has a DLL attribute, don't try to change it.
5760     return;
5761   }
5762 
5763   auto TSK = BaseTemplateSpec->getSpecializationKind();
5764   if (!getDLLAttr(BaseTemplateSpec) &&
5765       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5766        TSK == TSK_ImplicitInstantiation)) {
5767     // The template hasn't been instantiated yet (or it has, but only as an
5768     // explicit instantiation declaration or implicit instantiation, which means
5769     // we haven't codegenned any members yet), so propagate the attribute.
5770     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5771     NewAttr->setInherited(true);
5772     BaseTemplateSpec->addAttr(NewAttr);
5773 
5774     // If this was an import, mark that we propagated it from a derived class to
5775     // a base class template specialization.
5776     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5777       ImportAttr->setPropagatedToBaseTemplate();
5778 
5779     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5780     // needs to be run again to work see the new attribute. Otherwise this will
5781     // get run whenever the template is instantiated.
5782     if (TSK != TSK_Undeclared)
5783       checkClassLevelDLLAttribute(BaseTemplateSpec);
5784 
5785     return;
5786   }
5787 
5788   if (getDLLAttr(BaseTemplateSpec)) {
5789     // The template has already been specialized or instantiated with an
5790     // attribute, explicitly or through propagation. We should not try to change
5791     // it.
5792     return;
5793   }
5794 
5795   // The template was previously instantiated or explicitly specialized without
5796   // a dll attribute, It's too late for us to add an attribute, so warn that
5797   // this is unsupported.
5798   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5799       << BaseTemplateSpec->isExplicitSpecialization();
5800   Diag(ClassAttr->getLocation(), diag::note_attribute);
5801   if (BaseTemplateSpec->isExplicitSpecialization()) {
5802     Diag(BaseTemplateSpec->getLocation(),
5803            diag::note_template_class_explicit_specialization_was_here)
5804         << BaseTemplateSpec;
5805   } else {
5806     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5807            diag::note_template_class_instantiation_was_here)
5808         << BaseTemplateSpec;
5809   }
5810 }
5811 
5812 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5813                                         SourceLocation DefaultLoc) {
5814   switch (S.getSpecialMember(MD)) {
5815   case Sema::CXXDefaultConstructor:
5816     S.DefineImplicitDefaultConstructor(DefaultLoc,
5817                                        cast<CXXConstructorDecl>(MD));
5818     break;
5819   case Sema::CXXCopyConstructor:
5820     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5821     break;
5822   case Sema::CXXCopyAssignment:
5823     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5824     break;
5825   case Sema::CXXDestructor:
5826     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5827     break;
5828   case Sema::CXXMoveConstructor:
5829     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5830     break;
5831   case Sema::CXXMoveAssignment:
5832     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5833     break;
5834   case Sema::CXXInvalid:
5835     llvm_unreachable("Invalid special member.");
5836   }
5837 }
5838 
5839 /// Determine whether a type is permitted to be passed or returned in
5840 /// registers, per C++ [class.temporary]p3.
5841 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5842                                TargetInfo::CallingConvKind CCK) {
5843   if (D->isDependentType() || D->isInvalidDecl())
5844     return false;
5845 
5846   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5847   // The PS4 platform ABI follows the behavior of Clang 3.2.
5848   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5849     return !D->hasNonTrivialDestructorForCall() &&
5850            !D->hasNonTrivialCopyConstructorForCall();
5851 
5852   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5853     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5854     bool DtorIsTrivialForCall = false;
5855 
5856     // If a class has at least one non-deleted, trivial copy constructor, it
5857     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5858     //
5859     // Note: This permits classes with non-trivial copy or move ctors to be
5860     // passed in registers, so long as they *also* have a trivial copy ctor,
5861     // which is non-conforming.
5862     if (D->needsImplicitCopyConstructor()) {
5863       if (!D->defaultedCopyConstructorIsDeleted()) {
5864         if (D->hasTrivialCopyConstructor())
5865           CopyCtorIsTrivial = true;
5866         if (D->hasTrivialCopyConstructorForCall())
5867           CopyCtorIsTrivialForCall = true;
5868       }
5869     } else {
5870       for (const CXXConstructorDecl *CD : D->ctors()) {
5871         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5872           if (CD->isTrivial())
5873             CopyCtorIsTrivial = true;
5874           if (CD->isTrivialForCall())
5875             CopyCtorIsTrivialForCall = true;
5876         }
5877       }
5878     }
5879 
5880     if (D->needsImplicitDestructor()) {
5881       if (!D->defaultedDestructorIsDeleted() &&
5882           D->hasTrivialDestructorForCall())
5883         DtorIsTrivialForCall = true;
5884     } else if (const auto *DD = D->getDestructor()) {
5885       if (!DD->isDeleted() && DD->isTrivialForCall())
5886         DtorIsTrivialForCall = true;
5887     }
5888 
5889     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5890     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5891       return true;
5892 
5893     // If a class has a destructor, we'd really like to pass it indirectly
5894     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5895     // impossible for small types, which it will pass in a single register or
5896     // stack slot. Most objects with dtors are large-ish, so handle that early.
5897     // We can't call out all large objects as being indirect because there are
5898     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5899     // how we pass large POD types.
5900 
5901     // Note: This permits small classes with nontrivial destructors to be
5902     // passed in registers, which is non-conforming.
5903     if (CopyCtorIsTrivial &&
5904         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5905       return true;
5906     return false;
5907   }
5908 
5909   // Per C++ [class.temporary]p3, the relevant condition is:
5910   //   each copy constructor, move constructor, and destructor of X is
5911   //   either trivial or deleted, and X has at least one non-deleted copy
5912   //   or move constructor
5913   bool HasNonDeletedCopyOrMove = false;
5914 
5915   if (D->needsImplicitCopyConstructor() &&
5916       !D->defaultedCopyConstructorIsDeleted()) {
5917     if (!D->hasTrivialCopyConstructorForCall())
5918       return false;
5919     HasNonDeletedCopyOrMove = true;
5920   }
5921 
5922   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5923       !D->defaultedMoveConstructorIsDeleted()) {
5924     if (!D->hasTrivialMoveConstructorForCall())
5925       return false;
5926     HasNonDeletedCopyOrMove = true;
5927   }
5928 
5929   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5930       !D->hasTrivialDestructorForCall())
5931     return false;
5932 
5933   for (const CXXMethodDecl *MD : D->methods()) {
5934     if (MD->isDeleted())
5935       continue;
5936 
5937     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5938     if (CD && CD->isCopyOrMoveConstructor())
5939       HasNonDeletedCopyOrMove = true;
5940     else if (!isa<CXXDestructorDecl>(MD))
5941       continue;
5942 
5943     if (!MD->isTrivialForCall())
5944       return false;
5945   }
5946 
5947   return HasNonDeletedCopyOrMove;
5948 }
5949 
5950 /// Perform semantic checks on a class definition that has been
5951 /// completing, introducing implicitly-declared members, checking for
5952 /// abstract types, etc.
5953 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5954   if (!Record)
5955     return;
5956 
5957   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5958     AbstractUsageInfo Info(*this, Record);
5959     CheckAbstractClassUsage(Info, Record);
5960   }
5961 
5962   // If this is not an aggregate type and has no user-declared constructor,
5963   // complain about any non-static data members of reference or const scalar
5964   // type, since they will never get initializers.
5965   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5966       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5967       !Record->isLambda()) {
5968     bool Complained = false;
5969     for (const auto *F : Record->fields()) {
5970       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5971         continue;
5972 
5973       if (F->getType()->isReferenceType() ||
5974           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5975         if (!Complained) {
5976           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5977             << Record->getTagKind() << Record;
5978           Complained = true;
5979         }
5980 
5981         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5982           << F->getType()->isReferenceType()
5983           << F->getDeclName();
5984       }
5985     }
5986   }
5987 
5988   if (Record->getIdentifier()) {
5989     // C++ [class.mem]p13:
5990     //   If T is the name of a class, then each of the following shall have a
5991     //   name different from T:
5992     //     - every member of every anonymous union that is a member of class T.
5993     //
5994     // C++ [class.mem]p14:
5995     //   In addition, if class T has a user-declared constructor (12.1), every
5996     //   non-static data member of class T shall have a name different from T.
5997     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5998     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5999          ++I) {
6000       NamedDecl *D = (*I)->getUnderlyingDecl();
6001       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6002            Record->hasUserDeclaredConstructor()) ||
6003           isa<IndirectFieldDecl>(D)) {
6004         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6005           << D->getDeclName();
6006         break;
6007       }
6008     }
6009   }
6010 
6011   // Warn if the class has virtual methods but non-virtual public destructor.
6012   if (Record->isPolymorphic() && !Record->isDependentType()) {
6013     CXXDestructorDecl *dtor = Record->getDestructor();
6014     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6015         !Record->hasAttr<FinalAttr>())
6016       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6017            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6018   }
6019 
6020   if (Record->isAbstract()) {
6021     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6022       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6023         << FA->isSpelledAsSealed();
6024       DiagnoseAbstractType(Record);
6025     }
6026   }
6027 
6028   // See if trivial_abi has to be dropped.
6029   if (Record->hasAttr<TrivialABIAttr>())
6030     checkIllFormedTrivialABIStruct(*Record);
6031 
6032   // Set HasTrivialSpecialMemberForCall if the record has attribute
6033   // "trivial_abi".
6034   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6035 
6036   if (HasTrivialABI)
6037     Record->setHasTrivialSpecialMemberForCall();
6038 
6039   bool HasMethodWithOverrideControl = false,
6040        HasOverridingMethodWithoutOverrideControl = false;
6041   if (!Record->isDependentType()) {
6042     for (auto *M : Record->methods()) {
6043       // See if a method overloads virtual methods in a base
6044       // class without overriding any.
6045       if (!M->isStatic())
6046         DiagnoseHiddenVirtualMethods(M);
6047       if (M->hasAttr<OverrideAttr>())
6048         HasMethodWithOverrideControl = true;
6049       else if (M->size_overridden_methods() > 0)
6050         HasOverridingMethodWithoutOverrideControl = true;
6051       // Check whether the explicitly-defaulted special members are valid.
6052       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6053         CheckExplicitlyDefaultedSpecialMember(M);
6054 
6055       // For an explicitly defaulted or deleted special member, we defer
6056       // determining triviality until the class is complete. That time is now!
6057       CXXSpecialMember CSM = getSpecialMember(M);
6058       if (!M->isImplicit() && !M->isUserProvided()) {
6059         if (CSM != CXXInvalid) {
6060           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6061           // Inform the class that we've finished declaring this member.
6062           Record->finishedDefaultedOrDeletedMember(M);
6063           M->setTrivialForCall(
6064               HasTrivialABI ||
6065               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6066           Record->setTrivialForCallFlags(M);
6067         }
6068       }
6069 
6070       // Set triviality for the purpose of calls if this is a user-provided
6071       // copy/move constructor or destructor.
6072       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6073            CSM == CXXDestructor) && M->isUserProvided()) {
6074         M->setTrivialForCall(HasTrivialABI);
6075         Record->setTrivialForCallFlags(M);
6076       }
6077 
6078       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6079           M->hasAttr<DLLExportAttr>()) {
6080         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6081             M->isTrivial() &&
6082             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6083              CSM == CXXDestructor))
6084           M->dropAttr<DLLExportAttr>();
6085 
6086         if (M->hasAttr<DLLExportAttr>()) {
6087           DefineImplicitSpecialMember(*this, M, M->getLocation());
6088           ActOnFinishInlineFunctionDef(M);
6089         }
6090       }
6091     }
6092   }
6093 
6094   if (HasMethodWithOverrideControl &&
6095       HasOverridingMethodWithoutOverrideControl) {
6096     // At least one method has the 'override' control declared.
6097     // Diagnose all other overridden methods which do not have 'override' specified on them.
6098     for (auto *M : Record->methods())
6099       DiagnoseAbsenceOfOverrideControl(M);
6100   }
6101 
6102   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6103   // whether this class uses any C++ features that are implemented
6104   // completely differently in MSVC, and if so, emit a diagnostic.
6105   // That diagnostic defaults to an error, but we allow projects to
6106   // map it down to a warning (or ignore it).  It's a fairly common
6107   // practice among users of the ms_struct pragma to mass-annotate
6108   // headers, sweeping up a bunch of types that the project doesn't
6109   // really rely on MSVC-compatible layout for.  We must therefore
6110   // support "ms_struct except for C++ stuff" as a secondary ABI.
6111   if (Record->isMsStruct(Context) &&
6112       (Record->isPolymorphic() || Record->getNumBases())) {
6113     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6114   }
6115 
6116   checkClassLevelDLLAttribute(Record);
6117   checkClassLevelCodeSegAttribute(Record);
6118 
6119   bool ClangABICompat4 =
6120       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6121   TargetInfo::CallingConvKind CCK =
6122       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6123   bool CanPass = canPassInRegisters(*this, Record, CCK);
6124 
6125   // Do not change ArgPassingRestrictions if it has already been set to
6126   // APK_CanNeverPassInRegs.
6127   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6128     Record->setArgPassingRestrictions(CanPass
6129                                           ? RecordDecl::APK_CanPassInRegs
6130                                           : RecordDecl::APK_CannotPassInRegs);
6131 
6132   // If canPassInRegisters returns true despite the record having a non-trivial
6133   // destructor, the record is destructed in the callee. This happens only when
6134   // the record or one of its subobjects has a field annotated with trivial_abi
6135   // or a field qualified with ObjC __strong/__weak.
6136   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6137     Record->setParamDestroyedInCallee(true);
6138   else if (Record->hasNonTrivialDestructor())
6139     Record->setParamDestroyedInCallee(CanPass);
6140 
6141   if (getLangOpts().ForceEmitVTables) {
6142     // If we want to emit all the vtables, we need to mark it as used.  This
6143     // is especially required for cases like vtable assumption loads.
6144     MarkVTableUsed(Record->getInnerLocStart(), Record);
6145   }
6146 }
6147 
6148 /// Look up the special member function that would be called by a special
6149 /// member function for a subobject of class type.
6150 ///
6151 /// \param Class The class type of the subobject.
6152 /// \param CSM The kind of special member function.
6153 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6154 /// \param ConstRHS True if this is a copy operation with a const object
6155 ///        on its RHS, that is, if the argument to the outer special member
6156 ///        function is 'const' and this is not a field marked 'mutable'.
6157 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6158     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6159     unsigned FieldQuals, bool ConstRHS) {
6160   unsigned LHSQuals = 0;
6161   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6162     LHSQuals = FieldQuals;
6163 
6164   unsigned RHSQuals = FieldQuals;
6165   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6166     RHSQuals = 0;
6167   else if (ConstRHS)
6168     RHSQuals |= Qualifiers::Const;
6169 
6170   return S.LookupSpecialMember(Class, CSM,
6171                                RHSQuals & Qualifiers::Const,
6172                                RHSQuals & Qualifiers::Volatile,
6173                                false,
6174                                LHSQuals & Qualifiers::Const,
6175                                LHSQuals & Qualifiers::Volatile);
6176 }
6177 
6178 class Sema::InheritedConstructorInfo {
6179   Sema &S;
6180   SourceLocation UseLoc;
6181 
6182   /// A mapping from the base classes through which the constructor was
6183   /// inherited to the using shadow declaration in that base class (or a null
6184   /// pointer if the constructor was declared in that base class).
6185   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6186       InheritedFromBases;
6187 
6188 public:
6189   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6190                            ConstructorUsingShadowDecl *Shadow)
6191       : S(S), UseLoc(UseLoc) {
6192     bool DiagnosedMultipleConstructedBases = false;
6193     CXXRecordDecl *ConstructedBase = nullptr;
6194     UsingDecl *ConstructedBaseUsing = nullptr;
6195 
6196     // Find the set of such base class subobjects and check that there's a
6197     // unique constructed subobject.
6198     for (auto *D : Shadow->redecls()) {
6199       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6200       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6201       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6202 
6203       InheritedFromBases.insert(
6204           std::make_pair(DNominatedBase->getCanonicalDecl(),
6205                          DShadow->getNominatedBaseClassShadowDecl()));
6206       if (DShadow->constructsVirtualBase())
6207         InheritedFromBases.insert(
6208             std::make_pair(DConstructedBase->getCanonicalDecl(),
6209                            DShadow->getConstructedBaseClassShadowDecl()));
6210       else
6211         assert(DNominatedBase == DConstructedBase);
6212 
6213       // [class.inhctor.init]p2:
6214       //   If the constructor was inherited from multiple base class subobjects
6215       //   of type B, the program is ill-formed.
6216       if (!ConstructedBase) {
6217         ConstructedBase = DConstructedBase;
6218         ConstructedBaseUsing = D->getUsingDecl();
6219       } else if (ConstructedBase != DConstructedBase &&
6220                  !Shadow->isInvalidDecl()) {
6221         if (!DiagnosedMultipleConstructedBases) {
6222           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6223               << Shadow->getTargetDecl();
6224           S.Diag(ConstructedBaseUsing->getLocation(),
6225                diag::note_ambiguous_inherited_constructor_using)
6226               << ConstructedBase;
6227           DiagnosedMultipleConstructedBases = true;
6228         }
6229         S.Diag(D->getUsingDecl()->getLocation(),
6230                diag::note_ambiguous_inherited_constructor_using)
6231             << DConstructedBase;
6232       }
6233     }
6234 
6235     if (DiagnosedMultipleConstructedBases)
6236       Shadow->setInvalidDecl();
6237   }
6238 
6239   /// Find the constructor to use for inherited construction of a base class,
6240   /// and whether that base class constructor inherits the constructor from a
6241   /// virtual base class (in which case it won't actually invoke it).
6242   std::pair<CXXConstructorDecl *, bool>
6243   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6244     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6245     if (It == InheritedFromBases.end())
6246       return std::make_pair(nullptr, false);
6247 
6248     // This is an intermediary class.
6249     if (It->second)
6250       return std::make_pair(
6251           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6252           It->second->constructsVirtualBase());
6253 
6254     // This is the base class from which the constructor was inherited.
6255     return std::make_pair(Ctor, false);
6256   }
6257 };
6258 
6259 /// Is the special member function which would be selected to perform the
6260 /// specified operation on the specified class type a constexpr constructor?
6261 static bool
6262 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6263                          Sema::CXXSpecialMember CSM, unsigned Quals,
6264                          bool ConstRHS,
6265                          CXXConstructorDecl *InheritedCtor = nullptr,
6266                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6267   // If we're inheriting a constructor, see if we need to call it for this base
6268   // class.
6269   if (InheritedCtor) {
6270     assert(CSM == Sema::CXXDefaultConstructor);
6271     auto BaseCtor =
6272         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6273     if (BaseCtor)
6274       return BaseCtor->isConstexpr();
6275   }
6276 
6277   if (CSM == Sema::CXXDefaultConstructor)
6278     return ClassDecl->hasConstexprDefaultConstructor();
6279 
6280   Sema::SpecialMemberOverloadResult SMOR =
6281       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6282   if (!SMOR.getMethod())
6283     // A constructor we wouldn't select can't be "involved in initializing"
6284     // anything.
6285     return true;
6286   return SMOR.getMethod()->isConstexpr();
6287 }
6288 
6289 /// Determine whether the specified special member function would be constexpr
6290 /// if it were implicitly defined.
6291 static bool defaultedSpecialMemberIsConstexpr(
6292     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6293     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6294     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6295   if (!S.getLangOpts().CPlusPlus11)
6296     return false;
6297 
6298   // C++11 [dcl.constexpr]p4:
6299   // In the definition of a constexpr constructor [...]
6300   bool Ctor = true;
6301   switch (CSM) {
6302   case Sema::CXXDefaultConstructor:
6303     if (Inherited)
6304       break;
6305     // Since default constructor lookup is essentially trivial (and cannot
6306     // involve, for instance, template instantiation), we compute whether a
6307     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6308     //
6309     // This is important for performance; we need to know whether the default
6310     // constructor is constexpr to determine whether the type is a literal type.
6311     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6312 
6313   case Sema::CXXCopyConstructor:
6314   case Sema::CXXMoveConstructor:
6315     // For copy or move constructors, we need to perform overload resolution.
6316     break;
6317 
6318   case Sema::CXXCopyAssignment:
6319   case Sema::CXXMoveAssignment:
6320     if (!S.getLangOpts().CPlusPlus14)
6321       return false;
6322     // In C++1y, we need to perform overload resolution.
6323     Ctor = false;
6324     break;
6325 
6326   case Sema::CXXDestructor:
6327   case Sema::CXXInvalid:
6328     return false;
6329   }
6330 
6331   //   -- if the class is a non-empty union, or for each non-empty anonymous
6332   //      union member of a non-union class, exactly one non-static data member
6333   //      shall be initialized; [DR1359]
6334   //
6335   // If we squint, this is guaranteed, since exactly one non-static data member
6336   // will be initialized (if the constructor isn't deleted), we just don't know
6337   // which one.
6338   if (Ctor && ClassDecl->isUnion())
6339     return CSM == Sema::CXXDefaultConstructor
6340                ? ClassDecl->hasInClassInitializer() ||
6341                      !ClassDecl->hasVariantMembers()
6342                : true;
6343 
6344   //   -- the class shall not have any virtual base classes;
6345   if (Ctor && ClassDecl->getNumVBases())
6346     return false;
6347 
6348   // C++1y [class.copy]p26:
6349   //   -- [the class] is a literal type, and
6350   if (!Ctor && !ClassDecl->isLiteral())
6351     return false;
6352 
6353   //   -- every constructor involved in initializing [...] base class
6354   //      sub-objects shall be a constexpr constructor;
6355   //   -- the assignment operator selected to copy/move each direct base
6356   //      class is a constexpr function, and
6357   for (const auto &B : ClassDecl->bases()) {
6358     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6359     if (!BaseType) continue;
6360 
6361     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6362     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6363                                   InheritedCtor, Inherited))
6364       return false;
6365   }
6366 
6367   //   -- every constructor involved in initializing non-static data members
6368   //      [...] shall be a constexpr constructor;
6369   //   -- every non-static data member and base class sub-object shall be
6370   //      initialized
6371   //   -- for each non-static data member of X that is of class type (or array
6372   //      thereof), the assignment operator selected to copy/move that member is
6373   //      a constexpr function
6374   for (const auto *F : ClassDecl->fields()) {
6375     if (F->isInvalidDecl())
6376       continue;
6377     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6378       continue;
6379     QualType BaseType = S.Context.getBaseElementType(F->getType());
6380     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6381       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6382       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6383                                     BaseType.getCVRQualifiers(),
6384                                     ConstArg && !F->isMutable()))
6385         return false;
6386     } else if (CSM == Sema::CXXDefaultConstructor) {
6387       return false;
6388     }
6389   }
6390 
6391   // All OK, it's constexpr!
6392   return true;
6393 }
6394 
6395 static Sema::ImplicitExceptionSpecification
6396 ComputeDefaultedSpecialMemberExceptionSpec(
6397     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6398     Sema::InheritedConstructorInfo *ICI);
6399 
6400 static Sema::ImplicitExceptionSpecification
6401 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6402   auto CSM = S.getSpecialMember(MD);
6403   if (CSM != Sema::CXXInvalid)
6404     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6405 
6406   auto *CD = cast<CXXConstructorDecl>(MD);
6407   assert(CD->getInheritedConstructor() &&
6408          "only special members have implicit exception specs");
6409   Sema::InheritedConstructorInfo ICI(
6410       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6411   return ComputeDefaultedSpecialMemberExceptionSpec(
6412       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6413 }
6414 
6415 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6416                                                             CXXMethodDecl *MD) {
6417   FunctionProtoType::ExtProtoInfo EPI;
6418 
6419   // Build an exception specification pointing back at this member.
6420   EPI.ExceptionSpec.Type = EST_Unevaluated;
6421   EPI.ExceptionSpec.SourceDecl = MD;
6422 
6423   // Set the calling convention to the default for C++ instance methods.
6424   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6425       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6426                                             /*IsCXXMethod=*/true));
6427   return EPI;
6428 }
6429 
6430 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6431   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6432   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6433     return;
6434 
6435   // Evaluate the exception specification.
6436   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6437   auto ESI = IES.getExceptionSpec();
6438 
6439   // Update the type of the special member to use it.
6440   UpdateExceptionSpec(MD, ESI);
6441 
6442   // A user-provided destructor can be defined outside the class. When that
6443   // happens, be sure to update the exception specification on both
6444   // declarations.
6445   const FunctionProtoType *CanonicalFPT =
6446     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6447   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6448     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6449 }
6450 
6451 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6452   CXXRecordDecl *RD = MD->getParent();
6453   CXXSpecialMember CSM = getSpecialMember(MD);
6454 
6455   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6456          "not an explicitly-defaulted special member");
6457 
6458   // Whether this was the first-declared instance of the constructor.
6459   // This affects whether we implicitly add an exception spec and constexpr.
6460   bool First = MD == MD->getCanonicalDecl();
6461 
6462   bool HadError = false;
6463 
6464   // C++11 [dcl.fct.def.default]p1:
6465   //   A function that is explicitly defaulted shall
6466   //     -- be a special member function (checked elsewhere),
6467   //     -- have the same type (except for ref-qualifiers, and except that a
6468   //        copy operation can take a non-const reference) as an implicit
6469   //        declaration, and
6470   //     -- not have default arguments.
6471   unsigned ExpectedParams = 1;
6472   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6473     ExpectedParams = 0;
6474   if (MD->getNumParams() != ExpectedParams) {
6475     // This also checks for default arguments: a copy or move constructor with a
6476     // default argument is classified as a default constructor, and assignment
6477     // operations and destructors can't have default arguments.
6478     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6479       << CSM << MD->getSourceRange();
6480     HadError = true;
6481   } else if (MD->isVariadic()) {
6482     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6483       << CSM << MD->getSourceRange();
6484     HadError = true;
6485   }
6486 
6487   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6488 
6489   bool CanHaveConstParam = false;
6490   if (CSM == CXXCopyConstructor)
6491     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6492   else if (CSM == CXXCopyAssignment)
6493     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6494 
6495   QualType ReturnType = Context.VoidTy;
6496   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6497     // Check for return type matching.
6498     ReturnType = Type->getReturnType();
6499     QualType ExpectedReturnType =
6500         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6501     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6502       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6503         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6504       HadError = true;
6505     }
6506 
6507     // A defaulted special member cannot have cv-qualifiers.
6508     if (Type->getTypeQuals()) {
6509       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6510         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6511       HadError = true;
6512     }
6513   }
6514 
6515   // Check for parameter type matching.
6516   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6517   bool HasConstParam = false;
6518   if (ExpectedParams && ArgType->isReferenceType()) {
6519     // Argument must be reference to possibly-const T.
6520     QualType ReferentType = ArgType->getPointeeType();
6521     HasConstParam = ReferentType.isConstQualified();
6522 
6523     if (ReferentType.isVolatileQualified()) {
6524       Diag(MD->getLocation(),
6525            diag::err_defaulted_special_member_volatile_param) << CSM;
6526       HadError = true;
6527     }
6528 
6529     if (HasConstParam && !CanHaveConstParam) {
6530       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6531         Diag(MD->getLocation(),
6532              diag::err_defaulted_special_member_copy_const_param)
6533           << (CSM == CXXCopyAssignment);
6534         // FIXME: Explain why this special member can't be const.
6535       } else {
6536         Diag(MD->getLocation(),
6537              diag::err_defaulted_special_member_move_const_param)
6538           << (CSM == CXXMoveAssignment);
6539       }
6540       HadError = true;
6541     }
6542   } else if (ExpectedParams) {
6543     // A copy assignment operator can take its argument by value, but a
6544     // defaulted one cannot.
6545     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6546     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6547     HadError = true;
6548   }
6549 
6550   // C++11 [dcl.fct.def.default]p2:
6551   //   An explicitly-defaulted function may be declared constexpr only if it
6552   //   would have been implicitly declared as constexpr,
6553   // Do not apply this rule to members of class templates, since core issue 1358
6554   // makes such functions always instantiate to constexpr functions. For
6555   // functions which cannot be constexpr (for non-constructors in C++11 and for
6556   // destructors in C++1y), this is checked elsewhere.
6557   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6558                                                      HasConstParam);
6559   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6560                                  : isa<CXXConstructorDecl>(MD)) &&
6561       MD->isConstexpr() && !Constexpr &&
6562       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6563     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6564     // FIXME: Explain why the special member can't be constexpr.
6565     HadError = true;
6566   }
6567 
6568   //   and may have an explicit exception-specification only if it is compatible
6569   //   with the exception-specification on the implicit declaration.
6570   if (Type->hasExceptionSpec()) {
6571     // Delay the check if this is the first declaration of the special member,
6572     // since we may not have parsed some necessary in-class initializers yet.
6573     if (First) {
6574       // If the exception specification needs to be instantiated, do so now,
6575       // before we clobber it with an EST_Unevaluated specification below.
6576       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6577         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6578         Type = MD->getType()->getAs<FunctionProtoType>();
6579       }
6580       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6581     } else
6582       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6583   }
6584 
6585   //   If a function is explicitly defaulted on its first declaration,
6586   if (First) {
6587     //  -- it is implicitly considered to be constexpr if the implicit
6588     //     definition would be,
6589     MD->setConstexpr(Constexpr);
6590 
6591     //  -- it is implicitly considered to have the same exception-specification
6592     //     as if it had been implicitly declared,
6593     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6594     EPI.ExceptionSpec.Type = EST_Unevaluated;
6595     EPI.ExceptionSpec.SourceDecl = MD;
6596     MD->setType(Context.getFunctionType(ReturnType,
6597                                         llvm::makeArrayRef(&ArgType,
6598                                                            ExpectedParams),
6599                                         EPI));
6600   }
6601 
6602   if (ShouldDeleteSpecialMember(MD, CSM)) {
6603     if (First) {
6604       SetDeclDeleted(MD, MD->getLocation());
6605     } else {
6606       // C++11 [dcl.fct.def.default]p4:
6607       //   [For a] user-provided explicitly-defaulted function [...] if such a
6608       //   function is implicitly defined as deleted, the program is ill-formed.
6609       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6610       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6611       HadError = true;
6612     }
6613   }
6614 
6615   if (HadError)
6616     MD->setInvalidDecl();
6617 }
6618 
6619 /// Check whether the exception specification provided for an
6620 /// explicitly-defaulted special member matches the exception specification
6621 /// that would have been generated for an implicit special member, per
6622 /// C++11 [dcl.fct.def.default]p2.
6623 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6624     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6625   // If the exception specification was explicitly specified but hadn't been
6626   // parsed when the method was defaulted, grab it now.
6627   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6628     SpecifiedType =
6629         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6630 
6631   // Compute the implicit exception specification.
6632   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6633                                                        /*IsCXXMethod=*/true);
6634   FunctionProtoType::ExtProtoInfo EPI(CC);
6635   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6636   EPI.ExceptionSpec = IES.getExceptionSpec();
6637   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6638     Context.getFunctionType(Context.VoidTy, None, EPI));
6639 
6640   // Ensure that it matches.
6641   CheckEquivalentExceptionSpec(
6642     PDiag(diag::err_incorrect_defaulted_exception_spec)
6643       << getSpecialMember(MD), PDiag(),
6644     ImplicitType, SourceLocation(),
6645     SpecifiedType, MD->getLocation());
6646 }
6647 
6648 void Sema::CheckDelayedMemberExceptionSpecs() {
6649   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6650   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6651   decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6652 
6653   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6654   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6655   std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6656 
6657   // Perform any deferred checking of exception specifications for virtual
6658   // destructors.
6659   for (auto &Check : Overriding)
6660     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6661 
6662   // Perform any deferred checking of exception specifications for befriended
6663   // special members.
6664   for (auto &Check : Equivalent)
6665     CheckEquivalentExceptionSpec(Check.second, Check.first);
6666 
6667   // Check that any explicitly-defaulted methods have exception specifications
6668   // compatible with their implicit exception specifications.
6669   for (auto &Spec : Defaulted)
6670     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6671 }
6672 
6673 namespace {
6674 /// CRTP base class for visiting operations performed by a special member
6675 /// function (or inherited constructor).
6676 template<typename Derived>
6677 struct SpecialMemberVisitor {
6678   Sema &S;
6679   CXXMethodDecl *MD;
6680   Sema::CXXSpecialMember CSM;
6681   Sema::InheritedConstructorInfo *ICI;
6682 
6683   // Properties of the special member, computed for convenience.
6684   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6685 
6686   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6687                        Sema::InheritedConstructorInfo *ICI)
6688       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6689     switch (CSM) {
6690     case Sema::CXXDefaultConstructor:
6691     case Sema::CXXCopyConstructor:
6692     case Sema::CXXMoveConstructor:
6693       IsConstructor = true;
6694       break;
6695     case Sema::CXXCopyAssignment:
6696     case Sema::CXXMoveAssignment:
6697       IsAssignment = true;
6698       break;
6699     case Sema::CXXDestructor:
6700       break;
6701     case Sema::CXXInvalid:
6702       llvm_unreachable("invalid special member kind");
6703     }
6704 
6705     if (MD->getNumParams()) {
6706       if (const ReferenceType *RT =
6707               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6708         ConstArg = RT->getPointeeType().isConstQualified();
6709     }
6710   }
6711 
6712   Derived &getDerived() { return static_cast<Derived&>(*this); }
6713 
6714   /// Is this a "move" special member?
6715   bool isMove() const {
6716     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6717   }
6718 
6719   /// Look up the corresponding special member in the given class.
6720   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6721                                              unsigned Quals, bool IsMutable) {
6722     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6723                                        ConstArg && !IsMutable);
6724   }
6725 
6726   /// Look up the constructor for the specified base class to see if it's
6727   /// overridden due to this being an inherited constructor.
6728   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6729     if (!ICI)
6730       return {};
6731     assert(CSM == Sema::CXXDefaultConstructor);
6732     auto *BaseCtor =
6733       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6734     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6735       return MD;
6736     return {};
6737   }
6738 
6739   /// A base or member subobject.
6740   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6741 
6742   /// Get the location to use for a subobject in diagnostics.
6743   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6744     // FIXME: For an indirect virtual base, the direct base leading to
6745     // the indirect virtual base would be a more useful choice.
6746     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6747       return B->getBaseTypeLoc();
6748     else
6749       return Subobj.get<FieldDecl*>()->getLocation();
6750   }
6751 
6752   enum BasesToVisit {
6753     /// Visit all non-virtual (direct) bases.
6754     VisitNonVirtualBases,
6755     /// Visit all direct bases, virtual or not.
6756     VisitDirectBases,
6757     /// Visit all non-virtual bases, and all virtual bases if the class
6758     /// is not abstract.
6759     VisitPotentiallyConstructedBases,
6760     /// Visit all direct or virtual bases.
6761     VisitAllBases
6762   };
6763 
6764   // Visit the bases and members of the class.
6765   bool visit(BasesToVisit Bases) {
6766     CXXRecordDecl *RD = MD->getParent();
6767 
6768     if (Bases == VisitPotentiallyConstructedBases)
6769       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6770 
6771     for (auto &B : RD->bases())
6772       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6773           getDerived().visitBase(&B))
6774         return true;
6775 
6776     if (Bases == VisitAllBases)
6777       for (auto &B : RD->vbases())
6778         if (getDerived().visitBase(&B))
6779           return true;
6780 
6781     for (auto *F : RD->fields())
6782       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6783           getDerived().visitField(F))
6784         return true;
6785 
6786     return false;
6787   }
6788 };
6789 }
6790 
6791 namespace {
6792 struct SpecialMemberDeletionInfo
6793     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6794   bool Diagnose;
6795 
6796   SourceLocation Loc;
6797 
6798   bool AllFieldsAreConst;
6799 
6800   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6801                             Sema::CXXSpecialMember CSM,
6802                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6803       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6804         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6805 
6806   bool inUnion() const { return MD->getParent()->isUnion(); }
6807 
6808   Sema::CXXSpecialMember getEffectiveCSM() {
6809     return ICI ? Sema::CXXInvalid : CSM;
6810   }
6811 
6812   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6813   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6814 
6815   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6816   bool shouldDeleteForField(FieldDecl *FD);
6817   bool shouldDeleteForAllConstMembers();
6818 
6819   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6820                                      unsigned Quals);
6821   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6822                                     Sema::SpecialMemberOverloadResult SMOR,
6823                                     bool IsDtorCallInCtor);
6824 
6825   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6826 };
6827 }
6828 
6829 /// Is the given special member inaccessible when used on the given
6830 /// sub-object.
6831 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6832                                              CXXMethodDecl *target) {
6833   /// If we're operating on a base class, the object type is the
6834   /// type of this special member.
6835   QualType objectTy;
6836   AccessSpecifier access = target->getAccess();
6837   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6838     objectTy = S.Context.getTypeDeclType(MD->getParent());
6839     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6840 
6841   // If we're operating on a field, the object type is the type of the field.
6842   } else {
6843     objectTy = S.Context.getTypeDeclType(target->getParent());
6844   }
6845 
6846   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6847 }
6848 
6849 /// Check whether we should delete a special member due to the implicit
6850 /// definition containing a call to a special member of a subobject.
6851 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6852     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6853     bool IsDtorCallInCtor) {
6854   CXXMethodDecl *Decl = SMOR.getMethod();
6855   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6856 
6857   int DiagKind = -1;
6858 
6859   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6860     DiagKind = !Decl ? 0 : 1;
6861   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6862     DiagKind = 2;
6863   else if (!isAccessible(Subobj, Decl))
6864     DiagKind = 3;
6865   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6866            !Decl->isTrivial()) {
6867     // A member of a union must have a trivial corresponding special member.
6868     // As a weird special case, a destructor call from a union's constructor
6869     // must be accessible and non-deleted, but need not be trivial. Such a
6870     // destructor is never actually called, but is semantically checked as
6871     // if it were.
6872     DiagKind = 4;
6873   }
6874 
6875   if (DiagKind == -1)
6876     return false;
6877 
6878   if (Diagnose) {
6879     if (Field) {
6880       S.Diag(Field->getLocation(),
6881              diag::note_deleted_special_member_class_subobject)
6882         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6883         << Field << DiagKind << IsDtorCallInCtor;
6884     } else {
6885       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6886       S.Diag(Base->getBeginLoc(),
6887              diag::note_deleted_special_member_class_subobject)
6888           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6889           << Base->getType() << DiagKind << IsDtorCallInCtor;
6890     }
6891 
6892     if (DiagKind == 1)
6893       S.NoteDeletedFunction(Decl);
6894     // FIXME: Explain inaccessibility if DiagKind == 3.
6895   }
6896 
6897   return true;
6898 }
6899 
6900 /// Check whether we should delete a special member function due to having a
6901 /// direct or virtual base class or non-static data member of class type M.
6902 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6903     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6904   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6905   bool IsMutable = Field && Field->isMutable();
6906 
6907   // C++11 [class.ctor]p5:
6908   // -- any direct or virtual base class, or non-static data member with no
6909   //    brace-or-equal-initializer, has class type M (or array thereof) and
6910   //    either M has no default constructor or overload resolution as applied
6911   //    to M's default constructor results in an ambiguity or in a function
6912   //    that is deleted or inaccessible
6913   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6914   // -- a direct or virtual base class B that cannot be copied/moved because
6915   //    overload resolution, as applied to B's corresponding special member,
6916   //    results in an ambiguity or a function that is deleted or inaccessible
6917   //    from the defaulted special member
6918   // C++11 [class.dtor]p5:
6919   // -- any direct or virtual base class [...] has a type with a destructor
6920   //    that is deleted or inaccessible
6921   if (!(CSM == Sema::CXXDefaultConstructor &&
6922         Field && Field->hasInClassInitializer()) &&
6923       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6924                                    false))
6925     return true;
6926 
6927   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6928   // -- any direct or virtual base class or non-static data member has a
6929   //    type with a destructor that is deleted or inaccessible
6930   if (IsConstructor) {
6931     Sema::SpecialMemberOverloadResult SMOR =
6932         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6933                               false, false, false, false, false);
6934     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6935       return true;
6936   }
6937 
6938   return false;
6939 }
6940 
6941 /// Check whether we should delete a special member function due to the class
6942 /// having a particular direct or virtual base class.
6943 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6944   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6945   // If program is correct, BaseClass cannot be null, but if it is, the error
6946   // must be reported elsewhere.
6947   if (!BaseClass)
6948     return false;
6949   // If we have an inheriting constructor, check whether we're calling an
6950   // inherited constructor instead of a default constructor.
6951   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6952   if (auto *BaseCtor = SMOR.getMethod()) {
6953     // Note that we do not check access along this path; other than that,
6954     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6955     // FIXME: Check that the base has a usable destructor! Sink this into
6956     // shouldDeleteForClassSubobject.
6957     if (BaseCtor->isDeleted() && Diagnose) {
6958       S.Diag(Base->getBeginLoc(),
6959              diag::note_deleted_special_member_class_subobject)
6960           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6961           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
6962       S.NoteDeletedFunction(BaseCtor);
6963     }
6964     return BaseCtor->isDeleted();
6965   }
6966   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6967 }
6968 
6969 /// Check whether we should delete a special member function due to the class
6970 /// having a particular non-static data member.
6971 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6972   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6973   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6974 
6975   if (CSM == Sema::CXXDefaultConstructor) {
6976     // For a default constructor, all references must be initialized in-class
6977     // and, if a union, it must have a non-const member.
6978     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6979       if (Diagnose)
6980         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6981           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6982       return true;
6983     }
6984     // C++11 [class.ctor]p5: any non-variant non-static data member of
6985     // const-qualified type (or array thereof) with no
6986     // brace-or-equal-initializer does not have a user-provided default
6987     // constructor.
6988     if (!inUnion() && FieldType.isConstQualified() &&
6989         !FD->hasInClassInitializer() &&
6990         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6991       if (Diagnose)
6992         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6993           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6994       return true;
6995     }
6996 
6997     if (inUnion() && !FieldType.isConstQualified())
6998       AllFieldsAreConst = false;
6999   } else if (CSM == Sema::CXXCopyConstructor) {
7000     // For a copy constructor, data members must not be of rvalue reference
7001     // type.
7002     if (FieldType->isRValueReferenceType()) {
7003       if (Diagnose)
7004         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7005           << MD->getParent() << FD << FieldType;
7006       return true;
7007     }
7008   } else if (IsAssignment) {
7009     // For an assignment operator, data members must not be of reference type.
7010     if (FieldType->isReferenceType()) {
7011       if (Diagnose)
7012         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7013           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7014       return true;
7015     }
7016     if (!FieldRecord && FieldType.isConstQualified()) {
7017       // C++11 [class.copy]p23:
7018       // -- a non-static data member of const non-class type (or array thereof)
7019       if (Diagnose)
7020         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7021           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7022       return true;
7023     }
7024   }
7025 
7026   if (FieldRecord) {
7027     // Some additional restrictions exist on the variant members.
7028     if (!inUnion() && FieldRecord->isUnion() &&
7029         FieldRecord->isAnonymousStructOrUnion()) {
7030       bool AllVariantFieldsAreConst = true;
7031 
7032       // FIXME: Handle anonymous unions declared within anonymous unions.
7033       for (auto *UI : FieldRecord->fields()) {
7034         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7035 
7036         if (!UnionFieldType.isConstQualified())
7037           AllVariantFieldsAreConst = false;
7038 
7039         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7040         if (UnionFieldRecord &&
7041             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7042                                           UnionFieldType.getCVRQualifiers()))
7043           return true;
7044       }
7045 
7046       // At least one member in each anonymous union must be non-const
7047       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7048           !FieldRecord->field_empty()) {
7049         if (Diagnose)
7050           S.Diag(FieldRecord->getLocation(),
7051                  diag::note_deleted_default_ctor_all_const)
7052             << !!ICI << MD->getParent() << /*anonymous union*/1;
7053         return true;
7054       }
7055 
7056       // Don't check the implicit member of the anonymous union type.
7057       // This is technically non-conformant, but sanity demands it.
7058       return false;
7059     }
7060 
7061     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7062                                       FieldType.getCVRQualifiers()))
7063       return true;
7064   }
7065 
7066   return false;
7067 }
7068 
7069 /// C++11 [class.ctor] p5:
7070 ///   A defaulted default constructor for a class X is defined as deleted if
7071 /// X is a union and all of its variant members are of const-qualified type.
7072 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7073   // This is a silly definition, because it gives an empty union a deleted
7074   // default constructor. Don't do that.
7075   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7076     bool AnyFields = false;
7077     for (auto *F : MD->getParent()->fields())
7078       if ((AnyFields = !F->isUnnamedBitfield()))
7079         break;
7080     if (!AnyFields)
7081       return false;
7082     if (Diagnose)
7083       S.Diag(MD->getParent()->getLocation(),
7084              diag::note_deleted_default_ctor_all_const)
7085         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7086     return true;
7087   }
7088   return false;
7089 }
7090 
7091 /// Determine whether a defaulted special member function should be defined as
7092 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7093 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7094 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7095                                      InheritedConstructorInfo *ICI,
7096                                      bool Diagnose) {
7097   if (MD->isInvalidDecl())
7098     return false;
7099   CXXRecordDecl *RD = MD->getParent();
7100   assert(!RD->isDependentType() && "do deletion after instantiation");
7101   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7102     return false;
7103 
7104   // C++11 [expr.lambda.prim]p19:
7105   //   The closure type associated with a lambda-expression has a
7106   //   deleted (8.4.3) default constructor and a deleted copy
7107   //   assignment operator.
7108   if (RD->isLambda() &&
7109       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7110     if (Diagnose)
7111       Diag(RD->getLocation(), diag::note_lambda_decl);
7112     return true;
7113   }
7114 
7115   // For an anonymous struct or union, the copy and assignment special members
7116   // will never be used, so skip the check. For an anonymous union declared at
7117   // namespace scope, the constructor and destructor are used.
7118   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7119       RD->isAnonymousStructOrUnion())
7120     return false;
7121 
7122   // C++11 [class.copy]p7, p18:
7123   //   If the class definition declares a move constructor or move assignment
7124   //   operator, an implicitly declared copy constructor or copy assignment
7125   //   operator is defined as deleted.
7126   if (MD->isImplicit() &&
7127       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7128     CXXMethodDecl *UserDeclaredMove = nullptr;
7129 
7130     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7131     // deletion of the corresponding copy operation, not both copy operations.
7132     // MSVC 2015 has adopted the standards conforming behavior.
7133     bool DeletesOnlyMatchingCopy =
7134         getLangOpts().MSVCCompat &&
7135         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7136 
7137     if (RD->hasUserDeclaredMoveConstructor() &&
7138         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7139       if (!Diagnose) return true;
7140 
7141       // Find any user-declared move constructor.
7142       for (auto *I : RD->ctors()) {
7143         if (I->isMoveConstructor()) {
7144           UserDeclaredMove = I;
7145           break;
7146         }
7147       }
7148       assert(UserDeclaredMove);
7149     } else if (RD->hasUserDeclaredMoveAssignment() &&
7150                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7151       if (!Diagnose) return true;
7152 
7153       // Find any user-declared move assignment operator.
7154       for (auto *I : RD->methods()) {
7155         if (I->isMoveAssignmentOperator()) {
7156           UserDeclaredMove = I;
7157           break;
7158         }
7159       }
7160       assert(UserDeclaredMove);
7161     }
7162 
7163     if (UserDeclaredMove) {
7164       Diag(UserDeclaredMove->getLocation(),
7165            diag::note_deleted_copy_user_declared_move)
7166         << (CSM == CXXCopyAssignment) << RD
7167         << UserDeclaredMove->isMoveAssignmentOperator();
7168       return true;
7169     }
7170   }
7171 
7172   // Do access control from the special member function
7173   ContextRAII MethodContext(*this, MD);
7174 
7175   // C++11 [class.dtor]p5:
7176   // -- for a virtual destructor, lookup of the non-array deallocation function
7177   //    results in an ambiguity or in a function that is deleted or inaccessible
7178   if (CSM == CXXDestructor && MD->isVirtual()) {
7179     FunctionDecl *OperatorDelete = nullptr;
7180     DeclarationName Name =
7181       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7182     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7183                                  OperatorDelete, /*Diagnose*/false)) {
7184       if (Diagnose)
7185         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7186       return true;
7187     }
7188   }
7189 
7190   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7191 
7192   // Per DR1611, do not consider virtual bases of constructors of abstract
7193   // classes, since we are not going to construct them.
7194   // Per DR1658, do not consider virtual bases of destructors of abstract
7195   // classes either.
7196   // Per DR2180, for assignment operators we only assign (and thus only
7197   // consider) direct bases.
7198   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7199                                  : SMI.VisitPotentiallyConstructedBases))
7200     return true;
7201 
7202   if (SMI.shouldDeleteForAllConstMembers())
7203     return true;
7204 
7205   if (getLangOpts().CUDA) {
7206     // We should delete the special member in CUDA mode if target inference
7207     // failed.
7208     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7209                                                    Diagnose);
7210   }
7211 
7212   return false;
7213 }
7214 
7215 /// Perform lookup for a special member of the specified kind, and determine
7216 /// whether it is trivial. If the triviality can be determined without the
7217 /// lookup, skip it. This is intended for use when determining whether a
7218 /// special member of a containing object is trivial, and thus does not ever
7219 /// perform overload resolution for default constructors.
7220 ///
7221 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7222 /// member that was most likely to be intended to be trivial, if any.
7223 ///
7224 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7225 /// determine whether the special member is trivial.
7226 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7227                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7228                                      bool ConstRHS,
7229                                      Sema::TrivialABIHandling TAH,
7230                                      CXXMethodDecl **Selected) {
7231   if (Selected)
7232     *Selected = nullptr;
7233 
7234   switch (CSM) {
7235   case Sema::CXXInvalid:
7236     llvm_unreachable("not a special member");
7237 
7238   case Sema::CXXDefaultConstructor:
7239     // C++11 [class.ctor]p5:
7240     //   A default constructor is trivial if:
7241     //    - all the [direct subobjects] have trivial default constructors
7242     //
7243     // Note, no overload resolution is performed in this case.
7244     if (RD->hasTrivialDefaultConstructor())
7245       return true;
7246 
7247     if (Selected) {
7248       // If there's a default constructor which could have been trivial, dig it
7249       // out. Otherwise, if there's any user-provided default constructor, point
7250       // to that as an example of why there's not a trivial one.
7251       CXXConstructorDecl *DefCtor = nullptr;
7252       if (RD->needsImplicitDefaultConstructor())
7253         S.DeclareImplicitDefaultConstructor(RD);
7254       for (auto *CI : RD->ctors()) {
7255         if (!CI->isDefaultConstructor())
7256           continue;
7257         DefCtor = CI;
7258         if (!DefCtor->isUserProvided())
7259           break;
7260       }
7261 
7262       *Selected = DefCtor;
7263     }
7264 
7265     return false;
7266 
7267   case Sema::CXXDestructor:
7268     // C++11 [class.dtor]p5:
7269     //   A destructor is trivial if:
7270     //    - all the direct [subobjects] have trivial destructors
7271     if (RD->hasTrivialDestructor() ||
7272         (TAH == Sema::TAH_ConsiderTrivialABI &&
7273          RD->hasTrivialDestructorForCall()))
7274       return true;
7275 
7276     if (Selected) {
7277       if (RD->needsImplicitDestructor())
7278         S.DeclareImplicitDestructor(RD);
7279       *Selected = RD->getDestructor();
7280     }
7281 
7282     return false;
7283 
7284   case Sema::CXXCopyConstructor:
7285     // C++11 [class.copy]p12:
7286     //   A copy constructor is trivial if:
7287     //    - the constructor selected to copy each direct [subobject] is trivial
7288     if (RD->hasTrivialCopyConstructor() ||
7289         (TAH == Sema::TAH_ConsiderTrivialABI &&
7290          RD->hasTrivialCopyConstructorForCall())) {
7291       if (Quals == Qualifiers::Const)
7292         // We must either select the trivial copy constructor or reach an
7293         // ambiguity; no need to actually perform overload resolution.
7294         return true;
7295     } else if (!Selected) {
7296       return false;
7297     }
7298     // In C++98, we are not supposed to perform overload resolution here, but we
7299     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7300     // cases like B as having a non-trivial copy constructor:
7301     //   struct A { template<typename T> A(T&); };
7302     //   struct B { mutable A a; };
7303     goto NeedOverloadResolution;
7304 
7305   case Sema::CXXCopyAssignment:
7306     // C++11 [class.copy]p25:
7307     //   A copy assignment operator is trivial if:
7308     //    - the assignment operator selected to copy each direct [subobject] is
7309     //      trivial
7310     if (RD->hasTrivialCopyAssignment()) {
7311       if (Quals == Qualifiers::Const)
7312         return true;
7313     } else if (!Selected) {
7314       return false;
7315     }
7316     // In C++98, we are not supposed to perform overload resolution here, but we
7317     // treat that as a language defect.
7318     goto NeedOverloadResolution;
7319 
7320   case Sema::CXXMoveConstructor:
7321   case Sema::CXXMoveAssignment:
7322   NeedOverloadResolution:
7323     Sema::SpecialMemberOverloadResult SMOR =
7324         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7325 
7326     // The standard doesn't describe how to behave if the lookup is ambiguous.
7327     // We treat it as not making the member non-trivial, just like the standard
7328     // mandates for the default constructor. This should rarely matter, because
7329     // the member will also be deleted.
7330     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7331       return true;
7332 
7333     if (!SMOR.getMethod()) {
7334       assert(SMOR.getKind() ==
7335              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7336       return false;
7337     }
7338 
7339     // We deliberately don't check if we found a deleted special member. We're
7340     // not supposed to!
7341     if (Selected)
7342       *Selected = SMOR.getMethod();
7343 
7344     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7345         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7346       return SMOR.getMethod()->isTrivialForCall();
7347     return SMOR.getMethod()->isTrivial();
7348   }
7349 
7350   llvm_unreachable("unknown special method kind");
7351 }
7352 
7353 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7354   for (auto *CI : RD->ctors())
7355     if (!CI->isImplicit())
7356       return CI;
7357 
7358   // Look for constructor templates.
7359   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7360   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7361     if (CXXConstructorDecl *CD =
7362           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7363       return CD;
7364   }
7365 
7366   return nullptr;
7367 }
7368 
7369 /// The kind of subobject we are checking for triviality. The values of this
7370 /// enumeration are used in diagnostics.
7371 enum TrivialSubobjectKind {
7372   /// The subobject is a base class.
7373   TSK_BaseClass,
7374   /// The subobject is a non-static data member.
7375   TSK_Field,
7376   /// The object is actually the complete object.
7377   TSK_CompleteObject
7378 };
7379 
7380 /// Check whether the special member selected for a given type would be trivial.
7381 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7382                                       QualType SubType, bool ConstRHS,
7383                                       Sema::CXXSpecialMember CSM,
7384                                       TrivialSubobjectKind Kind,
7385                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7386   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7387   if (!SubRD)
7388     return true;
7389 
7390   CXXMethodDecl *Selected;
7391   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7392                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7393     return true;
7394 
7395   if (Diagnose) {
7396     if (ConstRHS)
7397       SubType.addConst();
7398 
7399     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7400       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7401         << Kind << SubType.getUnqualifiedType();
7402       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7403         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7404     } else if (!Selected)
7405       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7406         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7407     else if (Selected->isUserProvided()) {
7408       if (Kind == TSK_CompleteObject)
7409         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7410           << Kind << SubType.getUnqualifiedType() << CSM;
7411       else {
7412         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7413           << Kind << SubType.getUnqualifiedType() << CSM;
7414         S.Diag(Selected->getLocation(), diag::note_declared_at);
7415       }
7416     } else {
7417       if (Kind != TSK_CompleteObject)
7418         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7419           << Kind << SubType.getUnqualifiedType() << CSM;
7420 
7421       // Explain why the defaulted or deleted special member isn't trivial.
7422       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7423                                Diagnose);
7424     }
7425   }
7426 
7427   return false;
7428 }
7429 
7430 /// Check whether the members of a class type allow a special member to be
7431 /// trivial.
7432 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7433                                      Sema::CXXSpecialMember CSM,
7434                                      bool ConstArg,
7435                                      Sema::TrivialABIHandling TAH,
7436                                      bool Diagnose) {
7437   for (const auto *FI : RD->fields()) {
7438     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7439       continue;
7440 
7441     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7442 
7443     // Pretend anonymous struct or union members are members of this class.
7444     if (FI->isAnonymousStructOrUnion()) {
7445       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7446                                     CSM, ConstArg, TAH, Diagnose))
7447         return false;
7448       continue;
7449     }
7450 
7451     // C++11 [class.ctor]p5:
7452     //   A default constructor is trivial if [...]
7453     //    -- no non-static data member of its class has a
7454     //       brace-or-equal-initializer
7455     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7456       if (Diagnose)
7457         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7458       return false;
7459     }
7460 
7461     // Objective C ARC 4.3.5:
7462     //   [...] nontrivally ownership-qualified types are [...] not trivially
7463     //   default constructible, copy constructible, move constructible, copy
7464     //   assignable, move assignable, or destructible [...]
7465     if (FieldType.hasNonTrivialObjCLifetime()) {
7466       if (Diagnose)
7467         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7468           << RD << FieldType.getObjCLifetime();
7469       return false;
7470     }
7471 
7472     bool ConstRHS = ConstArg && !FI->isMutable();
7473     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7474                                    CSM, TSK_Field, TAH, Diagnose))
7475       return false;
7476   }
7477 
7478   return true;
7479 }
7480 
7481 /// Diagnose why the specified class does not have a trivial special member of
7482 /// the given kind.
7483 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7484   QualType Ty = Context.getRecordType(RD);
7485 
7486   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7487   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7488                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7489                             /*Diagnose*/true);
7490 }
7491 
7492 /// Determine whether a defaulted or deleted special member function is trivial,
7493 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7494 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7495 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7496                                   TrivialABIHandling TAH, bool Diagnose) {
7497   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7498 
7499   CXXRecordDecl *RD = MD->getParent();
7500 
7501   bool ConstArg = false;
7502 
7503   // C++11 [class.copy]p12, p25: [DR1593]
7504   //   A [special member] is trivial if [...] its parameter-type-list is
7505   //   equivalent to the parameter-type-list of an implicit declaration [...]
7506   switch (CSM) {
7507   case CXXDefaultConstructor:
7508   case CXXDestructor:
7509     // Trivial default constructors and destructors cannot have parameters.
7510     break;
7511 
7512   case CXXCopyConstructor:
7513   case CXXCopyAssignment: {
7514     // Trivial copy operations always have const, non-volatile parameter types.
7515     ConstArg = true;
7516     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7517     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7518     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7519       if (Diagnose)
7520         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7521           << Param0->getSourceRange() << Param0->getType()
7522           << Context.getLValueReferenceType(
7523                Context.getRecordType(RD).withConst());
7524       return false;
7525     }
7526     break;
7527   }
7528 
7529   case CXXMoveConstructor:
7530   case CXXMoveAssignment: {
7531     // Trivial move operations always have non-cv-qualified parameters.
7532     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7533     const RValueReferenceType *RT =
7534       Param0->getType()->getAs<RValueReferenceType>();
7535     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7536       if (Diagnose)
7537         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7538           << Param0->getSourceRange() << Param0->getType()
7539           << Context.getRValueReferenceType(Context.getRecordType(RD));
7540       return false;
7541     }
7542     break;
7543   }
7544 
7545   case CXXInvalid:
7546     llvm_unreachable("not a special member");
7547   }
7548 
7549   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7550     if (Diagnose)
7551       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7552            diag::note_nontrivial_default_arg)
7553         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7554     return false;
7555   }
7556   if (MD->isVariadic()) {
7557     if (Diagnose)
7558       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7559     return false;
7560   }
7561 
7562   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7563   //   A copy/move [constructor or assignment operator] is trivial if
7564   //    -- the [member] selected to copy/move each direct base class subobject
7565   //       is trivial
7566   //
7567   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7568   //   A [default constructor or destructor] is trivial if
7569   //    -- all the direct base classes have trivial [default constructors or
7570   //       destructors]
7571   for (const auto &BI : RD->bases())
7572     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7573                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7574       return false;
7575 
7576   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7577   //   A copy/move [constructor or assignment operator] for a class X is
7578   //   trivial if
7579   //    -- for each non-static data member of X that is of class type (or array
7580   //       thereof), the constructor selected to copy/move that member is
7581   //       trivial
7582   //
7583   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7584   //   A [default constructor or destructor] is trivial if
7585   //    -- for all of the non-static data members of its class that are of class
7586   //       type (or array thereof), each such class has a trivial [default
7587   //       constructor or destructor]
7588   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7589     return false;
7590 
7591   // C++11 [class.dtor]p5:
7592   //   A destructor is trivial if [...]
7593   //    -- the destructor is not virtual
7594   if (CSM == CXXDestructor && MD->isVirtual()) {
7595     if (Diagnose)
7596       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7597     return false;
7598   }
7599 
7600   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7601   //   A [special member] for class X is trivial if [...]
7602   //    -- class X has no virtual functions and no virtual base classes
7603   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7604     if (!Diagnose)
7605       return false;
7606 
7607     if (RD->getNumVBases()) {
7608       // Check for virtual bases. We already know that the corresponding
7609       // member in all bases is trivial, so vbases must all be direct.
7610       CXXBaseSpecifier &BS = *RD->vbases_begin();
7611       assert(BS.isVirtual());
7612       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7613       return false;
7614     }
7615 
7616     // Must have a virtual method.
7617     for (const auto *MI : RD->methods()) {
7618       if (MI->isVirtual()) {
7619         SourceLocation MLoc = MI->getBeginLoc();
7620         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7621         return false;
7622       }
7623     }
7624 
7625     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7626   }
7627 
7628   // Looks like it's trivial!
7629   return true;
7630 }
7631 
7632 namespace {
7633 struct FindHiddenVirtualMethod {
7634   Sema *S;
7635   CXXMethodDecl *Method;
7636   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7637   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7638 
7639 private:
7640   /// Check whether any most overriden method from MD in Methods
7641   static bool CheckMostOverridenMethods(
7642       const CXXMethodDecl *MD,
7643       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7644     if (MD->size_overridden_methods() == 0)
7645       return Methods.count(MD->getCanonicalDecl());
7646     for (const CXXMethodDecl *O : MD->overridden_methods())
7647       if (CheckMostOverridenMethods(O, Methods))
7648         return true;
7649     return false;
7650   }
7651 
7652 public:
7653   /// Member lookup function that determines whether a given C++
7654   /// method overloads virtual methods in a base class without overriding any,
7655   /// to be used with CXXRecordDecl::lookupInBases().
7656   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7657     RecordDecl *BaseRecord =
7658         Specifier->getType()->getAs<RecordType>()->getDecl();
7659 
7660     DeclarationName Name = Method->getDeclName();
7661     assert(Name.getNameKind() == DeclarationName::Identifier);
7662 
7663     bool foundSameNameMethod = false;
7664     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7665     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7666          Path.Decls = Path.Decls.slice(1)) {
7667       NamedDecl *D = Path.Decls.front();
7668       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7669         MD = MD->getCanonicalDecl();
7670         foundSameNameMethod = true;
7671         // Interested only in hidden virtual methods.
7672         if (!MD->isVirtual())
7673           continue;
7674         // If the method we are checking overrides a method from its base
7675         // don't warn about the other overloaded methods. Clang deviates from
7676         // GCC by only diagnosing overloads of inherited virtual functions that
7677         // do not override any other virtual functions in the base. GCC's
7678         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7679         // function from a base class. These cases may be better served by a
7680         // warning (not specific to virtual functions) on call sites when the
7681         // call would select a different function from the base class, were it
7682         // visible.
7683         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7684         if (!S->IsOverload(Method, MD, false))
7685           return true;
7686         // Collect the overload only if its hidden.
7687         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7688           overloadedMethods.push_back(MD);
7689       }
7690     }
7691 
7692     if (foundSameNameMethod)
7693       OverloadedMethods.append(overloadedMethods.begin(),
7694                                overloadedMethods.end());
7695     return foundSameNameMethod;
7696   }
7697 };
7698 } // end anonymous namespace
7699 
7700 /// Add the most overriden methods from MD to Methods
7701 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7702                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7703   if (MD->size_overridden_methods() == 0)
7704     Methods.insert(MD->getCanonicalDecl());
7705   else
7706     for (const CXXMethodDecl *O : MD->overridden_methods())
7707       AddMostOverridenMethods(O, Methods);
7708 }
7709 
7710 /// Check if a method overloads virtual methods in a base class without
7711 /// overriding any.
7712 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7713                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7714   if (!MD->getDeclName().isIdentifier())
7715     return;
7716 
7717   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7718                      /*bool RecordPaths=*/false,
7719                      /*bool DetectVirtual=*/false);
7720   FindHiddenVirtualMethod FHVM;
7721   FHVM.Method = MD;
7722   FHVM.S = this;
7723 
7724   // Keep the base methods that were overriden or introduced in the subclass
7725   // by 'using' in a set. A base method not in this set is hidden.
7726   CXXRecordDecl *DC = MD->getParent();
7727   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7728   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7729     NamedDecl *ND = *I;
7730     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7731       ND = shad->getTargetDecl();
7732     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7733       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7734   }
7735 
7736   if (DC->lookupInBases(FHVM, Paths))
7737     OverloadedMethods = FHVM.OverloadedMethods;
7738 }
7739 
7740 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7741                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7742   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7743     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7744     PartialDiagnostic PD = PDiag(
7745          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7746     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7747     Diag(overloadedMD->getLocation(), PD);
7748   }
7749 }
7750 
7751 /// Diagnose methods which overload virtual methods in a base class
7752 /// without overriding any.
7753 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7754   if (MD->isInvalidDecl())
7755     return;
7756 
7757   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7758     return;
7759 
7760   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7761   FindHiddenVirtualMethods(MD, OverloadedMethods);
7762   if (!OverloadedMethods.empty()) {
7763     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7764       << MD << (OverloadedMethods.size() > 1);
7765 
7766     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7767   }
7768 }
7769 
7770 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7771   auto PrintDiagAndRemoveAttr = [&]() {
7772     // No diagnostics if this is a template instantiation.
7773     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7774       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7775            diag::ext_cannot_use_trivial_abi) << &RD;
7776     RD.dropAttr<TrivialABIAttr>();
7777   };
7778 
7779   // Ill-formed if the struct has virtual functions.
7780   if (RD.isPolymorphic()) {
7781     PrintDiagAndRemoveAttr();
7782     return;
7783   }
7784 
7785   for (const auto &B : RD.bases()) {
7786     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7787     // virtual base.
7788     if ((!B.getType()->isDependentType() &&
7789          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7790         B.isVirtual()) {
7791       PrintDiagAndRemoveAttr();
7792       return;
7793     }
7794   }
7795 
7796   for (const auto *FD : RD.fields()) {
7797     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7798     // non-trivial for the purpose of calls.
7799     QualType FT = FD->getType();
7800     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7801       PrintDiagAndRemoveAttr();
7802       return;
7803     }
7804 
7805     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7806       if (!RT->isDependentType() &&
7807           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7808         PrintDiagAndRemoveAttr();
7809         return;
7810       }
7811   }
7812 }
7813 
7814 void Sema::ActOnFinishCXXMemberSpecification(
7815     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7816     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7817   if (!TagDecl)
7818     return;
7819 
7820   AdjustDeclIfTemplate(TagDecl);
7821 
7822   for (const ParsedAttr &AL : AttrList) {
7823     if (AL.getKind() != ParsedAttr::AT_Visibility)
7824       continue;
7825     AL.setInvalid();
7826     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7827         << AL.getName();
7828   }
7829 
7830   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7831               // strict aliasing violation!
7832               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7833               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7834 
7835   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7836 }
7837 
7838 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7839 /// special functions, such as the default constructor, copy
7840 /// constructor, or destructor, to the given C++ class (C++
7841 /// [special]p1).  This routine can only be executed just before the
7842 /// definition of the class is complete.
7843 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7844   if (ClassDecl->needsImplicitDefaultConstructor()) {
7845     ++ASTContext::NumImplicitDefaultConstructors;
7846 
7847     if (ClassDecl->hasInheritedConstructor())
7848       DeclareImplicitDefaultConstructor(ClassDecl);
7849   }
7850 
7851   if (ClassDecl->needsImplicitCopyConstructor()) {
7852     ++ASTContext::NumImplicitCopyConstructors;
7853 
7854     // If the properties or semantics of the copy constructor couldn't be
7855     // determined while the class was being declared, force a declaration
7856     // of it now.
7857     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7858         ClassDecl->hasInheritedConstructor())
7859       DeclareImplicitCopyConstructor(ClassDecl);
7860     // For the MS ABI we need to know whether the copy ctor is deleted. A
7861     // prerequisite for deleting the implicit copy ctor is that the class has a
7862     // move ctor or move assignment that is either user-declared or whose
7863     // semantics are inherited from a subobject. FIXME: We should provide a more
7864     // direct way for CodeGen to ask whether the constructor was deleted.
7865     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7866              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7867               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7868               ClassDecl->hasUserDeclaredMoveAssignment() ||
7869               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7870       DeclareImplicitCopyConstructor(ClassDecl);
7871   }
7872 
7873   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7874     ++ASTContext::NumImplicitMoveConstructors;
7875 
7876     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7877         ClassDecl->hasInheritedConstructor())
7878       DeclareImplicitMoveConstructor(ClassDecl);
7879   }
7880 
7881   if (ClassDecl->needsImplicitCopyAssignment()) {
7882     ++ASTContext::NumImplicitCopyAssignmentOperators;
7883 
7884     // If we have a dynamic class, then the copy assignment operator may be
7885     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7886     // it shows up in the right place in the vtable and that we diagnose
7887     // problems with the implicit exception specification.
7888     if (ClassDecl->isDynamicClass() ||
7889         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7890         ClassDecl->hasInheritedAssignment())
7891       DeclareImplicitCopyAssignment(ClassDecl);
7892   }
7893 
7894   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7895     ++ASTContext::NumImplicitMoveAssignmentOperators;
7896 
7897     // Likewise for the move assignment operator.
7898     if (ClassDecl->isDynamicClass() ||
7899         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7900         ClassDecl->hasInheritedAssignment())
7901       DeclareImplicitMoveAssignment(ClassDecl);
7902   }
7903 
7904   if (ClassDecl->needsImplicitDestructor()) {
7905     ++ASTContext::NumImplicitDestructors;
7906 
7907     // If we have a dynamic class, then the destructor may be virtual, so we
7908     // have to declare the destructor immediately. This ensures that, e.g., it
7909     // shows up in the right place in the vtable and that we diagnose problems
7910     // with the implicit exception specification.
7911     if (ClassDecl->isDynamicClass() ||
7912         ClassDecl->needsOverloadResolutionForDestructor())
7913       DeclareImplicitDestructor(ClassDecl);
7914   }
7915 }
7916 
7917 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7918   if (!D)
7919     return 0;
7920 
7921   // The order of template parameters is not important here. All names
7922   // get added to the same scope.
7923   SmallVector<TemplateParameterList *, 4> ParameterLists;
7924 
7925   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7926     D = TD->getTemplatedDecl();
7927 
7928   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7929     ParameterLists.push_back(PSD->getTemplateParameters());
7930 
7931   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7932     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7933       ParameterLists.push_back(DD->getTemplateParameterList(i));
7934 
7935     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7936       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7937         ParameterLists.push_back(FTD->getTemplateParameters());
7938     }
7939   }
7940 
7941   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7942     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7943       ParameterLists.push_back(TD->getTemplateParameterList(i));
7944 
7945     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7946       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7947         ParameterLists.push_back(CTD->getTemplateParameters());
7948     }
7949   }
7950 
7951   unsigned Count = 0;
7952   for (TemplateParameterList *Params : ParameterLists) {
7953     if (Params->size() > 0)
7954       // Ignore explicit specializations; they don't contribute to the template
7955       // depth.
7956       ++Count;
7957     for (NamedDecl *Param : *Params) {
7958       if (Param->getDeclName()) {
7959         S->AddDecl(Param);
7960         IdResolver.AddDecl(Param);
7961       }
7962     }
7963   }
7964 
7965   return Count;
7966 }
7967 
7968 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7969   if (!RecordD) return;
7970   AdjustDeclIfTemplate(RecordD);
7971   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7972   PushDeclContext(S, Record);
7973 }
7974 
7975 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7976   if (!RecordD) return;
7977   PopDeclContext();
7978 }
7979 
7980 /// This is used to implement the constant expression evaluation part of the
7981 /// attribute enable_if extension. There is nothing in standard C++ which would
7982 /// require reentering parameters.
7983 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7984   if (!Param)
7985     return;
7986 
7987   S->AddDecl(Param);
7988   if (Param->getDeclName())
7989     IdResolver.AddDecl(Param);
7990 }
7991 
7992 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7993 /// parsing a top-level (non-nested) C++ class, and we are now
7994 /// parsing those parts of the given Method declaration that could
7995 /// not be parsed earlier (C++ [class.mem]p2), such as default
7996 /// arguments. This action should enter the scope of the given
7997 /// Method declaration as if we had just parsed the qualified method
7998 /// name. However, it should not bring the parameters into scope;
7999 /// that will be performed by ActOnDelayedCXXMethodParameter.
8000 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8001 }
8002 
8003 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8004 /// C++ method declaration. We're (re-)introducing the given
8005 /// function parameter into scope for use in parsing later parts of
8006 /// the method declaration. For example, we could see an
8007 /// ActOnParamDefaultArgument event for this parameter.
8008 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8009   if (!ParamD)
8010     return;
8011 
8012   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8013 
8014   // If this parameter has an unparsed default argument, clear it out
8015   // to make way for the parsed default argument.
8016   if (Param->hasUnparsedDefaultArg())
8017     Param->setDefaultArg(nullptr);
8018 
8019   S->AddDecl(Param);
8020   if (Param->getDeclName())
8021     IdResolver.AddDecl(Param);
8022 }
8023 
8024 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8025 /// processing the delayed method declaration for Method. The method
8026 /// declaration is now considered finished. There may be a separate
8027 /// ActOnStartOfFunctionDef action later (not necessarily
8028 /// immediately!) for this method, if it was also defined inside the
8029 /// class body.
8030 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8031   if (!MethodD)
8032     return;
8033 
8034   AdjustDeclIfTemplate(MethodD);
8035 
8036   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8037 
8038   // Now that we have our default arguments, check the constructor
8039   // again. It could produce additional diagnostics or affect whether
8040   // the class has implicitly-declared destructors, among other
8041   // things.
8042   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8043     CheckConstructor(Constructor);
8044 
8045   // Check the default arguments, which we may have added.
8046   if (!Method->isInvalidDecl())
8047     CheckCXXDefaultArguments(Method);
8048 }
8049 
8050 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8051 /// the well-formedness of the constructor declarator @p D with type @p
8052 /// R. If there are any errors in the declarator, this routine will
8053 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8054 /// will be updated to reflect a well-formed type for the constructor and
8055 /// returned.
8056 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8057                                           StorageClass &SC) {
8058   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8059 
8060   // C++ [class.ctor]p3:
8061   //   A constructor shall not be virtual (10.3) or static (9.4). A
8062   //   constructor can be invoked for a const, volatile or const
8063   //   volatile object. A constructor shall not be declared const,
8064   //   volatile, or const volatile (9.3.2).
8065   if (isVirtual) {
8066     if (!D.isInvalidType())
8067       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8068         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8069         << SourceRange(D.getIdentifierLoc());
8070     D.setInvalidType();
8071   }
8072   if (SC == SC_Static) {
8073     if (!D.isInvalidType())
8074       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8075         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8076         << SourceRange(D.getIdentifierLoc());
8077     D.setInvalidType();
8078     SC = SC_None;
8079   }
8080 
8081   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8082     diagnoseIgnoredQualifiers(
8083         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8084         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8085         D.getDeclSpec().getRestrictSpecLoc(),
8086         D.getDeclSpec().getAtomicSpecLoc());
8087     D.setInvalidType();
8088   }
8089 
8090   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8091   if (FTI.TypeQuals != 0) {
8092     if (FTI.TypeQuals & Qualifiers::Const)
8093       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8094         << "const" << SourceRange(D.getIdentifierLoc());
8095     if (FTI.TypeQuals & Qualifiers::Volatile)
8096       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8097         << "volatile" << SourceRange(D.getIdentifierLoc());
8098     if (FTI.TypeQuals & Qualifiers::Restrict)
8099       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8100         << "restrict" << SourceRange(D.getIdentifierLoc());
8101     D.setInvalidType();
8102   }
8103 
8104   // C++0x [class.ctor]p4:
8105   //   A constructor shall not be declared with a ref-qualifier.
8106   if (FTI.hasRefQualifier()) {
8107     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8108       << FTI.RefQualifierIsLValueRef
8109       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8110     D.setInvalidType();
8111   }
8112 
8113   // Rebuild the function type "R" without any type qualifiers (in
8114   // case any of the errors above fired) and with "void" as the
8115   // return type, since constructors don't have return types.
8116   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8117   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8118     return R;
8119 
8120   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8121   EPI.TypeQuals = 0;
8122   EPI.RefQualifier = RQ_None;
8123 
8124   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8125 }
8126 
8127 /// CheckConstructor - Checks a fully-formed constructor for
8128 /// well-formedness, issuing any diagnostics required. Returns true if
8129 /// the constructor declarator is invalid.
8130 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8131   CXXRecordDecl *ClassDecl
8132     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8133   if (!ClassDecl)
8134     return Constructor->setInvalidDecl();
8135 
8136   // C++ [class.copy]p3:
8137   //   A declaration of a constructor for a class X is ill-formed if
8138   //   its first parameter is of type (optionally cv-qualified) X and
8139   //   either there are no other parameters or else all other
8140   //   parameters have default arguments.
8141   if (!Constructor->isInvalidDecl() &&
8142       ((Constructor->getNumParams() == 1) ||
8143        (Constructor->getNumParams() > 1 &&
8144         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8145       Constructor->getTemplateSpecializationKind()
8146                                               != TSK_ImplicitInstantiation) {
8147     QualType ParamType = Constructor->getParamDecl(0)->getType();
8148     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8149     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8150       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8151       const char *ConstRef
8152         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8153                                                         : " const &";
8154       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8155         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8156 
8157       // FIXME: Rather that making the constructor invalid, we should endeavor
8158       // to fix the type.
8159       Constructor->setInvalidDecl();
8160     }
8161   }
8162 }
8163 
8164 /// CheckDestructor - Checks a fully-formed destructor definition for
8165 /// well-formedness, issuing any diagnostics required.  Returns true
8166 /// on error.
8167 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8168   CXXRecordDecl *RD = Destructor->getParent();
8169 
8170   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8171     SourceLocation Loc;
8172 
8173     if (!Destructor->isImplicit())
8174       Loc = Destructor->getLocation();
8175     else
8176       Loc = RD->getLocation();
8177 
8178     // If we have a virtual destructor, look up the deallocation function
8179     if (FunctionDecl *OperatorDelete =
8180             FindDeallocationFunctionForDestructor(Loc, RD)) {
8181       Expr *ThisArg = nullptr;
8182 
8183       // If the notional 'delete this' expression requires a non-trivial
8184       // conversion from 'this' to the type of a destroying operator delete's
8185       // first parameter, perform that conversion now.
8186       if (OperatorDelete->isDestroyingOperatorDelete()) {
8187         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8188         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8189           // C++ [class.dtor]p13:
8190           //   ... as if for the expression 'delete this' appearing in a
8191           //   non-virtual destructor of the destructor's class.
8192           ContextRAII SwitchContext(*this, Destructor);
8193           ExprResult This =
8194               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8195           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8196           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8197           if (This.isInvalid()) {
8198             // FIXME: Register this as a context note so that it comes out
8199             // in the right order.
8200             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8201             return true;
8202           }
8203           ThisArg = This.get();
8204         }
8205       }
8206 
8207       MarkFunctionReferenced(Loc, OperatorDelete);
8208       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8209     }
8210   }
8211 
8212   return false;
8213 }
8214 
8215 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8216 /// the well-formednes of the destructor declarator @p D with type @p
8217 /// R. If there are any errors in the declarator, this routine will
8218 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8219 /// will be updated to reflect a well-formed type for the destructor and
8220 /// returned.
8221 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8222                                          StorageClass& SC) {
8223   // C++ [class.dtor]p1:
8224   //   [...] A typedef-name that names a class is a class-name
8225   //   (7.1.3); however, a typedef-name that names a class shall not
8226   //   be used as the identifier in the declarator for a destructor
8227   //   declaration.
8228   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8229   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8230     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8231       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8232   else if (const TemplateSpecializationType *TST =
8233              DeclaratorType->getAs<TemplateSpecializationType>())
8234     if (TST->isTypeAlias())
8235       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8236         << DeclaratorType << 1;
8237 
8238   // C++ [class.dtor]p2:
8239   //   A destructor is used to destroy objects of its class type. A
8240   //   destructor takes no parameters, and no return type can be
8241   //   specified for it (not even void). The address of a destructor
8242   //   shall not be taken. A destructor shall not be static. A
8243   //   destructor can be invoked for a const, volatile or const
8244   //   volatile object. A destructor shall not be declared const,
8245   //   volatile or const volatile (9.3.2).
8246   if (SC == SC_Static) {
8247     if (!D.isInvalidType())
8248       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8249         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8250         << SourceRange(D.getIdentifierLoc())
8251         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8252 
8253     SC = SC_None;
8254   }
8255   if (!D.isInvalidType()) {
8256     // Destructors don't have return types, but the parser will
8257     // happily parse something like:
8258     //
8259     //   class X {
8260     //     float ~X();
8261     //   };
8262     //
8263     // The return type will be eliminated later.
8264     if (D.getDeclSpec().hasTypeSpecifier())
8265       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8266         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8267         << SourceRange(D.getIdentifierLoc());
8268     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8269       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8270                                 SourceLocation(),
8271                                 D.getDeclSpec().getConstSpecLoc(),
8272                                 D.getDeclSpec().getVolatileSpecLoc(),
8273                                 D.getDeclSpec().getRestrictSpecLoc(),
8274                                 D.getDeclSpec().getAtomicSpecLoc());
8275       D.setInvalidType();
8276     }
8277   }
8278 
8279   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8280   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8281     if (FTI.TypeQuals & Qualifiers::Const)
8282       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8283         << "const" << SourceRange(D.getIdentifierLoc());
8284     if (FTI.TypeQuals & Qualifiers::Volatile)
8285       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8286         << "volatile" << SourceRange(D.getIdentifierLoc());
8287     if (FTI.TypeQuals & Qualifiers::Restrict)
8288       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8289         << "restrict" << SourceRange(D.getIdentifierLoc());
8290     D.setInvalidType();
8291   }
8292 
8293   // C++0x [class.dtor]p2:
8294   //   A destructor shall not be declared with a ref-qualifier.
8295   if (FTI.hasRefQualifier()) {
8296     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8297       << FTI.RefQualifierIsLValueRef
8298       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8299     D.setInvalidType();
8300   }
8301 
8302   // Make sure we don't have any parameters.
8303   if (FTIHasNonVoidParameters(FTI)) {
8304     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8305 
8306     // Delete the parameters.
8307     FTI.freeParams();
8308     D.setInvalidType();
8309   }
8310 
8311   // Make sure the destructor isn't variadic.
8312   if (FTI.isVariadic) {
8313     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8314     D.setInvalidType();
8315   }
8316 
8317   // Rebuild the function type "R" without any type qualifiers or
8318   // parameters (in case any of the errors above fired) and with
8319   // "void" as the return type, since destructors don't have return
8320   // types.
8321   if (!D.isInvalidType())
8322     return R;
8323 
8324   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8325   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8326   EPI.Variadic = false;
8327   EPI.TypeQuals = 0;
8328   EPI.RefQualifier = RQ_None;
8329   return Context.getFunctionType(Context.VoidTy, None, EPI);
8330 }
8331 
8332 static void extendLeft(SourceRange &R, SourceRange Before) {
8333   if (Before.isInvalid())
8334     return;
8335   R.setBegin(Before.getBegin());
8336   if (R.getEnd().isInvalid())
8337     R.setEnd(Before.getEnd());
8338 }
8339 
8340 static void extendRight(SourceRange &R, SourceRange After) {
8341   if (After.isInvalid())
8342     return;
8343   if (R.getBegin().isInvalid())
8344     R.setBegin(After.getBegin());
8345   R.setEnd(After.getEnd());
8346 }
8347 
8348 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8349 /// well-formednes of the conversion function declarator @p D with
8350 /// type @p R. If there are any errors in the declarator, this routine
8351 /// will emit diagnostics and return true. Otherwise, it will return
8352 /// false. Either way, the type @p R will be updated to reflect a
8353 /// well-formed type for the conversion operator.
8354 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8355                                      StorageClass& SC) {
8356   // C++ [class.conv.fct]p1:
8357   //   Neither parameter types nor return type can be specified. The
8358   //   type of a conversion function (8.3.5) is "function taking no
8359   //   parameter returning conversion-type-id."
8360   if (SC == SC_Static) {
8361     if (!D.isInvalidType())
8362       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8363         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8364         << D.getName().getSourceRange();
8365     D.setInvalidType();
8366     SC = SC_None;
8367   }
8368 
8369   TypeSourceInfo *ConvTSI = nullptr;
8370   QualType ConvType =
8371       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8372 
8373   const DeclSpec &DS = D.getDeclSpec();
8374   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8375     // Conversion functions don't have return types, but the parser will
8376     // happily parse something like:
8377     //
8378     //   class X {
8379     //     float operator bool();
8380     //   };
8381     //
8382     // The return type will be changed later anyway.
8383     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8384       << SourceRange(DS.getTypeSpecTypeLoc())
8385       << SourceRange(D.getIdentifierLoc());
8386     D.setInvalidType();
8387   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8388     // It's also plausible that the user writes type qualifiers in the wrong
8389     // place, such as:
8390     //   struct S { const operator int(); };
8391     // FIXME: we could provide a fixit to move the qualifiers onto the
8392     // conversion type.
8393     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8394         << SourceRange(D.getIdentifierLoc()) << 0;
8395     D.setInvalidType();
8396   }
8397 
8398   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8399 
8400   // Make sure we don't have any parameters.
8401   if (Proto->getNumParams() > 0) {
8402     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8403 
8404     // Delete the parameters.
8405     D.getFunctionTypeInfo().freeParams();
8406     D.setInvalidType();
8407   } else if (Proto->isVariadic()) {
8408     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8409     D.setInvalidType();
8410   }
8411 
8412   // Diagnose "&operator bool()" and other such nonsense.  This
8413   // is actually a gcc extension which we don't support.
8414   if (Proto->getReturnType() != ConvType) {
8415     bool NeedsTypedef = false;
8416     SourceRange Before, After;
8417 
8418     // Walk the chunks and extract information on them for our diagnostic.
8419     bool PastFunctionChunk = false;
8420     for (auto &Chunk : D.type_objects()) {
8421       switch (Chunk.Kind) {
8422       case DeclaratorChunk::Function:
8423         if (!PastFunctionChunk) {
8424           if (Chunk.Fun.HasTrailingReturnType) {
8425             TypeSourceInfo *TRT = nullptr;
8426             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8427             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8428           }
8429           PastFunctionChunk = true;
8430           break;
8431         }
8432         LLVM_FALLTHROUGH;
8433       case DeclaratorChunk::Array:
8434         NeedsTypedef = true;
8435         extendRight(After, Chunk.getSourceRange());
8436         break;
8437 
8438       case DeclaratorChunk::Pointer:
8439       case DeclaratorChunk::BlockPointer:
8440       case DeclaratorChunk::Reference:
8441       case DeclaratorChunk::MemberPointer:
8442       case DeclaratorChunk::Pipe:
8443         extendLeft(Before, Chunk.getSourceRange());
8444         break;
8445 
8446       case DeclaratorChunk::Paren:
8447         extendLeft(Before, Chunk.Loc);
8448         extendRight(After, Chunk.EndLoc);
8449         break;
8450       }
8451     }
8452 
8453     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8454                          After.isValid()  ? After.getBegin() :
8455                                             D.getIdentifierLoc();
8456     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8457     DB << Before << After;
8458 
8459     if (!NeedsTypedef) {
8460       DB << /*don't need a typedef*/0;
8461 
8462       // If we can provide a correct fix-it hint, do so.
8463       if (After.isInvalid() && ConvTSI) {
8464         SourceLocation InsertLoc =
8465             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8466         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8467            << FixItHint::CreateInsertionFromRange(
8468                   InsertLoc, CharSourceRange::getTokenRange(Before))
8469            << FixItHint::CreateRemoval(Before);
8470       }
8471     } else if (!Proto->getReturnType()->isDependentType()) {
8472       DB << /*typedef*/1 << Proto->getReturnType();
8473     } else if (getLangOpts().CPlusPlus11) {
8474       DB << /*alias template*/2 << Proto->getReturnType();
8475     } else {
8476       DB << /*might not be fixable*/3;
8477     }
8478 
8479     // Recover by incorporating the other type chunks into the result type.
8480     // Note, this does *not* change the name of the function. This is compatible
8481     // with the GCC extension:
8482     //   struct S { &operator int(); } s;
8483     //   int &r = s.operator int(); // ok in GCC
8484     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8485     ConvType = Proto->getReturnType();
8486   }
8487 
8488   // C++ [class.conv.fct]p4:
8489   //   The conversion-type-id shall not represent a function type nor
8490   //   an array type.
8491   if (ConvType->isArrayType()) {
8492     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8493     ConvType = Context.getPointerType(ConvType);
8494     D.setInvalidType();
8495   } else if (ConvType->isFunctionType()) {
8496     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8497     ConvType = Context.getPointerType(ConvType);
8498     D.setInvalidType();
8499   }
8500 
8501   // Rebuild the function type "R" without any parameters (in case any
8502   // of the errors above fired) and with the conversion type as the
8503   // return type.
8504   if (D.isInvalidType())
8505     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8506 
8507   // C++0x explicit conversion operators.
8508   if (DS.isExplicitSpecified())
8509     Diag(DS.getExplicitSpecLoc(),
8510          getLangOpts().CPlusPlus11
8511              ? diag::warn_cxx98_compat_explicit_conversion_functions
8512              : diag::ext_explicit_conversion_functions)
8513         << SourceRange(DS.getExplicitSpecLoc());
8514 }
8515 
8516 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8517 /// the declaration of the given C++ conversion function. This routine
8518 /// is responsible for recording the conversion function in the C++
8519 /// class, if possible.
8520 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8521   assert(Conversion && "Expected to receive a conversion function declaration");
8522 
8523   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8524 
8525   // Make sure we aren't redeclaring the conversion function.
8526   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8527 
8528   // C++ [class.conv.fct]p1:
8529   //   [...] A conversion function is never used to convert a
8530   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8531   //   same object type (or a reference to it), to a (possibly
8532   //   cv-qualified) base class of that type (or a reference to it),
8533   //   or to (possibly cv-qualified) void.
8534   // FIXME: Suppress this warning if the conversion function ends up being a
8535   // virtual function that overrides a virtual function in a base class.
8536   QualType ClassType
8537     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8538   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8539     ConvType = ConvTypeRef->getPointeeType();
8540   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8541       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8542     /* Suppress diagnostics for instantiations. */;
8543   else if (ConvType->isRecordType()) {
8544     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8545     if (ConvType == ClassType)
8546       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8547         << ClassType;
8548     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8549       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8550         <<  ClassType << ConvType;
8551   } else if (ConvType->isVoidType()) {
8552     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8553       << ClassType << ConvType;
8554   }
8555 
8556   if (FunctionTemplateDecl *ConversionTemplate
8557                                 = Conversion->getDescribedFunctionTemplate())
8558     return ConversionTemplate;
8559 
8560   return Conversion;
8561 }
8562 
8563 namespace {
8564 /// Utility class to accumulate and print a diagnostic listing the invalid
8565 /// specifier(s) on a declaration.
8566 struct BadSpecifierDiagnoser {
8567   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8568       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8569   ~BadSpecifierDiagnoser() {
8570     Diagnostic << Specifiers;
8571   }
8572 
8573   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8574     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8575   }
8576   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8577     return check(SpecLoc,
8578                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8579   }
8580   void check(SourceLocation SpecLoc, const char *Spec) {
8581     if (SpecLoc.isInvalid()) return;
8582     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8583     if (!Specifiers.empty()) Specifiers += " ";
8584     Specifiers += Spec;
8585   }
8586 
8587   Sema &S;
8588   Sema::SemaDiagnosticBuilder Diagnostic;
8589   std::string Specifiers;
8590 };
8591 }
8592 
8593 /// Check the validity of a declarator that we parsed for a deduction-guide.
8594 /// These aren't actually declarators in the grammar, so we need to check that
8595 /// the user didn't specify any pieces that are not part of the deduction-guide
8596 /// grammar.
8597 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8598                                          StorageClass &SC) {
8599   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8600   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8601   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8602 
8603   // C++ [temp.deduct.guide]p3:
8604   //   A deduction-gide shall be declared in the same scope as the
8605   //   corresponding class template.
8606   if (!CurContext->getRedeclContext()->Equals(
8607           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8608     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8609       << GuidedTemplateDecl;
8610     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8611   }
8612 
8613   auto &DS = D.getMutableDeclSpec();
8614   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8615   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8616       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8617       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8618     BadSpecifierDiagnoser Diagnoser(
8619         *this, D.getIdentifierLoc(),
8620         diag::err_deduction_guide_invalid_specifier);
8621 
8622     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8623     DS.ClearStorageClassSpecs();
8624     SC = SC_None;
8625 
8626     // 'explicit' is permitted.
8627     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8628     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8629     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8630     DS.ClearConstexprSpec();
8631 
8632     Diagnoser.check(DS.getConstSpecLoc(), "const");
8633     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8634     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8635     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8636     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8637     DS.ClearTypeQualifiers();
8638 
8639     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8640     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8641     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8642     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8643     DS.ClearTypeSpecType();
8644   }
8645 
8646   if (D.isInvalidType())
8647     return;
8648 
8649   // Check the declarator is simple enough.
8650   bool FoundFunction = false;
8651   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8652     if (Chunk.Kind == DeclaratorChunk::Paren)
8653       continue;
8654     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8655       Diag(D.getDeclSpec().getBeginLoc(),
8656            diag::err_deduction_guide_with_complex_decl)
8657           << D.getSourceRange();
8658       break;
8659     }
8660     if (!Chunk.Fun.hasTrailingReturnType()) {
8661       Diag(D.getName().getBeginLoc(),
8662            diag::err_deduction_guide_no_trailing_return_type);
8663       break;
8664     }
8665 
8666     // Check that the return type is written as a specialization of
8667     // the template specified as the deduction-guide's name.
8668     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8669     TypeSourceInfo *TSI = nullptr;
8670     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8671     assert(TSI && "deduction guide has valid type but invalid return type?");
8672     bool AcceptableReturnType = false;
8673     bool MightInstantiateToSpecialization = false;
8674     if (auto RetTST =
8675             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8676       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8677       bool TemplateMatches =
8678           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8679       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8680         AcceptableReturnType = true;
8681       else {
8682         // This could still instantiate to the right type, unless we know it
8683         // names the wrong class template.
8684         auto *TD = SpecifiedName.getAsTemplateDecl();
8685         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8686                                              !TemplateMatches);
8687       }
8688     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8689       MightInstantiateToSpecialization = true;
8690     }
8691 
8692     if (!AcceptableReturnType) {
8693       Diag(TSI->getTypeLoc().getBeginLoc(),
8694            diag::err_deduction_guide_bad_trailing_return_type)
8695           << GuidedTemplate << TSI->getType()
8696           << MightInstantiateToSpecialization
8697           << TSI->getTypeLoc().getSourceRange();
8698     }
8699 
8700     // Keep going to check that we don't have any inner declarator pieces (we
8701     // could still have a function returning a pointer to a function).
8702     FoundFunction = true;
8703   }
8704 
8705   if (D.isFunctionDefinition())
8706     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8707 }
8708 
8709 //===----------------------------------------------------------------------===//
8710 // Namespace Handling
8711 //===----------------------------------------------------------------------===//
8712 
8713 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8714 /// reopened.
8715 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8716                                             SourceLocation Loc,
8717                                             IdentifierInfo *II, bool *IsInline,
8718                                             NamespaceDecl *PrevNS) {
8719   assert(*IsInline != PrevNS->isInline());
8720 
8721   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8722   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8723   // inline namespaces, with the intention of bringing names into namespace std.
8724   //
8725   // We support this just well enough to get that case working; this is not
8726   // sufficient to support reopening namespaces as inline in general.
8727   if (*IsInline && II && II->getName().startswith("__atomic") &&
8728       S.getSourceManager().isInSystemHeader(Loc)) {
8729     // Mark all prior declarations of the namespace as inline.
8730     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8731          NS = NS->getPreviousDecl())
8732       NS->setInline(*IsInline);
8733     // Patch up the lookup table for the containing namespace. This isn't really
8734     // correct, but it's good enough for this particular case.
8735     for (auto *I : PrevNS->decls())
8736       if (auto *ND = dyn_cast<NamedDecl>(I))
8737         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8738     return;
8739   }
8740 
8741   if (PrevNS->isInline())
8742     // The user probably just forgot the 'inline', so suggest that it
8743     // be added back.
8744     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8745       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8746   else
8747     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8748 
8749   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8750   *IsInline = PrevNS->isInline();
8751 }
8752 
8753 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8754 /// definition.
8755 Decl *Sema::ActOnStartNamespaceDef(
8756     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8757     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8758     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8759   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8760   // For anonymous namespace, take the location of the left brace.
8761   SourceLocation Loc = II ? IdentLoc : LBrace;
8762   bool IsInline = InlineLoc.isValid();
8763   bool IsInvalid = false;
8764   bool IsStd = false;
8765   bool AddToKnown = false;
8766   Scope *DeclRegionScope = NamespcScope->getParent();
8767 
8768   NamespaceDecl *PrevNS = nullptr;
8769   if (II) {
8770     // C++ [namespace.def]p2:
8771     //   The identifier in an original-namespace-definition shall not
8772     //   have been previously defined in the declarative region in
8773     //   which the original-namespace-definition appears. The
8774     //   identifier in an original-namespace-definition is the name of
8775     //   the namespace. Subsequently in that declarative region, it is
8776     //   treated as an original-namespace-name.
8777     //
8778     // Since namespace names are unique in their scope, and we don't
8779     // look through using directives, just look for any ordinary names
8780     // as if by qualified name lookup.
8781     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8782                    ForExternalRedeclaration);
8783     LookupQualifiedName(R, CurContext->getRedeclContext());
8784     NamedDecl *PrevDecl =
8785         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8786     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8787 
8788     if (PrevNS) {
8789       // This is an extended namespace definition.
8790       if (IsInline != PrevNS->isInline())
8791         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8792                                         &IsInline, PrevNS);
8793     } else if (PrevDecl) {
8794       // This is an invalid name redefinition.
8795       Diag(Loc, diag::err_redefinition_different_kind)
8796         << II;
8797       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8798       IsInvalid = true;
8799       // Continue on to push Namespc as current DeclContext and return it.
8800     } else if (II->isStr("std") &&
8801                CurContext->getRedeclContext()->isTranslationUnit()) {
8802       // This is the first "real" definition of the namespace "std", so update
8803       // our cache of the "std" namespace to point at this definition.
8804       PrevNS = getStdNamespace();
8805       IsStd = true;
8806       AddToKnown = !IsInline;
8807     } else {
8808       // We've seen this namespace for the first time.
8809       AddToKnown = !IsInline;
8810     }
8811   } else {
8812     // Anonymous namespaces.
8813 
8814     // Determine whether the parent already has an anonymous namespace.
8815     DeclContext *Parent = CurContext->getRedeclContext();
8816     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8817       PrevNS = TU->getAnonymousNamespace();
8818     } else {
8819       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8820       PrevNS = ND->getAnonymousNamespace();
8821     }
8822 
8823     if (PrevNS && IsInline != PrevNS->isInline())
8824       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8825                                       &IsInline, PrevNS);
8826   }
8827 
8828   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8829                                                  StartLoc, Loc, II, PrevNS);
8830   if (IsInvalid)
8831     Namespc->setInvalidDecl();
8832 
8833   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8834   AddPragmaAttributes(DeclRegionScope, Namespc);
8835 
8836   // FIXME: Should we be merging attributes?
8837   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8838     PushNamespaceVisibilityAttr(Attr, Loc);
8839 
8840   if (IsStd)
8841     StdNamespace = Namespc;
8842   if (AddToKnown)
8843     KnownNamespaces[Namespc] = false;
8844 
8845   if (II) {
8846     PushOnScopeChains(Namespc, DeclRegionScope);
8847   } else {
8848     // Link the anonymous namespace into its parent.
8849     DeclContext *Parent = CurContext->getRedeclContext();
8850     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8851       TU->setAnonymousNamespace(Namespc);
8852     } else {
8853       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8854     }
8855 
8856     CurContext->addDecl(Namespc);
8857 
8858     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8859     //   behaves as if it were replaced by
8860     //     namespace unique { /* empty body */ }
8861     //     using namespace unique;
8862     //     namespace unique { namespace-body }
8863     //   where all occurrences of 'unique' in a translation unit are
8864     //   replaced by the same identifier and this identifier differs
8865     //   from all other identifiers in the entire program.
8866 
8867     // We just create the namespace with an empty name and then add an
8868     // implicit using declaration, just like the standard suggests.
8869     //
8870     // CodeGen enforces the "universally unique" aspect by giving all
8871     // declarations semantically contained within an anonymous
8872     // namespace internal linkage.
8873 
8874     if (!PrevNS) {
8875       UD = UsingDirectiveDecl::Create(Context, Parent,
8876                                       /* 'using' */ LBrace,
8877                                       /* 'namespace' */ SourceLocation(),
8878                                       /* qualifier */ NestedNameSpecifierLoc(),
8879                                       /* identifier */ SourceLocation(),
8880                                       Namespc,
8881                                       /* Ancestor */ Parent);
8882       UD->setImplicit();
8883       Parent->addDecl(UD);
8884     }
8885   }
8886 
8887   ActOnDocumentableDecl(Namespc);
8888 
8889   // Although we could have an invalid decl (i.e. the namespace name is a
8890   // redefinition), push it as current DeclContext and try to continue parsing.
8891   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8892   // for the namespace has the declarations that showed up in that particular
8893   // namespace definition.
8894   PushDeclContext(NamespcScope, Namespc);
8895   return Namespc;
8896 }
8897 
8898 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8899 /// is a namespace alias, returns the namespace it points to.
8900 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8901   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8902     return AD->getNamespace();
8903   return dyn_cast_or_null<NamespaceDecl>(D);
8904 }
8905 
8906 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8907 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8908 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8909   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8910   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8911   Namespc->setRBraceLoc(RBrace);
8912   PopDeclContext();
8913   if (Namespc->hasAttr<VisibilityAttr>())
8914     PopPragmaVisibility(true, RBrace);
8915 }
8916 
8917 CXXRecordDecl *Sema::getStdBadAlloc() const {
8918   return cast_or_null<CXXRecordDecl>(
8919                                   StdBadAlloc.get(Context.getExternalSource()));
8920 }
8921 
8922 EnumDecl *Sema::getStdAlignValT() const {
8923   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8924 }
8925 
8926 NamespaceDecl *Sema::getStdNamespace() const {
8927   return cast_or_null<NamespaceDecl>(
8928                                  StdNamespace.get(Context.getExternalSource()));
8929 }
8930 
8931 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8932   if (!StdExperimentalNamespaceCache) {
8933     if (auto Std = getStdNamespace()) {
8934       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8935                           SourceLocation(), LookupNamespaceName);
8936       if (!LookupQualifiedName(Result, Std) ||
8937           !(StdExperimentalNamespaceCache =
8938                 Result.getAsSingle<NamespaceDecl>()))
8939         Result.suppressDiagnostics();
8940     }
8941   }
8942   return StdExperimentalNamespaceCache;
8943 }
8944 
8945 namespace {
8946 
8947 enum UnsupportedSTLSelect {
8948   USS_InvalidMember,
8949   USS_MissingMember,
8950   USS_NonTrivial,
8951   USS_Other
8952 };
8953 
8954 struct InvalidSTLDiagnoser {
8955   Sema &S;
8956   SourceLocation Loc;
8957   QualType TyForDiags;
8958 
8959   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
8960                       const VarDecl *VD = nullptr) {
8961     {
8962       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
8963                << TyForDiags << ((int)Sel);
8964       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
8965         assert(!Name.empty());
8966         D << Name;
8967       }
8968     }
8969     if (Sel == USS_InvalidMember) {
8970       S.Diag(VD->getLocation(), diag::note_var_declared_here)
8971           << VD << VD->getSourceRange();
8972     }
8973     return QualType();
8974   }
8975 };
8976 } // namespace
8977 
8978 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
8979                                            SourceLocation Loc) {
8980   assert(getLangOpts().CPlusPlus &&
8981          "Looking for comparison category type outside of C++.");
8982 
8983   // Check if we've already successfully checked the comparison category type
8984   // before. If so, skip checking it again.
8985   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
8986   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
8987     return Info->getType();
8988 
8989   // If lookup failed
8990   if (!Info) {
8991     std::string NameForDiags = "std::";
8992     NameForDiags += ComparisonCategories::getCategoryString(Kind);
8993     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
8994         << NameForDiags;
8995     return QualType();
8996   }
8997 
8998   assert(Info->Kind == Kind);
8999   assert(Info->Record);
9000 
9001   // Update the Record decl in case we encountered a forward declaration on our
9002   // first pass. FIXME: This is a bit of a hack.
9003   if (Info->Record->hasDefinition())
9004     Info->Record = Info->Record->getDefinition();
9005 
9006   // Use an elaborated type for diagnostics which has a name containing the
9007   // prepended 'std' namespace but not any inline namespace names.
9008   QualType TyForDiags = [&]() {
9009     auto *NNS =
9010         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9011     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9012   }();
9013 
9014   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9015     return QualType();
9016 
9017   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9018 
9019   if (!Info->Record->isTriviallyCopyable())
9020     return UnsupportedSTLError(USS_NonTrivial);
9021 
9022   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9023     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9024     // Tolerate empty base classes.
9025     if (Base->isEmpty())
9026       continue;
9027     // Reject STL implementations which have at least one non-empty base.
9028     return UnsupportedSTLError();
9029   }
9030 
9031   // Check that the STL has implemented the types using a single integer field.
9032   // This expectation allows better codegen for builtin operators. We require:
9033   //   (1) The class has exactly one field.
9034   //   (2) The field is an integral or enumeration type.
9035   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9036   if (std::distance(FIt, FEnd) != 1 ||
9037       !FIt->getType()->isIntegralOrEnumerationType()) {
9038     return UnsupportedSTLError();
9039   }
9040 
9041   // Build each of the require values and store them in Info.
9042   for (ComparisonCategoryResult CCR :
9043        ComparisonCategories::getPossibleResultsForType(Kind)) {
9044     StringRef MemName = ComparisonCategories::getResultString(CCR);
9045     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9046 
9047     if (!ValInfo)
9048       return UnsupportedSTLError(USS_MissingMember, MemName);
9049 
9050     VarDecl *VD = ValInfo->VD;
9051     assert(VD && "should not be null!");
9052 
9053     // Attempt to diagnose reasons why the STL definition of this type
9054     // might be foobar, including it failing to be a constant expression.
9055     // TODO Handle more ways the lookup or result can be invalid.
9056     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9057         !VD->checkInitIsICE())
9058       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9059 
9060     // Attempt to evaluate the var decl as a constant expression and extract
9061     // the value of its first field as a ICE. If this fails, the STL
9062     // implementation is not supported.
9063     if (!ValInfo->hasValidIntValue())
9064       return UnsupportedSTLError();
9065 
9066     MarkVariableReferenced(Loc, VD);
9067   }
9068 
9069   // We've successfully built the required types and expressions. Update
9070   // the cache and return the newly cached value.
9071   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9072   return Info->getType();
9073 }
9074 
9075 /// Retrieve the special "std" namespace, which may require us to
9076 /// implicitly define the namespace.
9077 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9078   if (!StdNamespace) {
9079     // The "std" namespace has not yet been defined, so build one implicitly.
9080     StdNamespace = NamespaceDecl::Create(Context,
9081                                          Context.getTranslationUnitDecl(),
9082                                          /*Inline=*/false,
9083                                          SourceLocation(), SourceLocation(),
9084                                          &PP.getIdentifierTable().get("std"),
9085                                          /*PrevDecl=*/nullptr);
9086     getStdNamespace()->setImplicit(true);
9087   }
9088 
9089   return getStdNamespace();
9090 }
9091 
9092 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9093   assert(getLangOpts().CPlusPlus &&
9094          "Looking for std::initializer_list outside of C++.");
9095 
9096   // We're looking for implicit instantiations of
9097   // template <typename E> class std::initializer_list.
9098 
9099   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9100     return false;
9101 
9102   ClassTemplateDecl *Template = nullptr;
9103   const TemplateArgument *Arguments = nullptr;
9104 
9105   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9106 
9107     ClassTemplateSpecializationDecl *Specialization =
9108         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9109     if (!Specialization)
9110       return false;
9111 
9112     Template = Specialization->getSpecializedTemplate();
9113     Arguments = Specialization->getTemplateArgs().data();
9114   } else if (const TemplateSpecializationType *TST =
9115                  Ty->getAs<TemplateSpecializationType>()) {
9116     Template = dyn_cast_or_null<ClassTemplateDecl>(
9117         TST->getTemplateName().getAsTemplateDecl());
9118     Arguments = TST->getArgs();
9119   }
9120   if (!Template)
9121     return false;
9122 
9123   if (!StdInitializerList) {
9124     // Haven't recognized std::initializer_list yet, maybe this is it.
9125     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9126     if (TemplateClass->getIdentifier() !=
9127             &PP.getIdentifierTable().get("initializer_list") ||
9128         !getStdNamespace()->InEnclosingNamespaceSetOf(
9129             TemplateClass->getDeclContext()))
9130       return false;
9131     // This is a template called std::initializer_list, but is it the right
9132     // template?
9133     TemplateParameterList *Params = Template->getTemplateParameters();
9134     if (Params->getMinRequiredArguments() != 1)
9135       return false;
9136     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9137       return false;
9138 
9139     // It's the right template.
9140     StdInitializerList = Template;
9141   }
9142 
9143   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9144     return false;
9145 
9146   // This is an instance of std::initializer_list. Find the argument type.
9147   if (Element)
9148     *Element = Arguments[0].getAsType();
9149   return true;
9150 }
9151 
9152 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9153   NamespaceDecl *Std = S.getStdNamespace();
9154   if (!Std) {
9155     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9156     return nullptr;
9157   }
9158 
9159   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9160                       Loc, Sema::LookupOrdinaryName);
9161   if (!S.LookupQualifiedName(Result, Std)) {
9162     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9163     return nullptr;
9164   }
9165   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9166   if (!Template) {
9167     Result.suppressDiagnostics();
9168     // We found something weird. Complain about the first thing we found.
9169     NamedDecl *Found = *Result.begin();
9170     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9171     return nullptr;
9172   }
9173 
9174   // We found some template called std::initializer_list. Now verify that it's
9175   // correct.
9176   TemplateParameterList *Params = Template->getTemplateParameters();
9177   if (Params->getMinRequiredArguments() != 1 ||
9178       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9179     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9180     return nullptr;
9181   }
9182 
9183   return Template;
9184 }
9185 
9186 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9187   if (!StdInitializerList) {
9188     StdInitializerList = LookupStdInitializerList(*this, Loc);
9189     if (!StdInitializerList)
9190       return QualType();
9191   }
9192 
9193   TemplateArgumentListInfo Args(Loc, Loc);
9194   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9195                                        Context.getTrivialTypeSourceInfo(Element,
9196                                                                         Loc)));
9197   return Context.getCanonicalType(
9198       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9199 }
9200 
9201 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9202   // C++ [dcl.init.list]p2:
9203   //   A constructor is an initializer-list constructor if its first parameter
9204   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9205   //   std::initializer_list<E> for some type E, and either there are no other
9206   //   parameters or else all other parameters have default arguments.
9207   if (Ctor->getNumParams() < 1 ||
9208       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9209     return false;
9210 
9211   QualType ArgType = Ctor->getParamDecl(0)->getType();
9212   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9213     ArgType = RT->getPointeeType().getUnqualifiedType();
9214 
9215   return isStdInitializerList(ArgType, nullptr);
9216 }
9217 
9218 /// Determine whether a using statement is in a context where it will be
9219 /// apply in all contexts.
9220 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9221   switch (CurContext->getDeclKind()) {
9222     case Decl::TranslationUnit:
9223       return true;
9224     case Decl::LinkageSpec:
9225       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9226     default:
9227       return false;
9228   }
9229 }
9230 
9231 namespace {
9232 
9233 // Callback to only accept typo corrections that are namespaces.
9234 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9235 public:
9236   bool ValidateCandidate(const TypoCorrection &candidate) override {
9237     if (NamedDecl *ND = candidate.getCorrectionDecl())
9238       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9239     return false;
9240   }
9241 };
9242 
9243 }
9244 
9245 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9246                                        CXXScopeSpec &SS,
9247                                        SourceLocation IdentLoc,
9248                                        IdentifierInfo *Ident) {
9249   R.clear();
9250   if (TypoCorrection Corrected =
9251           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9252                         llvm::make_unique<NamespaceValidatorCCC>(),
9253                         Sema::CTK_ErrorRecovery)) {
9254     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9255       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9256       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9257                               Ident->getName().equals(CorrectedStr);
9258       S.diagnoseTypo(Corrected,
9259                      S.PDiag(diag::err_using_directive_member_suggest)
9260                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9261                      S.PDiag(diag::note_namespace_defined_here));
9262     } else {
9263       S.diagnoseTypo(Corrected,
9264                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9265                      S.PDiag(diag::note_namespace_defined_here));
9266     }
9267     R.addDecl(Corrected.getFoundDecl());
9268     return true;
9269   }
9270   return false;
9271 }
9272 
9273 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9274                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9275                                 SourceLocation IdentLoc,
9276                                 IdentifierInfo *NamespcName,
9277                                 const ParsedAttributesView &AttrList) {
9278   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9279   assert(NamespcName && "Invalid NamespcName.");
9280   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9281 
9282   // This can only happen along a recovery path.
9283   while (S->isTemplateParamScope())
9284     S = S->getParent();
9285   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9286 
9287   UsingDirectiveDecl *UDir = nullptr;
9288   NestedNameSpecifier *Qualifier = nullptr;
9289   if (SS.isSet())
9290     Qualifier = SS.getScopeRep();
9291 
9292   // Lookup namespace name.
9293   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9294   LookupParsedName(R, S, &SS);
9295   if (R.isAmbiguous())
9296     return nullptr;
9297 
9298   if (R.empty()) {
9299     R.clear();
9300     // Allow "using namespace std;" or "using namespace ::std;" even if
9301     // "std" hasn't been defined yet, for GCC compatibility.
9302     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9303         NamespcName->isStr("std")) {
9304       Diag(IdentLoc, diag::ext_using_undefined_std);
9305       R.addDecl(getOrCreateStdNamespace());
9306       R.resolveKind();
9307     }
9308     // Otherwise, attempt typo correction.
9309     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9310   }
9311 
9312   if (!R.empty()) {
9313     NamedDecl *Named = R.getRepresentativeDecl();
9314     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9315     assert(NS && "expected namespace decl");
9316 
9317     // The use of a nested name specifier may trigger deprecation warnings.
9318     DiagnoseUseOfDecl(Named, IdentLoc);
9319 
9320     // C++ [namespace.udir]p1:
9321     //   A using-directive specifies that the names in the nominated
9322     //   namespace can be used in the scope in which the
9323     //   using-directive appears after the using-directive. During
9324     //   unqualified name lookup (3.4.1), the names appear as if they
9325     //   were declared in the nearest enclosing namespace which
9326     //   contains both the using-directive and the nominated
9327     //   namespace. [Note: in this context, "contains" means "contains
9328     //   directly or indirectly". ]
9329 
9330     // Find enclosing context containing both using-directive and
9331     // nominated namespace.
9332     DeclContext *CommonAncestor = NS;
9333     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9334       CommonAncestor = CommonAncestor->getParent();
9335 
9336     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9337                                       SS.getWithLocInContext(Context),
9338                                       IdentLoc, Named, CommonAncestor);
9339 
9340     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9341         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9342       Diag(IdentLoc, diag::warn_using_directive_in_header);
9343     }
9344 
9345     PushUsingDirective(S, UDir);
9346   } else {
9347     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9348   }
9349 
9350   if (UDir)
9351     ProcessDeclAttributeList(S, UDir, AttrList);
9352 
9353   return UDir;
9354 }
9355 
9356 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9357   // If the scope has an associated entity and the using directive is at
9358   // namespace or translation unit scope, add the UsingDirectiveDecl into
9359   // its lookup structure so qualified name lookup can find it.
9360   DeclContext *Ctx = S->getEntity();
9361   if (Ctx && !Ctx->isFunctionOrMethod())
9362     Ctx->addDecl(UDir);
9363   else
9364     // Otherwise, it is at block scope. The using-directives will affect lookup
9365     // only to the end of the scope.
9366     S->PushUsingDirective(UDir);
9367 }
9368 
9369 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9370                                   SourceLocation UsingLoc,
9371                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9372                                   UnqualifiedId &Name,
9373                                   SourceLocation EllipsisLoc,
9374                                   const ParsedAttributesView &AttrList) {
9375   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9376 
9377   if (SS.isEmpty()) {
9378     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9379     return nullptr;
9380   }
9381 
9382   switch (Name.getKind()) {
9383   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9384   case UnqualifiedIdKind::IK_Identifier:
9385   case UnqualifiedIdKind::IK_OperatorFunctionId:
9386   case UnqualifiedIdKind::IK_LiteralOperatorId:
9387   case UnqualifiedIdKind::IK_ConversionFunctionId:
9388     break;
9389 
9390   case UnqualifiedIdKind::IK_ConstructorName:
9391   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9392     // C++11 inheriting constructors.
9393     Diag(Name.getBeginLoc(),
9394          getLangOpts().CPlusPlus11
9395              ? diag::warn_cxx98_compat_using_decl_constructor
9396              : diag::err_using_decl_constructor)
9397         << SS.getRange();
9398 
9399     if (getLangOpts().CPlusPlus11) break;
9400 
9401     return nullptr;
9402 
9403   case UnqualifiedIdKind::IK_DestructorName:
9404     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9405     return nullptr;
9406 
9407   case UnqualifiedIdKind::IK_TemplateId:
9408     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9409         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9410     return nullptr;
9411 
9412   case UnqualifiedIdKind::IK_DeductionGuideName:
9413     llvm_unreachable("cannot parse qualified deduction guide name");
9414   }
9415 
9416   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9417   DeclarationName TargetName = TargetNameInfo.getName();
9418   if (!TargetName)
9419     return nullptr;
9420 
9421   // Warn about access declarations.
9422   if (UsingLoc.isInvalid()) {
9423     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9424                                  ? diag::err_access_decl
9425                                  : diag::warn_access_decl_deprecated)
9426         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9427   }
9428 
9429   if (EllipsisLoc.isInvalid()) {
9430     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9431         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9432       return nullptr;
9433   } else {
9434     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9435         !TargetNameInfo.containsUnexpandedParameterPack()) {
9436       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9437         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9438       EllipsisLoc = SourceLocation();
9439     }
9440   }
9441 
9442   NamedDecl *UD =
9443       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9444                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9445                             /*IsInstantiation*/false);
9446   if (UD)
9447     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9448 
9449   return UD;
9450 }
9451 
9452 /// Determine whether a using declaration considers the given
9453 /// declarations as "equivalent", e.g., if they are redeclarations of
9454 /// the same entity or are both typedefs of the same type.
9455 static bool
9456 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9457   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9458     return true;
9459 
9460   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9461     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9462       return Context.hasSameType(TD1->getUnderlyingType(),
9463                                  TD2->getUnderlyingType());
9464 
9465   return false;
9466 }
9467 
9468 
9469 /// Determines whether to create a using shadow decl for a particular
9470 /// decl, given the set of decls existing prior to this using lookup.
9471 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9472                                 const LookupResult &Previous,
9473                                 UsingShadowDecl *&PrevShadow) {
9474   // Diagnose finding a decl which is not from a base class of the
9475   // current class.  We do this now because there are cases where this
9476   // function will silently decide not to build a shadow decl, which
9477   // will pre-empt further diagnostics.
9478   //
9479   // We don't need to do this in C++11 because we do the check once on
9480   // the qualifier.
9481   //
9482   // FIXME: diagnose the following if we care enough:
9483   //   struct A { int foo; };
9484   //   struct B : A { using A::foo; };
9485   //   template <class T> struct C : A {};
9486   //   template <class T> struct D : C<T> { using B::foo; } // <---
9487   // This is invalid (during instantiation) in C++03 because B::foo
9488   // resolves to the using decl in B, which is not a base class of D<T>.
9489   // We can't diagnose it immediately because C<T> is an unknown
9490   // specialization.  The UsingShadowDecl in D<T> then points directly
9491   // to A::foo, which will look well-formed when we instantiate.
9492   // The right solution is to not collapse the shadow-decl chain.
9493   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9494     DeclContext *OrigDC = Orig->getDeclContext();
9495 
9496     // Handle enums and anonymous structs.
9497     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9498     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9499     while (OrigRec->isAnonymousStructOrUnion())
9500       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9501 
9502     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9503       if (OrigDC == CurContext) {
9504         Diag(Using->getLocation(),
9505              diag::err_using_decl_nested_name_specifier_is_current_class)
9506           << Using->getQualifierLoc().getSourceRange();
9507         Diag(Orig->getLocation(), diag::note_using_decl_target);
9508         Using->setInvalidDecl();
9509         return true;
9510       }
9511 
9512       Diag(Using->getQualifierLoc().getBeginLoc(),
9513            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9514         << Using->getQualifier()
9515         << cast<CXXRecordDecl>(CurContext)
9516         << Using->getQualifierLoc().getSourceRange();
9517       Diag(Orig->getLocation(), diag::note_using_decl_target);
9518       Using->setInvalidDecl();
9519       return true;
9520     }
9521   }
9522 
9523   if (Previous.empty()) return false;
9524 
9525   NamedDecl *Target = Orig;
9526   if (isa<UsingShadowDecl>(Target))
9527     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9528 
9529   // If the target happens to be one of the previous declarations, we
9530   // don't have a conflict.
9531   //
9532   // FIXME: but we might be increasing its access, in which case we
9533   // should redeclare it.
9534   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9535   bool FoundEquivalentDecl = false;
9536   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9537          I != E; ++I) {
9538     NamedDecl *D = (*I)->getUnderlyingDecl();
9539     // We can have UsingDecls in our Previous results because we use the same
9540     // LookupResult for checking whether the UsingDecl itself is a valid
9541     // redeclaration.
9542     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9543       continue;
9544 
9545     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9546       // C++ [class.mem]p19:
9547       //   If T is the name of a class, then [every named member other than
9548       //   a non-static data member] shall have a name different from T
9549       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9550           !isa<IndirectFieldDecl>(Target) &&
9551           !isa<UnresolvedUsingValueDecl>(Target) &&
9552           DiagnoseClassNameShadow(
9553               CurContext,
9554               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9555         return true;
9556     }
9557 
9558     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9559       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9560         PrevShadow = Shadow;
9561       FoundEquivalentDecl = true;
9562     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9563       // We don't conflict with an existing using shadow decl of an equivalent
9564       // declaration, but we're not a redeclaration of it.
9565       FoundEquivalentDecl = true;
9566     }
9567 
9568     if (isVisible(D))
9569       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9570   }
9571 
9572   if (FoundEquivalentDecl)
9573     return false;
9574 
9575   if (FunctionDecl *FD = Target->getAsFunction()) {
9576     NamedDecl *OldDecl = nullptr;
9577     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9578                           /*IsForUsingDecl*/ true)) {
9579     case Ovl_Overload:
9580       return false;
9581 
9582     case Ovl_NonFunction:
9583       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9584       break;
9585 
9586     // We found a decl with the exact signature.
9587     case Ovl_Match:
9588       // If we're in a record, we want to hide the target, so we
9589       // return true (without a diagnostic) to tell the caller not to
9590       // build a shadow decl.
9591       if (CurContext->isRecord())
9592         return true;
9593 
9594       // If we're not in a record, this is an error.
9595       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9596       break;
9597     }
9598 
9599     Diag(Target->getLocation(), diag::note_using_decl_target);
9600     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9601     Using->setInvalidDecl();
9602     return true;
9603   }
9604 
9605   // Target is not a function.
9606 
9607   if (isa<TagDecl>(Target)) {
9608     // No conflict between a tag and a non-tag.
9609     if (!Tag) return false;
9610 
9611     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9612     Diag(Target->getLocation(), diag::note_using_decl_target);
9613     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9614     Using->setInvalidDecl();
9615     return true;
9616   }
9617 
9618   // No conflict between a tag and a non-tag.
9619   if (!NonTag) return false;
9620 
9621   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9622   Diag(Target->getLocation(), diag::note_using_decl_target);
9623   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9624   Using->setInvalidDecl();
9625   return true;
9626 }
9627 
9628 /// Determine whether a direct base class is a virtual base class.
9629 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9630   if (!Derived->getNumVBases())
9631     return false;
9632   for (auto &B : Derived->bases())
9633     if (B.getType()->getAsCXXRecordDecl() == Base)
9634       return B.isVirtual();
9635   llvm_unreachable("not a direct base class");
9636 }
9637 
9638 /// Builds a shadow declaration corresponding to a 'using' declaration.
9639 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9640                                             UsingDecl *UD,
9641                                             NamedDecl *Orig,
9642                                             UsingShadowDecl *PrevDecl) {
9643   // If we resolved to another shadow declaration, just coalesce them.
9644   NamedDecl *Target = Orig;
9645   if (isa<UsingShadowDecl>(Target)) {
9646     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9647     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9648   }
9649 
9650   NamedDecl *NonTemplateTarget = Target;
9651   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9652     NonTemplateTarget = TargetTD->getTemplatedDecl();
9653 
9654   UsingShadowDecl *Shadow;
9655   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9656     bool IsVirtualBase =
9657         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9658                             UD->getQualifier()->getAsRecordDecl());
9659     Shadow = ConstructorUsingShadowDecl::Create(
9660         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9661   } else {
9662     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9663                                      Target);
9664   }
9665   UD->addShadowDecl(Shadow);
9666 
9667   Shadow->setAccess(UD->getAccess());
9668   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9669     Shadow->setInvalidDecl();
9670 
9671   Shadow->setPreviousDecl(PrevDecl);
9672 
9673   if (S)
9674     PushOnScopeChains(Shadow, S);
9675   else
9676     CurContext->addDecl(Shadow);
9677 
9678 
9679   return Shadow;
9680 }
9681 
9682 /// Hides a using shadow declaration.  This is required by the current
9683 /// using-decl implementation when a resolvable using declaration in a
9684 /// class is followed by a declaration which would hide or override
9685 /// one or more of the using decl's targets; for example:
9686 ///
9687 ///   struct Base { void foo(int); };
9688 ///   struct Derived : Base {
9689 ///     using Base::foo;
9690 ///     void foo(int);
9691 ///   };
9692 ///
9693 /// The governing language is C++03 [namespace.udecl]p12:
9694 ///
9695 ///   When a using-declaration brings names from a base class into a
9696 ///   derived class scope, member functions in the derived class
9697 ///   override and/or hide member functions with the same name and
9698 ///   parameter types in a base class (rather than conflicting).
9699 ///
9700 /// There are two ways to implement this:
9701 ///   (1) optimistically create shadow decls when they're not hidden
9702 ///       by existing declarations, or
9703 ///   (2) don't create any shadow decls (or at least don't make them
9704 ///       visible) until we've fully parsed/instantiated the class.
9705 /// The problem with (1) is that we might have to retroactively remove
9706 /// a shadow decl, which requires several O(n) operations because the
9707 /// decl structures are (very reasonably) not designed for removal.
9708 /// (2) avoids this but is very fiddly and phase-dependent.
9709 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9710   if (Shadow->getDeclName().getNameKind() ==
9711         DeclarationName::CXXConversionFunctionName)
9712     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9713 
9714   // Remove it from the DeclContext...
9715   Shadow->getDeclContext()->removeDecl(Shadow);
9716 
9717   // ...and the scope, if applicable...
9718   if (S) {
9719     S->RemoveDecl(Shadow);
9720     IdResolver.RemoveDecl(Shadow);
9721   }
9722 
9723   // ...and the using decl.
9724   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9725 
9726   // TODO: complain somehow if Shadow was used.  It shouldn't
9727   // be possible for this to happen, because...?
9728 }
9729 
9730 /// Find the base specifier for a base class with the given type.
9731 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9732                                                 QualType DesiredBase,
9733                                                 bool &AnyDependentBases) {
9734   // Check whether the named type is a direct base class.
9735   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9736   for (auto &Base : Derived->bases()) {
9737     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9738     if (CanonicalDesiredBase == BaseType)
9739       return &Base;
9740     if (BaseType->isDependentType())
9741       AnyDependentBases = true;
9742   }
9743   return nullptr;
9744 }
9745 
9746 namespace {
9747 class UsingValidatorCCC : public CorrectionCandidateCallback {
9748 public:
9749   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9750                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9751       : HasTypenameKeyword(HasTypenameKeyword),
9752         IsInstantiation(IsInstantiation), OldNNS(NNS),
9753         RequireMemberOf(RequireMemberOf) {}
9754 
9755   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9756     NamedDecl *ND = Candidate.getCorrectionDecl();
9757 
9758     // Keywords are not valid here.
9759     if (!ND || isa<NamespaceDecl>(ND))
9760       return false;
9761 
9762     // Completely unqualified names are invalid for a 'using' declaration.
9763     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9764       return false;
9765 
9766     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9767     // reject.
9768 
9769     if (RequireMemberOf) {
9770       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9771       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9772         // No-one ever wants a using-declaration to name an injected-class-name
9773         // of a base class, unless they're declaring an inheriting constructor.
9774         ASTContext &Ctx = ND->getASTContext();
9775         if (!Ctx.getLangOpts().CPlusPlus11)
9776           return false;
9777         QualType FoundType = Ctx.getRecordType(FoundRecord);
9778 
9779         // Check that the injected-class-name is named as a member of its own
9780         // type; we don't want to suggest 'using Derived::Base;', since that
9781         // means something else.
9782         NestedNameSpecifier *Specifier =
9783             Candidate.WillReplaceSpecifier()
9784                 ? Candidate.getCorrectionSpecifier()
9785                 : OldNNS;
9786         if (!Specifier->getAsType() ||
9787             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9788           return false;
9789 
9790         // Check that this inheriting constructor declaration actually names a
9791         // direct base class of the current class.
9792         bool AnyDependentBases = false;
9793         if (!findDirectBaseWithType(RequireMemberOf,
9794                                     Ctx.getRecordType(FoundRecord),
9795                                     AnyDependentBases) &&
9796             !AnyDependentBases)
9797           return false;
9798       } else {
9799         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9800         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9801           return false;
9802 
9803         // FIXME: Check that the base class member is accessible?
9804       }
9805     } else {
9806       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9807       if (FoundRecord && FoundRecord->isInjectedClassName())
9808         return false;
9809     }
9810 
9811     if (isa<TypeDecl>(ND))
9812       return HasTypenameKeyword || !IsInstantiation;
9813 
9814     return !HasTypenameKeyword;
9815   }
9816 
9817 private:
9818   bool HasTypenameKeyword;
9819   bool IsInstantiation;
9820   NestedNameSpecifier *OldNNS;
9821   CXXRecordDecl *RequireMemberOf;
9822 };
9823 } // end anonymous namespace
9824 
9825 /// Builds a using declaration.
9826 ///
9827 /// \param IsInstantiation - Whether this call arises from an
9828 ///   instantiation of an unresolved using declaration.  We treat
9829 ///   the lookup differently for these declarations.
9830 NamedDecl *Sema::BuildUsingDeclaration(
9831     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9832     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9833     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9834     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9835   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9836   SourceLocation IdentLoc = NameInfo.getLoc();
9837   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9838 
9839   // FIXME: We ignore attributes for now.
9840 
9841   // For an inheriting constructor declaration, the name of the using
9842   // declaration is the name of a constructor in this class, not in the
9843   // base class.
9844   DeclarationNameInfo UsingName = NameInfo;
9845   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9846     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9847       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9848           Context.getCanonicalType(Context.getRecordType(RD))));
9849 
9850   // Do the redeclaration lookup in the current scope.
9851   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9852                         ForVisibleRedeclaration);
9853   Previous.setHideTags(false);
9854   if (S) {
9855     LookupName(Previous, S);
9856 
9857     // It is really dumb that we have to do this.
9858     LookupResult::Filter F = Previous.makeFilter();
9859     while (F.hasNext()) {
9860       NamedDecl *D = F.next();
9861       if (!isDeclInScope(D, CurContext, S))
9862         F.erase();
9863       // If we found a local extern declaration that's not ordinarily visible,
9864       // and this declaration is being added to a non-block scope, ignore it.
9865       // We're only checking for scope conflicts here, not also for violations
9866       // of the linkage rules.
9867       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9868                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9869         F.erase();
9870     }
9871     F.done();
9872   } else {
9873     assert(IsInstantiation && "no scope in non-instantiation");
9874     if (CurContext->isRecord())
9875       LookupQualifiedName(Previous, CurContext);
9876     else {
9877       // No redeclaration check is needed here; in non-member contexts we
9878       // diagnosed all possible conflicts with other using-declarations when
9879       // building the template:
9880       //
9881       // For a dependent non-type using declaration, the only valid case is
9882       // if we instantiate to a single enumerator. We check for conflicts
9883       // between shadow declarations we introduce, and we check in the template
9884       // definition for conflicts between a non-type using declaration and any
9885       // other declaration, which together covers all cases.
9886       //
9887       // A dependent typename using declaration will never successfully
9888       // instantiate, since it will always name a class member, so we reject
9889       // that in the template definition.
9890     }
9891   }
9892 
9893   // Check for invalid redeclarations.
9894   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9895                                   SS, IdentLoc, Previous))
9896     return nullptr;
9897 
9898   // Check for bad qualifiers.
9899   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9900                               IdentLoc))
9901     return nullptr;
9902 
9903   DeclContext *LookupContext = computeDeclContext(SS);
9904   NamedDecl *D;
9905   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9906   if (!LookupContext || EllipsisLoc.isValid()) {
9907     if (HasTypenameKeyword) {
9908       // FIXME: not all declaration name kinds are legal here
9909       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9910                                               UsingLoc, TypenameLoc,
9911                                               QualifierLoc,
9912                                               IdentLoc, NameInfo.getName(),
9913                                               EllipsisLoc);
9914     } else {
9915       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9916                                            QualifierLoc, NameInfo, EllipsisLoc);
9917     }
9918     D->setAccess(AS);
9919     CurContext->addDecl(D);
9920     return D;
9921   }
9922 
9923   auto Build = [&](bool Invalid) {
9924     UsingDecl *UD =
9925         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9926                           UsingName, HasTypenameKeyword);
9927     UD->setAccess(AS);
9928     CurContext->addDecl(UD);
9929     UD->setInvalidDecl(Invalid);
9930     return UD;
9931   };
9932   auto BuildInvalid = [&]{ return Build(true); };
9933   auto BuildValid = [&]{ return Build(false); };
9934 
9935   if (RequireCompleteDeclContext(SS, LookupContext))
9936     return BuildInvalid();
9937 
9938   // Look up the target name.
9939   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9940 
9941   // Unlike most lookups, we don't always want to hide tag
9942   // declarations: tag names are visible through the using declaration
9943   // even if hidden by ordinary names, *except* in a dependent context
9944   // where it's important for the sanity of two-phase lookup.
9945   if (!IsInstantiation)
9946     R.setHideTags(false);
9947 
9948   // For the purposes of this lookup, we have a base object type
9949   // equal to that of the current context.
9950   if (CurContext->isRecord()) {
9951     R.setBaseObjectType(
9952                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9953   }
9954 
9955   LookupQualifiedName(R, LookupContext);
9956 
9957   // Try to correct typos if possible. If constructor name lookup finds no
9958   // results, that means the named class has no explicit constructors, and we
9959   // suppressed declaring implicit ones (probably because it's dependent or
9960   // invalid).
9961   if (R.empty() &&
9962       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9963     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9964     // it will believe that glibc provides a ::gets in cases where it does not,
9965     // and will try to pull it into namespace std with a using-declaration.
9966     // Just ignore the using-declaration in that case.
9967     auto *II = NameInfo.getName().getAsIdentifierInfo();
9968     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9969         CurContext->isStdNamespace() &&
9970         isa<TranslationUnitDecl>(LookupContext) &&
9971         getSourceManager().isInSystemHeader(UsingLoc))
9972       return nullptr;
9973     if (TypoCorrection Corrected = CorrectTypo(
9974             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9975             llvm::make_unique<UsingValidatorCCC>(
9976                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9977                 dyn_cast<CXXRecordDecl>(CurContext)),
9978             CTK_ErrorRecovery)) {
9979       // We reject candidates where DroppedSpecifier == true, hence the
9980       // literal '0' below.
9981       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9982                                 << NameInfo.getName() << LookupContext << 0
9983                                 << SS.getRange());
9984 
9985       // If we picked a correction with no attached Decl we can't do anything
9986       // useful with it, bail out.
9987       NamedDecl *ND = Corrected.getCorrectionDecl();
9988       if (!ND)
9989         return BuildInvalid();
9990 
9991       // If we corrected to an inheriting constructor, handle it as one.
9992       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9993       if (RD && RD->isInjectedClassName()) {
9994         // The parent of the injected class name is the class itself.
9995         RD = cast<CXXRecordDecl>(RD->getParent());
9996 
9997         // Fix up the information we'll use to build the using declaration.
9998         if (Corrected.WillReplaceSpecifier()) {
9999           NestedNameSpecifierLocBuilder Builder;
10000           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10001                               QualifierLoc.getSourceRange());
10002           QualifierLoc = Builder.getWithLocInContext(Context);
10003         }
10004 
10005         // In this case, the name we introduce is the name of a derived class
10006         // constructor.
10007         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10008         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10009             Context.getCanonicalType(Context.getRecordType(CurClass))));
10010         UsingName.setNamedTypeInfo(nullptr);
10011         for (auto *Ctor : LookupConstructors(RD))
10012           R.addDecl(Ctor);
10013         R.resolveKind();
10014       } else {
10015         // FIXME: Pick up all the declarations if we found an overloaded
10016         // function.
10017         UsingName.setName(ND->getDeclName());
10018         R.addDecl(ND);
10019       }
10020     } else {
10021       Diag(IdentLoc, diag::err_no_member)
10022         << NameInfo.getName() << LookupContext << SS.getRange();
10023       return BuildInvalid();
10024     }
10025   }
10026 
10027   if (R.isAmbiguous())
10028     return BuildInvalid();
10029 
10030   if (HasTypenameKeyword) {
10031     // If we asked for a typename and got a non-type decl, error out.
10032     if (!R.getAsSingle<TypeDecl>()) {
10033       Diag(IdentLoc, diag::err_using_typename_non_type);
10034       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10035         Diag((*I)->getUnderlyingDecl()->getLocation(),
10036              diag::note_using_decl_target);
10037       return BuildInvalid();
10038     }
10039   } else {
10040     // If we asked for a non-typename and we got a type, error out,
10041     // but only if this is an instantiation of an unresolved using
10042     // decl.  Otherwise just silently find the type name.
10043     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10044       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10045       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10046       return BuildInvalid();
10047     }
10048   }
10049 
10050   // C++14 [namespace.udecl]p6:
10051   // A using-declaration shall not name a namespace.
10052   if (R.getAsSingle<NamespaceDecl>()) {
10053     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10054       << SS.getRange();
10055     return BuildInvalid();
10056   }
10057 
10058   // C++14 [namespace.udecl]p7:
10059   // A using-declaration shall not name a scoped enumerator.
10060   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10061     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10062       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10063         << SS.getRange();
10064       return BuildInvalid();
10065     }
10066   }
10067 
10068   UsingDecl *UD = BuildValid();
10069 
10070   // Some additional rules apply to inheriting constructors.
10071   if (UsingName.getName().getNameKind() ==
10072         DeclarationName::CXXConstructorName) {
10073     // Suppress access diagnostics; the access check is instead performed at the
10074     // point of use for an inheriting constructor.
10075     R.suppressDiagnostics();
10076     if (CheckInheritingConstructorUsingDecl(UD))
10077       return UD;
10078   }
10079 
10080   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10081     UsingShadowDecl *PrevDecl = nullptr;
10082     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10083       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10084   }
10085 
10086   return UD;
10087 }
10088 
10089 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10090                                     ArrayRef<NamedDecl *> Expansions) {
10091   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10092          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10093          isa<UsingPackDecl>(InstantiatedFrom));
10094 
10095   auto *UPD =
10096       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10097   UPD->setAccess(InstantiatedFrom->getAccess());
10098   CurContext->addDecl(UPD);
10099   return UPD;
10100 }
10101 
10102 /// Additional checks for a using declaration referring to a constructor name.
10103 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10104   assert(!UD->hasTypename() && "expecting a constructor name");
10105 
10106   const Type *SourceType = UD->getQualifier()->getAsType();
10107   assert(SourceType &&
10108          "Using decl naming constructor doesn't have type in scope spec.");
10109   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10110 
10111   // Check whether the named type is a direct base class.
10112   bool AnyDependentBases = false;
10113   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10114                                       AnyDependentBases);
10115   if (!Base && !AnyDependentBases) {
10116     Diag(UD->getUsingLoc(),
10117          diag::err_using_decl_constructor_not_in_direct_base)
10118       << UD->getNameInfo().getSourceRange()
10119       << QualType(SourceType, 0) << TargetClass;
10120     UD->setInvalidDecl();
10121     return true;
10122   }
10123 
10124   if (Base)
10125     Base->setInheritConstructors();
10126 
10127   return false;
10128 }
10129 
10130 /// Checks that the given using declaration is not an invalid
10131 /// redeclaration.  Note that this is checking only for the using decl
10132 /// itself, not for any ill-formedness among the UsingShadowDecls.
10133 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10134                                        bool HasTypenameKeyword,
10135                                        const CXXScopeSpec &SS,
10136                                        SourceLocation NameLoc,
10137                                        const LookupResult &Prev) {
10138   NestedNameSpecifier *Qual = SS.getScopeRep();
10139 
10140   // C++03 [namespace.udecl]p8:
10141   // C++0x [namespace.udecl]p10:
10142   //   A using-declaration is a declaration and can therefore be used
10143   //   repeatedly where (and only where) multiple declarations are
10144   //   allowed.
10145   //
10146   // That's in non-member contexts.
10147   if (!CurContext->getRedeclContext()->isRecord()) {
10148     // A dependent qualifier outside a class can only ever resolve to an
10149     // enumeration type. Therefore it conflicts with any other non-type
10150     // declaration in the same scope.
10151     // FIXME: How should we check for dependent type-type conflicts at block
10152     // scope?
10153     if (Qual->isDependent() && !HasTypenameKeyword) {
10154       for (auto *D : Prev) {
10155         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10156           bool OldCouldBeEnumerator =
10157               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10158           Diag(NameLoc,
10159                OldCouldBeEnumerator ? diag::err_redefinition
10160                                     : diag::err_redefinition_different_kind)
10161               << Prev.getLookupName();
10162           Diag(D->getLocation(), diag::note_previous_definition);
10163           return true;
10164         }
10165       }
10166     }
10167     return false;
10168   }
10169 
10170   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10171     NamedDecl *D = *I;
10172 
10173     bool DTypename;
10174     NestedNameSpecifier *DQual;
10175     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10176       DTypename = UD->hasTypename();
10177       DQual = UD->getQualifier();
10178     } else if (UnresolvedUsingValueDecl *UD
10179                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10180       DTypename = false;
10181       DQual = UD->getQualifier();
10182     } else if (UnresolvedUsingTypenameDecl *UD
10183                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10184       DTypename = true;
10185       DQual = UD->getQualifier();
10186     } else continue;
10187 
10188     // using decls differ if one says 'typename' and the other doesn't.
10189     // FIXME: non-dependent using decls?
10190     if (HasTypenameKeyword != DTypename) continue;
10191 
10192     // using decls differ if they name different scopes (but note that
10193     // template instantiation can cause this check to trigger when it
10194     // didn't before instantiation).
10195     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10196         Context.getCanonicalNestedNameSpecifier(DQual))
10197       continue;
10198 
10199     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10200     Diag(D->getLocation(), diag::note_using_decl) << 1;
10201     return true;
10202   }
10203 
10204   return false;
10205 }
10206 
10207 
10208 /// Checks that the given nested-name qualifier used in a using decl
10209 /// in the current context is appropriately related to the current
10210 /// scope.  If an error is found, diagnoses it and returns true.
10211 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10212                                    bool HasTypename,
10213                                    const CXXScopeSpec &SS,
10214                                    const DeclarationNameInfo &NameInfo,
10215                                    SourceLocation NameLoc) {
10216   DeclContext *NamedContext = computeDeclContext(SS);
10217 
10218   if (!CurContext->isRecord()) {
10219     // C++03 [namespace.udecl]p3:
10220     // C++0x [namespace.udecl]p8:
10221     //   A using-declaration for a class member shall be a member-declaration.
10222 
10223     // If we weren't able to compute a valid scope, it might validly be a
10224     // dependent class scope or a dependent enumeration unscoped scope. If
10225     // we have a 'typename' keyword, the scope must resolve to a class type.
10226     if ((HasTypename && !NamedContext) ||
10227         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10228       auto *RD = NamedContext
10229                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10230                      : nullptr;
10231       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10232         RD = nullptr;
10233 
10234       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10235         << SS.getRange();
10236 
10237       // If we have a complete, non-dependent source type, try to suggest a
10238       // way to get the same effect.
10239       if (!RD)
10240         return true;
10241 
10242       // Find what this using-declaration was referring to.
10243       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10244       R.setHideTags(false);
10245       R.suppressDiagnostics();
10246       LookupQualifiedName(R, RD);
10247 
10248       if (R.getAsSingle<TypeDecl>()) {
10249         if (getLangOpts().CPlusPlus11) {
10250           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10251           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10252             << 0 // alias declaration
10253             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10254                                           NameInfo.getName().getAsString() +
10255                                               " = ");
10256         } else {
10257           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10258           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10259           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10260             << 1 // typedef declaration
10261             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10262             << FixItHint::CreateInsertion(
10263                    InsertLoc, " " + NameInfo.getName().getAsString());
10264         }
10265       } else if (R.getAsSingle<VarDecl>()) {
10266         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10267         // repeating the type of the static data member here.
10268         FixItHint FixIt;
10269         if (getLangOpts().CPlusPlus11) {
10270           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10271           FixIt = FixItHint::CreateReplacement(
10272               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10273         }
10274 
10275         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10276           << 2 // reference declaration
10277           << FixIt;
10278       } else if (R.getAsSingle<EnumConstantDecl>()) {
10279         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10280         // repeating the type of the enumeration here, and we can't do so if
10281         // the type is anonymous.
10282         FixItHint FixIt;
10283         if (getLangOpts().CPlusPlus11) {
10284           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10285           FixIt = FixItHint::CreateReplacement(
10286               UsingLoc,
10287               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10288         }
10289 
10290         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10291           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10292           << FixIt;
10293       }
10294       return true;
10295     }
10296 
10297     // Otherwise, this might be valid.
10298     return false;
10299   }
10300 
10301   // The current scope is a record.
10302 
10303   // If the named context is dependent, we can't decide much.
10304   if (!NamedContext) {
10305     // FIXME: in C++0x, we can diagnose if we can prove that the
10306     // nested-name-specifier does not refer to a base class, which is
10307     // still possible in some cases.
10308 
10309     // Otherwise we have to conservatively report that things might be
10310     // okay.
10311     return false;
10312   }
10313 
10314   if (!NamedContext->isRecord()) {
10315     // Ideally this would point at the last name in the specifier,
10316     // but we don't have that level of source info.
10317     Diag(SS.getRange().getBegin(),
10318          diag::err_using_decl_nested_name_specifier_is_not_class)
10319       << SS.getScopeRep() << SS.getRange();
10320     return true;
10321   }
10322 
10323   if (!NamedContext->isDependentContext() &&
10324       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10325     return true;
10326 
10327   if (getLangOpts().CPlusPlus11) {
10328     // C++11 [namespace.udecl]p3:
10329     //   In a using-declaration used as a member-declaration, the
10330     //   nested-name-specifier shall name a base class of the class
10331     //   being defined.
10332 
10333     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10334                                  cast<CXXRecordDecl>(NamedContext))) {
10335       if (CurContext == NamedContext) {
10336         Diag(NameLoc,
10337              diag::err_using_decl_nested_name_specifier_is_current_class)
10338           << SS.getRange();
10339         return true;
10340       }
10341 
10342       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10343         Diag(SS.getRange().getBegin(),
10344              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10345           << SS.getScopeRep()
10346           << cast<CXXRecordDecl>(CurContext)
10347           << SS.getRange();
10348       }
10349       return true;
10350     }
10351 
10352     return false;
10353   }
10354 
10355   // C++03 [namespace.udecl]p4:
10356   //   A using-declaration used as a member-declaration shall refer
10357   //   to a member of a base class of the class being defined [etc.].
10358 
10359   // Salient point: SS doesn't have to name a base class as long as
10360   // lookup only finds members from base classes.  Therefore we can
10361   // diagnose here only if we can prove that that can't happen,
10362   // i.e. if the class hierarchies provably don't intersect.
10363 
10364   // TODO: it would be nice if "definitely valid" results were cached
10365   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10366   // need to be repeated.
10367 
10368   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10369   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10370     Bases.insert(Base);
10371     return true;
10372   };
10373 
10374   // Collect all bases. Return false if we find a dependent base.
10375   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10376     return false;
10377 
10378   // Returns true if the base is dependent or is one of the accumulated base
10379   // classes.
10380   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10381     return !Bases.count(Base);
10382   };
10383 
10384   // Return false if the class has a dependent base or if it or one
10385   // of its bases is present in the base set of the current context.
10386   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10387       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10388     return false;
10389 
10390   Diag(SS.getRange().getBegin(),
10391        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10392     << SS.getScopeRep()
10393     << cast<CXXRecordDecl>(CurContext)
10394     << SS.getRange();
10395 
10396   return true;
10397 }
10398 
10399 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10400                                   MultiTemplateParamsArg TemplateParamLists,
10401                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10402                                   const ParsedAttributesView &AttrList,
10403                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10404   // Skip up to the relevant declaration scope.
10405   while (S->isTemplateParamScope())
10406     S = S->getParent();
10407   assert((S->getFlags() & Scope::DeclScope) &&
10408          "got alias-declaration outside of declaration scope");
10409 
10410   if (Type.isInvalid())
10411     return nullptr;
10412 
10413   bool Invalid = false;
10414   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10415   TypeSourceInfo *TInfo = nullptr;
10416   GetTypeFromParser(Type.get(), &TInfo);
10417 
10418   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10419     return nullptr;
10420 
10421   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10422                                       UPPC_DeclarationType)) {
10423     Invalid = true;
10424     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10425                                              TInfo->getTypeLoc().getBeginLoc());
10426   }
10427 
10428   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10429                         TemplateParamLists.size()
10430                             ? forRedeclarationInCurContext()
10431                             : ForVisibleRedeclaration);
10432   LookupName(Previous, S);
10433 
10434   // Warn about shadowing the name of a template parameter.
10435   if (Previous.isSingleResult() &&
10436       Previous.getFoundDecl()->isTemplateParameter()) {
10437     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10438     Previous.clear();
10439   }
10440 
10441   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10442          "name in alias declaration must be an identifier");
10443   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10444                                                Name.StartLocation,
10445                                                Name.Identifier, TInfo);
10446 
10447   NewTD->setAccess(AS);
10448 
10449   if (Invalid)
10450     NewTD->setInvalidDecl();
10451 
10452   ProcessDeclAttributeList(S, NewTD, AttrList);
10453   AddPragmaAttributes(S, NewTD);
10454 
10455   CheckTypedefForVariablyModifiedType(S, NewTD);
10456   Invalid |= NewTD->isInvalidDecl();
10457 
10458   bool Redeclaration = false;
10459 
10460   NamedDecl *NewND;
10461   if (TemplateParamLists.size()) {
10462     TypeAliasTemplateDecl *OldDecl = nullptr;
10463     TemplateParameterList *OldTemplateParams = nullptr;
10464 
10465     if (TemplateParamLists.size() != 1) {
10466       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10467         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10468          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10469     }
10470     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10471 
10472     // Check that we can declare a template here.
10473     if (CheckTemplateDeclScope(S, TemplateParams))
10474       return nullptr;
10475 
10476     // Only consider previous declarations in the same scope.
10477     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10478                          /*ExplicitInstantiationOrSpecialization*/false);
10479     if (!Previous.empty()) {
10480       Redeclaration = true;
10481 
10482       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10483       if (!OldDecl && !Invalid) {
10484         Diag(UsingLoc, diag::err_redefinition_different_kind)
10485           << Name.Identifier;
10486 
10487         NamedDecl *OldD = Previous.getRepresentativeDecl();
10488         if (OldD->getLocation().isValid())
10489           Diag(OldD->getLocation(), diag::note_previous_definition);
10490 
10491         Invalid = true;
10492       }
10493 
10494       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10495         if (TemplateParameterListsAreEqual(TemplateParams,
10496                                            OldDecl->getTemplateParameters(),
10497                                            /*Complain=*/true,
10498                                            TPL_TemplateMatch))
10499           OldTemplateParams =
10500               OldDecl->getMostRecentDecl()->getTemplateParameters();
10501         else
10502           Invalid = true;
10503 
10504         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10505         if (!Invalid &&
10506             !Context.hasSameType(OldTD->getUnderlyingType(),
10507                                  NewTD->getUnderlyingType())) {
10508           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10509           // but we can't reasonably accept it.
10510           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10511             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10512           if (OldTD->getLocation().isValid())
10513             Diag(OldTD->getLocation(), diag::note_previous_definition);
10514           Invalid = true;
10515         }
10516       }
10517     }
10518 
10519     // Merge any previous default template arguments into our parameters,
10520     // and check the parameter list.
10521     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10522                                    TPC_TypeAliasTemplate))
10523       return nullptr;
10524 
10525     TypeAliasTemplateDecl *NewDecl =
10526       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10527                                     Name.Identifier, TemplateParams,
10528                                     NewTD);
10529     NewTD->setDescribedAliasTemplate(NewDecl);
10530 
10531     NewDecl->setAccess(AS);
10532 
10533     if (Invalid)
10534       NewDecl->setInvalidDecl();
10535     else if (OldDecl) {
10536       NewDecl->setPreviousDecl(OldDecl);
10537       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10538     }
10539 
10540     NewND = NewDecl;
10541   } else {
10542     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10543       setTagNameForLinkagePurposes(TD, NewTD);
10544       handleTagNumbering(TD, S);
10545     }
10546     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10547     NewND = NewTD;
10548   }
10549 
10550   PushOnScopeChains(NewND, S);
10551   ActOnDocumentableDecl(NewND);
10552   return NewND;
10553 }
10554 
10555 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10556                                    SourceLocation AliasLoc,
10557                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10558                                    SourceLocation IdentLoc,
10559                                    IdentifierInfo *Ident) {
10560 
10561   // Lookup the namespace name.
10562   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10563   LookupParsedName(R, S, &SS);
10564 
10565   if (R.isAmbiguous())
10566     return nullptr;
10567 
10568   if (R.empty()) {
10569     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10570       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10571       return nullptr;
10572     }
10573   }
10574   assert(!R.isAmbiguous() && !R.empty());
10575   NamedDecl *ND = R.getRepresentativeDecl();
10576 
10577   // Check if we have a previous declaration with the same name.
10578   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10579                      ForVisibleRedeclaration);
10580   LookupName(PrevR, S);
10581 
10582   // Check we're not shadowing a template parameter.
10583   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10584     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10585     PrevR.clear();
10586   }
10587 
10588   // Filter out any other lookup result from an enclosing scope.
10589   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10590                        /*AllowInlineNamespace*/false);
10591 
10592   // Find the previous declaration and check that we can redeclare it.
10593   NamespaceAliasDecl *Prev = nullptr;
10594   if (PrevR.isSingleResult()) {
10595     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10596     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10597       // We already have an alias with the same name that points to the same
10598       // namespace; check that it matches.
10599       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10600         Prev = AD;
10601       } else if (isVisible(PrevDecl)) {
10602         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10603           << Alias;
10604         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10605           << AD->getNamespace();
10606         return nullptr;
10607       }
10608     } else if (isVisible(PrevDecl)) {
10609       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10610                             ? diag::err_redefinition
10611                             : diag::err_redefinition_different_kind;
10612       Diag(AliasLoc, DiagID) << Alias;
10613       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10614       return nullptr;
10615     }
10616   }
10617 
10618   // The use of a nested name specifier may trigger deprecation warnings.
10619   DiagnoseUseOfDecl(ND, IdentLoc);
10620 
10621   NamespaceAliasDecl *AliasDecl =
10622     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10623                                Alias, SS.getWithLocInContext(Context),
10624                                IdentLoc, ND);
10625   if (Prev)
10626     AliasDecl->setPreviousDecl(Prev);
10627 
10628   PushOnScopeChains(AliasDecl, S);
10629   return AliasDecl;
10630 }
10631 
10632 namespace {
10633 struct SpecialMemberExceptionSpecInfo
10634     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10635   SourceLocation Loc;
10636   Sema::ImplicitExceptionSpecification ExceptSpec;
10637 
10638   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10639                                  Sema::CXXSpecialMember CSM,
10640                                  Sema::InheritedConstructorInfo *ICI,
10641                                  SourceLocation Loc)
10642       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10643 
10644   bool visitBase(CXXBaseSpecifier *Base);
10645   bool visitField(FieldDecl *FD);
10646 
10647   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10648                            unsigned Quals);
10649 
10650   void visitSubobjectCall(Subobject Subobj,
10651                           Sema::SpecialMemberOverloadResult SMOR);
10652 };
10653 }
10654 
10655 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10656   auto *RT = Base->getType()->getAs<RecordType>();
10657   if (!RT)
10658     return false;
10659 
10660   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10661   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10662   if (auto *BaseCtor = SMOR.getMethod()) {
10663     visitSubobjectCall(Base, BaseCtor);
10664     return false;
10665   }
10666 
10667   visitClassSubobject(BaseClass, Base, 0);
10668   return false;
10669 }
10670 
10671 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10672   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10673     Expr *E = FD->getInClassInitializer();
10674     if (!E)
10675       // FIXME: It's a little wasteful to build and throw away a
10676       // CXXDefaultInitExpr here.
10677       // FIXME: We should have a single context note pointing at Loc, and
10678       // this location should be MD->getLocation() instead, since that's
10679       // the location where we actually use the default init expression.
10680       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10681     if (E)
10682       ExceptSpec.CalledExpr(E);
10683   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10684                             ->getAs<RecordType>()) {
10685     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10686                         FD->getType().getCVRQualifiers());
10687   }
10688   return false;
10689 }
10690 
10691 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10692                                                          Subobject Subobj,
10693                                                          unsigned Quals) {
10694   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10695   bool IsMutable = Field && Field->isMutable();
10696   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10697 }
10698 
10699 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10700     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10701   // Note, if lookup fails, it doesn't matter what exception specification we
10702   // choose because the special member will be deleted.
10703   if (CXXMethodDecl *MD = SMOR.getMethod())
10704     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10705 }
10706 
10707 namespace {
10708 /// RAII object to register a special member as being currently declared.
10709 struct ComputingExceptionSpec {
10710   Sema &S;
10711 
10712   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10713       : S(S) {
10714     Sema::CodeSynthesisContext Ctx;
10715     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10716     Ctx.PointOfInstantiation = Loc;
10717     Ctx.Entity = MD;
10718     S.pushCodeSynthesisContext(Ctx);
10719   }
10720   ~ComputingExceptionSpec() {
10721     S.popCodeSynthesisContext();
10722   }
10723 };
10724 }
10725 
10726 static Sema::ImplicitExceptionSpecification
10727 ComputeDefaultedSpecialMemberExceptionSpec(
10728     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10729     Sema::InheritedConstructorInfo *ICI) {
10730   ComputingExceptionSpec CES(S, MD, Loc);
10731 
10732   CXXRecordDecl *ClassDecl = MD->getParent();
10733 
10734   // C++ [except.spec]p14:
10735   //   An implicitly declared special member function (Clause 12) shall have an
10736   //   exception-specification. [...]
10737   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10738   if (ClassDecl->isInvalidDecl())
10739     return Info.ExceptSpec;
10740 
10741   // FIXME: If this diagnostic fires, we're probably missing a check for
10742   // attempting to resolve an exception specification before it's known
10743   // at a higher level.
10744   if (S.RequireCompleteType(MD->getLocation(),
10745                             S.Context.getRecordType(ClassDecl),
10746                             diag::err_exception_spec_incomplete_type))
10747     return Info.ExceptSpec;
10748 
10749   // C++1z [except.spec]p7:
10750   //   [Look for exceptions thrown by] a constructor selected [...] to
10751   //   initialize a potentially constructed subobject,
10752   // C++1z [except.spec]p8:
10753   //   The exception specification for an implicitly-declared destructor, or a
10754   //   destructor without a noexcept-specifier, is potentially-throwing if and
10755   //   only if any of the destructors for any of its potentially constructed
10756   //   subojects is potentially throwing.
10757   // FIXME: We respect the first rule but ignore the "potentially constructed"
10758   // in the second rule to resolve a core issue (no number yet) that would have
10759   // us reject:
10760   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10761   //   struct B : A {};
10762   //   struct C : B { void f(); };
10763   // ... due to giving B::~B() a non-throwing exception specification.
10764   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10765                                 : Info.VisitAllBases);
10766 
10767   return Info.ExceptSpec;
10768 }
10769 
10770 namespace {
10771 /// RAII object to register a special member as being currently declared.
10772 struct DeclaringSpecialMember {
10773   Sema &S;
10774   Sema::SpecialMemberDecl D;
10775   Sema::ContextRAII SavedContext;
10776   bool WasAlreadyBeingDeclared;
10777 
10778   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10779       : S(S), D(RD, CSM), SavedContext(S, RD) {
10780     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10781     if (WasAlreadyBeingDeclared)
10782       // This almost never happens, but if it does, ensure that our cache
10783       // doesn't contain a stale result.
10784       S.SpecialMemberCache.clear();
10785     else {
10786       // Register a note to be produced if we encounter an error while
10787       // declaring the special member.
10788       Sema::CodeSynthesisContext Ctx;
10789       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10790       // FIXME: We don't have a location to use here. Using the class's
10791       // location maintains the fiction that we declare all special members
10792       // with the class, but (1) it's not clear that lying about that helps our
10793       // users understand what's going on, and (2) there may be outer contexts
10794       // on the stack (some of which are relevant) and printing them exposes
10795       // our lies.
10796       Ctx.PointOfInstantiation = RD->getLocation();
10797       Ctx.Entity = RD;
10798       Ctx.SpecialMember = CSM;
10799       S.pushCodeSynthesisContext(Ctx);
10800     }
10801   }
10802   ~DeclaringSpecialMember() {
10803     if (!WasAlreadyBeingDeclared) {
10804       S.SpecialMembersBeingDeclared.erase(D);
10805       S.popCodeSynthesisContext();
10806     }
10807   }
10808 
10809   /// Are we already trying to declare this special member?
10810   bool isAlreadyBeingDeclared() const {
10811     return WasAlreadyBeingDeclared;
10812   }
10813 };
10814 }
10815 
10816 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10817   // Look up any existing declarations, but don't trigger declaration of all
10818   // implicit special members with this name.
10819   DeclarationName Name = FD->getDeclName();
10820   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10821                  ForExternalRedeclaration);
10822   for (auto *D : FD->getParent()->lookup(Name))
10823     if (auto *Acceptable = R.getAcceptableDecl(D))
10824       R.addDecl(Acceptable);
10825   R.resolveKind();
10826   R.suppressDiagnostics();
10827 
10828   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10829 }
10830 
10831 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10832                                                      CXXRecordDecl *ClassDecl) {
10833   // C++ [class.ctor]p5:
10834   //   A default constructor for a class X is a constructor of class X
10835   //   that can be called without an argument. If there is no
10836   //   user-declared constructor for class X, a default constructor is
10837   //   implicitly declared. An implicitly-declared default constructor
10838   //   is an inline public member of its class.
10839   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10840          "Should not build implicit default constructor!");
10841 
10842   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10843   if (DSM.isAlreadyBeingDeclared())
10844     return nullptr;
10845 
10846   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10847                                                      CXXDefaultConstructor,
10848                                                      false);
10849 
10850   // Create the actual constructor declaration.
10851   CanQualType ClassType
10852     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10853   SourceLocation ClassLoc = ClassDecl->getLocation();
10854   DeclarationName Name
10855     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10856   DeclarationNameInfo NameInfo(Name, ClassLoc);
10857   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10858       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10859       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10860       /*isImplicitlyDeclared=*/true, Constexpr);
10861   DefaultCon->setAccess(AS_public);
10862   DefaultCon->setDefaulted();
10863 
10864   if (getLangOpts().CUDA) {
10865     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10866                                             DefaultCon,
10867                                             /* ConstRHS */ false,
10868                                             /* Diagnose */ false);
10869   }
10870 
10871   // Build an exception specification pointing back at this constructor.
10872   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10873   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10874 
10875   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10876   // constructors is easy to compute.
10877   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10878 
10879   // Note that we have declared this constructor.
10880   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10881 
10882   Scope *S = getScopeForContext(ClassDecl);
10883   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10884 
10885   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10886     SetDeclDeleted(DefaultCon, ClassLoc);
10887 
10888   if (S)
10889     PushOnScopeChains(DefaultCon, S, false);
10890   ClassDecl->addDecl(DefaultCon);
10891 
10892   return DefaultCon;
10893 }
10894 
10895 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10896                                             CXXConstructorDecl *Constructor) {
10897   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10898           !Constructor->doesThisDeclarationHaveABody() &&
10899           !Constructor->isDeleted()) &&
10900     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10901   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10902     return;
10903 
10904   CXXRecordDecl *ClassDecl = Constructor->getParent();
10905   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10906 
10907   SynthesizedFunctionScope Scope(*this, Constructor);
10908 
10909   // The exception specification is needed because we are defining the
10910   // function.
10911   ResolveExceptionSpec(CurrentLocation,
10912                        Constructor->getType()->castAs<FunctionProtoType>());
10913   MarkVTableUsed(CurrentLocation, ClassDecl);
10914 
10915   // Add a context note for diagnostics produced after this point.
10916   Scope.addContextNote(CurrentLocation);
10917 
10918   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10919     Constructor->setInvalidDecl();
10920     return;
10921   }
10922 
10923   SourceLocation Loc = Constructor->getEndLoc().isValid()
10924                            ? Constructor->getEndLoc()
10925                            : Constructor->getLocation();
10926   Constructor->setBody(new (Context) CompoundStmt(Loc));
10927   Constructor->markUsed(Context);
10928 
10929   if (ASTMutationListener *L = getASTMutationListener()) {
10930     L->CompletedImplicitDefinition(Constructor);
10931   }
10932 
10933   DiagnoseUninitializedFields(*this, Constructor);
10934 }
10935 
10936 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10937   // Perform any delayed checks on exception specifications.
10938   CheckDelayedMemberExceptionSpecs();
10939 }
10940 
10941 /// Find or create the fake constructor we synthesize to model constructing an
10942 /// object of a derived class via a constructor of a base class.
10943 CXXConstructorDecl *
10944 Sema::findInheritingConstructor(SourceLocation Loc,
10945                                 CXXConstructorDecl *BaseCtor,
10946                                 ConstructorUsingShadowDecl *Shadow) {
10947   CXXRecordDecl *Derived = Shadow->getParent();
10948   SourceLocation UsingLoc = Shadow->getLocation();
10949 
10950   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10951   // For now we use the name of the base class constructor as a member of the
10952   // derived class to indicate a (fake) inherited constructor name.
10953   DeclarationName Name = BaseCtor->getDeclName();
10954 
10955   // Check to see if we already have a fake constructor for this inherited
10956   // constructor call.
10957   for (NamedDecl *Ctor : Derived->lookup(Name))
10958     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10959                                ->getInheritedConstructor()
10960                                .getConstructor(),
10961                            BaseCtor))
10962       return cast<CXXConstructorDecl>(Ctor);
10963 
10964   DeclarationNameInfo NameInfo(Name, UsingLoc);
10965   TypeSourceInfo *TInfo =
10966       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10967   FunctionProtoTypeLoc ProtoLoc =
10968       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10969 
10970   // Check the inherited constructor is valid and find the list of base classes
10971   // from which it was inherited.
10972   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10973 
10974   bool Constexpr =
10975       BaseCtor->isConstexpr() &&
10976       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10977                                         false, BaseCtor, &ICI);
10978 
10979   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10980       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10981       BaseCtor->isExplicit(), /*Inline=*/true,
10982       /*ImplicitlyDeclared=*/true, Constexpr,
10983       InheritedConstructor(Shadow, BaseCtor));
10984   if (Shadow->isInvalidDecl())
10985     DerivedCtor->setInvalidDecl();
10986 
10987   // Build an unevaluated exception specification for this fake constructor.
10988   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10989   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10990   EPI.ExceptionSpec.Type = EST_Unevaluated;
10991   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10992   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10993                                                FPT->getParamTypes(), EPI));
10994 
10995   // Build the parameter declarations.
10996   SmallVector<ParmVarDecl *, 16> ParamDecls;
10997   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10998     TypeSourceInfo *TInfo =
10999         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11000     ParmVarDecl *PD = ParmVarDecl::Create(
11001         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11002         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11003     PD->setScopeInfo(0, I);
11004     PD->setImplicit();
11005     // Ensure attributes are propagated onto parameters (this matters for
11006     // format, pass_object_size, ...).
11007     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11008     ParamDecls.push_back(PD);
11009     ProtoLoc.setParam(I, PD);
11010   }
11011 
11012   // Set up the new constructor.
11013   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11014   DerivedCtor->setAccess(BaseCtor->getAccess());
11015   DerivedCtor->setParams(ParamDecls);
11016   Derived->addDecl(DerivedCtor);
11017 
11018   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11019     SetDeclDeleted(DerivedCtor, UsingLoc);
11020 
11021   return DerivedCtor;
11022 }
11023 
11024 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11025   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11026                                Ctor->getInheritedConstructor().getShadowDecl());
11027   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11028                             /*Diagnose*/true);
11029 }
11030 
11031 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11032                                        CXXConstructorDecl *Constructor) {
11033   CXXRecordDecl *ClassDecl = Constructor->getParent();
11034   assert(Constructor->getInheritedConstructor() &&
11035          !Constructor->doesThisDeclarationHaveABody() &&
11036          !Constructor->isDeleted());
11037   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11038     return;
11039 
11040   // Initializations are performed "as if by a defaulted default constructor",
11041   // so enter the appropriate scope.
11042   SynthesizedFunctionScope Scope(*this, Constructor);
11043 
11044   // The exception specification is needed because we are defining the
11045   // function.
11046   ResolveExceptionSpec(CurrentLocation,
11047                        Constructor->getType()->castAs<FunctionProtoType>());
11048   MarkVTableUsed(CurrentLocation, ClassDecl);
11049 
11050   // Add a context note for diagnostics produced after this point.
11051   Scope.addContextNote(CurrentLocation);
11052 
11053   ConstructorUsingShadowDecl *Shadow =
11054       Constructor->getInheritedConstructor().getShadowDecl();
11055   CXXConstructorDecl *InheritedCtor =
11056       Constructor->getInheritedConstructor().getConstructor();
11057 
11058   // [class.inhctor.init]p1:
11059   //   initialization proceeds as if a defaulted default constructor is used to
11060   //   initialize the D object and each base class subobject from which the
11061   //   constructor was inherited
11062 
11063   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11064   CXXRecordDecl *RD = Shadow->getParent();
11065   SourceLocation InitLoc = Shadow->getLocation();
11066 
11067   // Build explicit initializers for all base classes from which the
11068   // constructor was inherited.
11069   SmallVector<CXXCtorInitializer*, 8> Inits;
11070   for (bool VBase : {false, true}) {
11071     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11072       if (B.isVirtual() != VBase)
11073         continue;
11074 
11075       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11076       if (!BaseRD)
11077         continue;
11078 
11079       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11080       if (!BaseCtor.first)
11081         continue;
11082 
11083       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11084       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11085           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11086 
11087       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11088       Inits.push_back(new (Context) CXXCtorInitializer(
11089           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11090           SourceLocation()));
11091     }
11092   }
11093 
11094   // We now proceed as if for a defaulted default constructor, with the relevant
11095   // initializers replaced.
11096 
11097   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11098     Constructor->setInvalidDecl();
11099     return;
11100   }
11101 
11102   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11103   Constructor->markUsed(Context);
11104 
11105   if (ASTMutationListener *L = getASTMutationListener()) {
11106     L->CompletedImplicitDefinition(Constructor);
11107   }
11108 
11109   DiagnoseUninitializedFields(*this, Constructor);
11110 }
11111 
11112 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11113   // C++ [class.dtor]p2:
11114   //   If a class has no user-declared destructor, a destructor is
11115   //   declared implicitly. An implicitly-declared destructor is an
11116   //   inline public member of its class.
11117   assert(ClassDecl->needsImplicitDestructor());
11118 
11119   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11120   if (DSM.isAlreadyBeingDeclared())
11121     return nullptr;
11122 
11123   // Create the actual destructor declaration.
11124   CanQualType ClassType
11125     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11126   SourceLocation ClassLoc = ClassDecl->getLocation();
11127   DeclarationName Name
11128     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11129   DeclarationNameInfo NameInfo(Name, ClassLoc);
11130   CXXDestructorDecl *Destructor
11131       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11132                                   QualType(), nullptr, /*isInline=*/true,
11133                                   /*isImplicitlyDeclared=*/true);
11134   Destructor->setAccess(AS_public);
11135   Destructor->setDefaulted();
11136 
11137   if (getLangOpts().CUDA) {
11138     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11139                                             Destructor,
11140                                             /* ConstRHS */ false,
11141                                             /* Diagnose */ false);
11142   }
11143 
11144   // Build an exception specification pointing back at this destructor.
11145   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11146   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11147 
11148   // We don't need to use SpecialMemberIsTrivial here; triviality for
11149   // destructors is easy to compute.
11150   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11151   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11152                                 ClassDecl->hasTrivialDestructorForCall());
11153 
11154   // Note that we have declared this destructor.
11155   ++ASTContext::NumImplicitDestructorsDeclared;
11156 
11157   Scope *S = getScopeForContext(ClassDecl);
11158   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11159 
11160   // We can't check whether an implicit destructor is deleted before we complete
11161   // the definition of the class, because its validity depends on the alignment
11162   // of the class. We'll check this from ActOnFields once the class is complete.
11163   if (ClassDecl->isCompleteDefinition() &&
11164       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11165     SetDeclDeleted(Destructor, ClassLoc);
11166 
11167   // Introduce this destructor into its scope.
11168   if (S)
11169     PushOnScopeChains(Destructor, S, false);
11170   ClassDecl->addDecl(Destructor);
11171 
11172   return Destructor;
11173 }
11174 
11175 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11176                                     CXXDestructorDecl *Destructor) {
11177   assert((Destructor->isDefaulted() &&
11178           !Destructor->doesThisDeclarationHaveABody() &&
11179           !Destructor->isDeleted()) &&
11180          "DefineImplicitDestructor - call it for implicit default dtor");
11181   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11182     return;
11183 
11184   CXXRecordDecl *ClassDecl = Destructor->getParent();
11185   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11186 
11187   SynthesizedFunctionScope Scope(*this, Destructor);
11188 
11189   // The exception specification is needed because we are defining the
11190   // function.
11191   ResolveExceptionSpec(CurrentLocation,
11192                        Destructor->getType()->castAs<FunctionProtoType>());
11193   MarkVTableUsed(CurrentLocation, ClassDecl);
11194 
11195   // Add a context note for diagnostics produced after this point.
11196   Scope.addContextNote(CurrentLocation);
11197 
11198   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11199                                          Destructor->getParent());
11200 
11201   if (CheckDestructor(Destructor)) {
11202     Destructor->setInvalidDecl();
11203     return;
11204   }
11205 
11206   SourceLocation Loc = Destructor->getEndLoc().isValid()
11207                            ? Destructor->getEndLoc()
11208                            : Destructor->getLocation();
11209   Destructor->setBody(new (Context) CompoundStmt(Loc));
11210   Destructor->markUsed(Context);
11211 
11212   if (ASTMutationListener *L = getASTMutationListener()) {
11213     L->CompletedImplicitDefinition(Destructor);
11214   }
11215 }
11216 
11217 /// Perform any semantic analysis which needs to be delayed until all
11218 /// pending class member declarations have been parsed.
11219 void Sema::ActOnFinishCXXMemberDecls() {
11220   // If the context is an invalid C++ class, just suppress these checks.
11221   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11222     if (Record->isInvalidDecl()) {
11223       DelayedOverridingExceptionSpecChecks.clear();
11224       DelayedEquivalentExceptionSpecChecks.clear();
11225       DelayedDefaultedMemberExceptionSpecs.clear();
11226       return;
11227     }
11228     checkForMultipleExportedDefaultConstructors(*this, Record);
11229   }
11230 }
11231 
11232 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11233   referenceDLLExportedClassMethods();
11234 }
11235 
11236 void Sema::referenceDLLExportedClassMethods() {
11237   if (!DelayedDllExportClasses.empty()) {
11238     // Calling ReferenceDllExportedMembers might cause the current function to
11239     // be called again, so use a local copy of DelayedDllExportClasses.
11240     SmallVector<CXXRecordDecl *, 4> WorkList;
11241     std::swap(DelayedDllExportClasses, WorkList);
11242     for (CXXRecordDecl *Class : WorkList)
11243       ReferenceDllExportedMembers(*this, Class);
11244   }
11245 }
11246 
11247 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11248   assert(getLangOpts().CPlusPlus11 &&
11249          "adjusting dtor exception specs was introduced in c++11");
11250 
11251   if (Destructor->isDependentContext())
11252     return;
11253 
11254   // C++11 [class.dtor]p3:
11255   //   A declaration of a destructor that does not have an exception-
11256   //   specification is implicitly considered to have the same exception-
11257   //   specification as an implicit declaration.
11258   const FunctionProtoType *DtorType = Destructor->getType()->
11259                                         getAs<FunctionProtoType>();
11260   if (DtorType->hasExceptionSpec())
11261     return;
11262 
11263   // Replace the destructor's type, building off the existing one. Fortunately,
11264   // the only thing of interest in the destructor type is its extended info.
11265   // The return and arguments are fixed.
11266   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11267   EPI.ExceptionSpec.Type = EST_Unevaluated;
11268   EPI.ExceptionSpec.SourceDecl = Destructor;
11269   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11270 
11271   // FIXME: If the destructor has a body that could throw, and the newly created
11272   // spec doesn't allow exceptions, we should emit a warning, because this
11273   // change in behavior can break conforming C++03 programs at runtime.
11274   // However, we don't have a body or an exception specification yet, so it
11275   // needs to be done somewhere else.
11276 }
11277 
11278 namespace {
11279 /// An abstract base class for all helper classes used in building the
11280 //  copy/move operators. These classes serve as factory functions and help us
11281 //  avoid using the same Expr* in the AST twice.
11282 class ExprBuilder {
11283   ExprBuilder(const ExprBuilder&) = delete;
11284   ExprBuilder &operator=(const ExprBuilder&) = delete;
11285 
11286 protected:
11287   static Expr *assertNotNull(Expr *E) {
11288     assert(E && "Expression construction must not fail.");
11289     return E;
11290   }
11291 
11292 public:
11293   ExprBuilder() {}
11294   virtual ~ExprBuilder() {}
11295 
11296   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11297 };
11298 
11299 class RefBuilder: public ExprBuilder {
11300   VarDecl *Var;
11301   QualType VarType;
11302 
11303 public:
11304   Expr *build(Sema &S, SourceLocation Loc) const override {
11305     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11306   }
11307 
11308   RefBuilder(VarDecl *Var, QualType VarType)
11309       : Var(Var), VarType(VarType) {}
11310 };
11311 
11312 class ThisBuilder: public ExprBuilder {
11313 public:
11314   Expr *build(Sema &S, SourceLocation Loc) const override {
11315     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11316   }
11317 };
11318 
11319 class CastBuilder: public ExprBuilder {
11320   const ExprBuilder &Builder;
11321   QualType Type;
11322   ExprValueKind Kind;
11323   const CXXCastPath &Path;
11324 
11325 public:
11326   Expr *build(Sema &S, SourceLocation Loc) const override {
11327     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11328                                              CK_UncheckedDerivedToBase, Kind,
11329                                              &Path).get());
11330   }
11331 
11332   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11333               const CXXCastPath &Path)
11334       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11335 };
11336 
11337 class DerefBuilder: public ExprBuilder {
11338   const ExprBuilder &Builder;
11339 
11340 public:
11341   Expr *build(Sema &S, SourceLocation Loc) const override {
11342     return assertNotNull(
11343         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11344   }
11345 
11346   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11347 };
11348 
11349 class MemberBuilder: public ExprBuilder {
11350   const ExprBuilder &Builder;
11351   QualType Type;
11352   CXXScopeSpec SS;
11353   bool IsArrow;
11354   LookupResult &MemberLookup;
11355 
11356 public:
11357   Expr *build(Sema &S, SourceLocation Loc) const override {
11358     return assertNotNull(S.BuildMemberReferenceExpr(
11359         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11360         nullptr, MemberLookup, nullptr, nullptr).get());
11361   }
11362 
11363   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11364                 LookupResult &MemberLookup)
11365       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11366         MemberLookup(MemberLookup) {}
11367 };
11368 
11369 class MoveCastBuilder: public ExprBuilder {
11370   const ExprBuilder &Builder;
11371 
11372 public:
11373   Expr *build(Sema &S, SourceLocation Loc) const override {
11374     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11375   }
11376 
11377   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11378 };
11379 
11380 class LvalueConvBuilder: public ExprBuilder {
11381   const ExprBuilder &Builder;
11382 
11383 public:
11384   Expr *build(Sema &S, SourceLocation Loc) const override {
11385     return assertNotNull(
11386         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11387   }
11388 
11389   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11390 };
11391 
11392 class SubscriptBuilder: public ExprBuilder {
11393   const ExprBuilder &Base;
11394   const ExprBuilder &Index;
11395 
11396 public:
11397   Expr *build(Sema &S, SourceLocation Loc) const override {
11398     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11399         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11400   }
11401 
11402   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11403       : Base(Base), Index(Index) {}
11404 };
11405 
11406 } // end anonymous namespace
11407 
11408 /// When generating a defaulted copy or move assignment operator, if a field
11409 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11410 /// do so. This optimization only applies for arrays of scalars, and for arrays
11411 /// of class type where the selected copy/move-assignment operator is trivial.
11412 static StmtResult
11413 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11414                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11415   // Compute the size of the memory buffer to be copied.
11416   QualType SizeType = S.Context.getSizeType();
11417   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11418                    S.Context.getTypeSizeInChars(T).getQuantity());
11419 
11420   // Take the address of the field references for "from" and "to". We
11421   // directly construct UnaryOperators here because semantic analysis
11422   // does not permit us to take the address of an xvalue.
11423   Expr *From = FromB.build(S, Loc);
11424   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11425                          S.Context.getPointerType(From->getType()),
11426                          VK_RValue, OK_Ordinary, Loc, false);
11427   Expr *To = ToB.build(S, Loc);
11428   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11429                        S.Context.getPointerType(To->getType()),
11430                        VK_RValue, OK_Ordinary, Loc, false);
11431 
11432   const Type *E = T->getBaseElementTypeUnsafe();
11433   bool NeedsCollectableMemCpy =
11434     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11435 
11436   // Create a reference to the __builtin_objc_memmove_collectable function
11437   StringRef MemCpyName = NeedsCollectableMemCpy ?
11438     "__builtin_objc_memmove_collectable" :
11439     "__builtin_memcpy";
11440   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11441                  Sema::LookupOrdinaryName);
11442   S.LookupName(R, S.TUScope, true);
11443 
11444   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11445   if (!MemCpy)
11446     // Something went horribly wrong earlier, and we will have complained
11447     // about it.
11448     return StmtError();
11449 
11450   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11451                                             VK_RValue, Loc, nullptr);
11452   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11453 
11454   Expr *CallArgs[] = {
11455     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11456   };
11457   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11458                                     Loc, CallArgs, Loc);
11459 
11460   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11461   return Call.getAs<Stmt>();
11462 }
11463 
11464 /// Builds a statement that copies/moves the given entity from \p From to
11465 /// \c To.
11466 ///
11467 /// This routine is used to copy/move the members of a class with an
11468 /// implicitly-declared copy/move assignment operator. When the entities being
11469 /// copied are arrays, this routine builds for loops to copy them.
11470 ///
11471 /// \param S The Sema object used for type-checking.
11472 ///
11473 /// \param Loc The location where the implicit copy/move is being generated.
11474 ///
11475 /// \param T The type of the expressions being copied/moved. Both expressions
11476 /// must have this type.
11477 ///
11478 /// \param To The expression we are copying/moving to.
11479 ///
11480 /// \param From The expression we are copying/moving from.
11481 ///
11482 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11483 /// Otherwise, it's a non-static member subobject.
11484 ///
11485 /// \param Copying Whether we're copying or moving.
11486 ///
11487 /// \param Depth Internal parameter recording the depth of the recursion.
11488 ///
11489 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11490 /// if a memcpy should be used instead.
11491 static StmtResult
11492 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11493                                  const ExprBuilder &To, const ExprBuilder &From,
11494                                  bool CopyingBaseSubobject, bool Copying,
11495                                  unsigned Depth = 0) {
11496   // C++11 [class.copy]p28:
11497   //   Each subobject is assigned in the manner appropriate to its type:
11498   //
11499   //     - if the subobject is of class type, as if by a call to operator= with
11500   //       the subobject as the object expression and the corresponding
11501   //       subobject of x as a single function argument (as if by explicit
11502   //       qualification; that is, ignoring any possible virtual overriding
11503   //       functions in more derived classes);
11504   //
11505   // C++03 [class.copy]p13:
11506   //     - if the subobject is of class type, the copy assignment operator for
11507   //       the class is used (as if by explicit qualification; that is,
11508   //       ignoring any possible virtual overriding functions in more derived
11509   //       classes);
11510   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11511     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11512 
11513     // Look for operator=.
11514     DeclarationName Name
11515       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11516     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11517     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11518 
11519     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11520     // operator.
11521     if (!S.getLangOpts().CPlusPlus11) {
11522       LookupResult::Filter F = OpLookup.makeFilter();
11523       while (F.hasNext()) {
11524         NamedDecl *D = F.next();
11525         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11526           if (Method->isCopyAssignmentOperator() ||
11527               (!Copying && Method->isMoveAssignmentOperator()))
11528             continue;
11529 
11530         F.erase();
11531       }
11532       F.done();
11533     }
11534 
11535     // Suppress the protected check (C++ [class.protected]) for each of the
11536     // assignment operators we found. This strange dance is required when
11537     // we're assigning via a base classes's copy-assignment operator. To
11538     // ensure that we're getting the right base class subobject (without
11539     // ambiguities), we need to cast "this" to that subobject type; to
11540     // ensure that we don't go through the virtual call mechanism, we need
11541     // to qualify the operator= name with the base class (see below). However,
11542     // this means that if the base class has a protected copy assignment
11543     // operator, the protected member access check will fail. So, we
11544     // rewrite "protected" access to "public" access in this case, since we
11545     // know by construction that we're calling from a derived class.
11546     if (CopyingBaseSubobject) {
11547       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11548            L != LEnd; ++L) {
11549         if (L.getAccess() == AS_protected)
11550           L.setAccess(AS_public);
11551       }
11552     }
11553 
11554     // Create the nested-name-specifier that will be used to qualify the
11555     // reference to operator=; this is required to suppress the virtual
11556     // call mechanism.
11557     CXXScopeSpec SS;
11558     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11559     SS.MakeTrivial(S.Context,
11560                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11561                                                CanonicalT),
11562                    Loc);
11563 
11564     // Create the reference to operator=.
11565     ExprResult OpEqualRef
11566       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11567                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11568                                    /*FirstQualifierInScope=*/nullptr,
11569                                    OpLookup,
11570                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11571                                    /*SuppressQualifierCheck=*/true);
11572     if (OpEqualRef.isInvalid())
11573       return StmtError();
11574 
11575     // Build the call to the assignment operator.
11576 
11577     Expr *FromInst = From.build(S, Loc);
11578     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11579                                                   OpEqualRef.getAs<Expr>(),
11580                                                   Loc, FromInst, Loc);
11581     if (Call.isInvalid())
11582       return StmtError();
11583 
11584     // If we built a call to a trivial 'operator=' while copying an array,
11585     // bail out. We'll replace the whole shebang with a memcpy.
11586     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11587     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11588       return StmtResult((Stmt*)nullptr);
11589 
11590     // Convert to an expression-statement, and clean up any produced
11591     // temporaries.
11592     return S.ActOnExprStmt(Call);
11593   }
11594 
11595   //     - if the subobject is of scalar type, the built-in assignment
11596   //       operator is used.
11597   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11598   if (!ArrayTy) {
11599     ExprResult Assignment = S.CreateBuiltinBinOp(
11600         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11601     if (Assignment.isInvalid())
11602       return StmtError();
11603     return S.ActOnExprStmt(Assignment);
11604   }
11605 
11606   //     - if the subobject is an array, each element is assigned, in the
11607   //       manner appropriate to the element type;
11608 
11609   // Construct a loop over the array bounds, e.g.,
11610   //
11611   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11612   //
11613   // that will copy each of the array elements.
11614   QualType SizeType = S.Context.getSizeType();
11615 
11616   // Create the iteration variable.
11617   IdentifierInfo *IterationVarName = nullptr;
11618   {
11619     SmallString<8> Str;
11620     llvm::raw_svector_ostream OS(Str);
11621     OS << "__i" << Depth;
11622     IterationVarName = &S.Context.Idents.get(OS.str());
11623   }
11624   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11625                                           IterationVarName, SizeType,
11626                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11627                                           SC_None);
11628 
11629   // Initialize the iteration variable to zero.
11630   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11631   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11632 
11633   // Creates a reference to the iteration variable.
11634   RefBuilder IterationVarRef(IterationVar, SizeType);
11635   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11636 
11637   // Create the DeclStmt that holds the iteration variable.
11638   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11639 
11640   // Subscript the "from" and "to" expressions with the iteration variable.
11641   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11642   MoveCastBuilder FromIndexMove(FromIndexCopy);
11643   const ExprBuilder *FromIndex;
11644   if (Copying)
11645     FromIndex = &FromIndexCopy;
11646   else
11647     FromIndex = &FromIndexMove;
11648 
11649   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11650 
11651   // Build the copy/move for an individual element of the array.
11652   StmtResult Copy =
11653     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11654                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11655                                      Copying, Depth + 1);
11656   // Bail out if copying fails or if we determined that we should use memcpy.
11657   if (Copy.isInvalid() || !Copy.get())
11658     return Copy;
11659 
11660   // Create the comparison against the array bound.
11661   llvm::APInt Upper
11662     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11663   Expr *Comparison
11664     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11665                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11666                                      BO_NE, S.Context.BoolTy,
11667                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11668 
11669   // Create the pre-increment of the iteration variable. We can determine
11670   // whether the increment will overflow based on the value of the array
11671   // bound.
11672   Expr *Increment = new (S.Context)
11673       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11674                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11675 
11676   // Construct the loop that copies all elements of this array.
11677   return S.ActOnForStmt(
11678       Loc, Loc, InitStmt,
11679       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11680       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11681 }
11682 
11683 static StmtResult
11684 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11685                       const ExprBuilder &To, const ExprBuilder &From,
11686                       bool CopyingBaseSubobject, bool Copying) {
11687   // Maybe we should use a memcpy?
11688   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11689       T.isTriviallyCopyableType(S.Context))
11690     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11691 
11692   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11693                                                      CopyingBaseSubobject,
11694                                                      Copying, 0));
11695 
11696   // If we ended up picking a trivial assignment operator for an array of a
11697   // non-trivially-copyable class type, just emit a memcpy.
11698   if (!Result.isInvalid() && !Result.get())
11699     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11700 
11701   return Result;
11702 }
11703 
11704 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11705   // Note: The following rules are largely analoguous to the copy
11706   // constructor rules. Note that virtual bases are not taken into account
11707   // for determining the argument type of the operator. Note also that
11708   // operators taking an object instead of a reference are allowed.
11709   assert(ClassDecl->needsImplicitCopyAssignment());
11710 
11711   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11712   if (DSM.isAlreadyBeingDeclared())
11713     return nullptr;
11714 
11715   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11716   QualType RetType = Context.getLValueReferenceType(ArgType);
11717   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11718   if (Const)
11719     ArgType = ArgType.withConst();
11720   ArgType = Context.getLValueReferenceType(ArgType);
11721 
11722   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11723                                                      CXXCopyAssignment,
11724                                                      Const);
11725 
11726   //   An implicitly-declared copy assignment operator is an inline public
11727   //   member of its class.
11728   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11729   SourceLocation ClassLoc = ClassDecl->getLocation();
11730   DeclarationNameInfo NameInfo(Name, ClassLoc);
11731   CXXMethodDecl *CopyAssignment =
11732       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11733                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11734                             /*isInline=*/true, Constexpr, SourceLocation());
11735   CopyAssignment->setAccess(AS_public);
11736   CopyAssignment->setDefaulted();
11737   CopyAssignment->setImplicit();
11738 
11739   if (getLangOpts().CUDA) {
11740     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11741                                             CopyAssignment,
11742                                             /* ConstRHS */ Const,
11743                                             /* Diagnose */ false);
11744   }
11745 
11746   // Build an exception specification pointing back at this member.
11747   FunctionProtoType::ExtProtoInfo EPI =
11748       getImplicitMethodEPI(*this, CopyAssignment);
11749   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11750 
11751   // Add the parameter to the operator.
11752   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11753                                                ClassLoc, ClassLoc,
11754                                                /*Id=*/nullptr, ArgType,
11755                                                /*TInfo=*/nullptr, SC_None,
11756                                                nullptr);
11757   CopyAssignment->setParams(FromParam);
11758 
11759   CopyAssignment->setTrivial(
11760     ClassDecl->needsOverloadResolutionForCopyAssignment()
11761       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11762       : ClassDecl->hasTrivialCopyAssignment());
11763 
11764   // Note that we have added this copy-assignment operator.
11765   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11766 
11767   Scope *S = getScopeForContext(ClassDecl);
11768   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11769 
11770   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11771     SetDeclDeleted(CopyAssignment, ClassLoc);
11772 
11773   if (S)
11774     PushOnScopeChains(CopyAssignment, S, false);
11775   ClassDecl->addDecl(CopyAssignment);
11776 
11777   return CopyAssignment;
11778 }
11779 
11780 /// Diagnose an implicit copy operation for a class which is odr-used, but
11781 /// which is deprecated because the class has a user-declared copy constructor,
11782 /// copy assignment operator, or destructor.
11783 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11784   assert(CopyOp->isImplicit());
11785 
11786   CXXRecordDecl *RD = CopyOp->getParent();
11787   CXXMethodDecl *UserDeclaredOperation = nullptr;
11788 
11789   // In Microsoft mode, assignment operations don't affect constructors and
11790   // vice versa.
11791   if (RD->hasUserDeclaredDestructor()) {
11792     UserDeclaredOperation = RD->getDestructor();
11793   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11794              RD->hasUserDeclaredCopyConstructor() &&
11795              !S.getLangOpts().MSVCCompat) {
11796     // Find any user-declared copy constructor.
11797     for (auto *I : RD->ctors()) {
11798       if (I->isCopyConstructor()) {
11799         UserDeclaredOperation = I;
11800         break;
11801       }
11802     }
11803     assert(UserDeclaredOperation);
11804   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11805              RD->hasUserDeclaredCopyAssignment() &&
11806              !S.getLangOpts().MSVCCompat) {
11807     // Find any user-declared move assignment operator.
11808     for (auto *I : RD->methods()) {
11809       if (I->isCopyAssignmentOperator()) {
11810         UserDeclaredOperation = I;
11811         break;
11812       }
11813     }
11814     assert(UserDeclaredOperation);
11815   }
11816 
11817   if (UserDeclaredOperation) {
11818     S.Diag(UserDeclaredOperation->getLocation(),
11819          diag::warn_deprecated_copy_operation)
11820       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11821       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11822   }
11823 }
11824 
11825 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11826                                         CXXMethodDecl *CopyAssignOperator) {
11827   assert((CopyAssignOperator->isDefaulted() &&
11828           CopyAssignOperator->isOverloadedOperator() &&
11829           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11830           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11831           !CopyAssignOperator->isDeleted()) &&
11832          "DefineImplicitCopyAssignment called for wrong function");
11833   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11834     return;
11835 
11836   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11837   if (ClassDecl->isInvalidDecl()) {
11838     CopyAssignOperator->setInvalidDecl();
11839     return;
11840   }
11841 
11842   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11843 
11844   // The exception specification is needed because we are defining the
11845   // function.
11846   ResolveExceptionSpec(CurrentLocation,
11847                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11848 
11849   // Add a context note for diagnostics produced after this point.
11850   Scope.addContextNote(CurrentLocation);
11851 
11852   // C++11 [class.copy]p18:
11853   //   The [definition of an implicitly declared copy assignment operator] is
11854   //   deprecated if the class has a user-declared copy constructor or a
11855   //   user-declared destructor.
11856   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11857     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11858 
11859   // C++0x [class.copy]p30:
11860   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11861   //   for a non-union class X performs memberwise copy assignment of its
11862   //   subobjects. The direct base classes of X are assigned first, in the
11863   //   order of their declaration in the base-specifier-list, and then the
11864   //   immediate non-static data members of X are assigned, in the order in
11865   //   which they were declared in the class definition.
11866 
11867   // The statements that form the synthesized function body.
11868   SmallVector<Stmt*, 8> Statements;
11869 
11870   // The parameter for the "other" object, which we are copying from.
11871   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11872   Qualifiers OtherQuals = Other->getType().getQualifiers();
11873   QualType OtherRefType = Other->getType();
11874   if (const LValueReferenceType *OtherRef
11875                                 = OtherRefType->getAs<LValueReferenceType>()) {
11876     OtherRefType = OtherRef->getPointeeType();
11877     OtherQuals = OtherRefType.getQualifiers();
11878   }
11879 
11880   // Our location for everything implicitly-generated.
11881   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11882                            ? CopyAssignOperator->getEndLoc()
11883                            : CopyAssignOperator->getLocation();
11884 
11885   // Builds a DeclRefExpr for the "other" object.
11886   RefBuilder OtherRef(Other, OtherRefType);
11887 
11888   // Builds the "this" pointer.
11889   ThisBuilder This;
11890 
11891   // Assign base classes.
11892   bool Invalid = false;
11893   for (auto &Base : ClassDecl->bases()) {
11894     // Form the assignment:
11895     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11896     QualType BaseType = Base.getType().getUnqualifiedType();
11897     if (!BaseType->isRecordType()) {
11898       Invalid = true;
11899       continue;
11900     }
11901 
11902     CXXCastPath BasePath;
11903     BasePath.push_back(&Base);
11904 
11905     // Construct the "from" expression, which is an implicit cast to the
11906     // appropriately-qualified base type.
11907     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11908                      VK_LValue, BasePath);
11909 
11910     // Dereference "this".
11911     DerefBuilder DerefThis(This);
11912     CastBuilder To(DerefThis,
11913                    Context.getCVRQualifiedType(
11914                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11915                    VK_LValue, BasePath);
11916 
11917     // Build the copy.
11918     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11919                                             To, From,
11920                                             /*CopyingBaseSubobject=*/true,
11921                                             /*Copying=*/true);
11922     if (Copy.isInvalid()) {
11923       CopyAssignOperator->setInvalidDecl();
11924       return;
11925     }
11926 
11927     // Success! Record the copy.
11928     Statements.push_back(Copy.getAs<Expr>());
11929   }
11930 
11931   // Assign non-static members.
11932   for (auto *Field : ClassDecl->fields()) {
11933     // FIXME: We should form some kind of AST representation for the implied
11934     // memcpy in a union copy operation.
11935     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11936       continue;
11937 
11938     if (Field->isInvalidDecl()) {
11939       Invalid = true;
11940       continue;
11941     }
11942 
11943     // Check for members of reference type; we can't copy those.
11944     if (Field->getType()->isReferenceType()) {
11945       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11946         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11947       Diag(Field->getLocation(), diag::note_declared_at);
11948       Invalid = true;
11949       continue;
11950     }
11951 
11952     // Check for members of const-qualified, non-class type.
11953     QualType BaseType = Context.getBaseElementType(Field->getType());
11954     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11955       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11956         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11957       Diag(Field->getLocation(), diag::note_declared_at);
11958       Invalid = true;
11959       continue;
11960     }
11961 
11962     // Suppress assigning zero-width bitfields.
11963     if (Field->isZeroLengthBitField(Context))
11964       continue;
11965 
11966     QualType FieldType = Field->getType().getNonReferenceType();
11967     if (FieldType->isIncompleteArrayType()) {
11968       assert(ClassDecl->hasFlexibleArrayMember() &&
11969              "Incomplete array type is not valid");
11970       continue;
11971     }
11972 
11973     // Build references to the field in the object we're copying from and to.
11974     CXXScopeSpec SS; // Intentionally empty
11975     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11976                               LookupMemberName);
11977     MemberLookup.addDecl(Field);
11978     MemberLookup.resolveKind();
11979 
11980     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11981 
11982     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11983 
11984     // Build the copy of this field.
11985     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11986                                             To, From,
11987                                             /*CopyingBaseSubobject=*/false,
11988                                             /*Copying=*/true);
11989     if (Copy.isInvalid()) {
11990       CopyAssignOperator->setInvalidDecl();
11991       return;
11992     }
11993 
11994     // Success! Record the copy.
11995     Statements.push_back(Copy.getAs<Stmt>());
11996   }
11997 
11998   if (!Invalid) {
11999     // Add a "return *this;"
12000     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12001 
12002     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12003     if (Return.isInvalid())
12004       Invalid = true;
12005     else
12006       Statements.push_back(Return.getAs<Stmt>());
12007   }
12008 
12009   if (Invalid) {
12010     CopyAssignOperator->setInvalidDecl();
12011     return;
12012   }
12013 
12014   StmtResult Body;
12015   {
12016     CompoundScopeRAII CompoundScope(*this);
12017     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12018                              /*isStmtExpr=*/false);
12019     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12020   }
12021   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12022   CopyAssignOperator->markUsed(Context);
12023 
12024   if (ASTMutationListener *L = getASTMutationListener()) {
12025     L->CompletedImplicitDefinition(CopyAssignOperator);
12026   }
12027 }
12028 
12029 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12030   assert(ClassDecl->needsImplicitMoveAssignment());
12031 
12032   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12033   if (DSM.isAlreadyBeingDeclared())
12034     return nullptr;
12035 
12036   // Note: The following rules are largely analoguous to the move
12037   // constructor rules.
12038 
12039   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12040   QualType RetType = Context.getLValueReferenceType(ArgType);
12041   ArgType = Context.getRValueReferenceType(ArgType);
12042 
12043   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12044                                                      CXXMoveAssignment,
12045                                                      false);
12046 
12047   //   An implicitly-declared move assignment operator is an inline public
12048   //   member of its class.
12049   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12050   SourceLocation ClassLoc = ClassDecl->getLocation();
12051   DeclarationNameInfo NameInfo(Name, ClassLoc);
12052   CXXMethodDecl *MoveAssignment =
12053       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12054                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12055                             /*isInline=*/true, Constexpr, SourceLocation());
12056   MoveAssignment->setAccess(AS_public);
12057   MoveAssignment->setDefaulted();
12058   MoveAssignment->setImplicit();
12059 
12060   if (getLangOpts().CUDA) {
12061     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12062                                             MoveAssignment,
12063                                             /* ConstRHS */ false,
12064                                             /* Diagnose */ false);
12065   }
12066 
12067   // Build an exception specification pointing back at this member.
12068   FunctionProtoType::ExtProtoInfo EPI =
12069       getImplicitMethodEPI(*this, MoveAssignment);
12070   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12071 
12072   // Add the parameter to the operator.
12073   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12074                                                ClassLoc, ClassLoc,
12075                                                /*Id=*/nullptr, ArgType,
12076                                                /*TInfo=*/nullptr, SC_None,
12077                                                nullptr);
12078   MoveAssignment->setParams(FromParam);
12079 
12080   MoveAssignment->setTrivial(
12081     ClassDecl->needsOverloadResolutionForMoveAssignment()
12082       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12083       : ClassDecl->hasTrivialMoveAssignment());
12084 
12085   // Note that we have added this copy-assignment operator.
12086   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12087 
12088   Scope *S = getScopeForContext(ClassDecl);
12089   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12090 
12091   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12092     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12093     SetDeclDeleted(MoveAssignment, ClassLoc);
12094   }
12095 
12096   if (S)
12097     PushOnScopeChains(MoveAssignment, S, false);
12098   ClassDecl->addDecl(MoveAssignment);
12099 
12100   return MoveAssignment;
12101 }
12102 
12103 /// Check if we're implicitly defining a move assignment operator for a class
12104 /// with virtual bases. Such a move assignment might move-assign the virtual
12105 /// base multiple times.
12106 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12107                                                SourceLocation CurrentLocation) {
12108   assert(!Class->isDependentContext() && "should not define dependent move");
12109 
12110   // Only a virtual base could get implicitly move-assigned multiple times.
12111   // Only a non-trivial move assignment can observe this. We only want to
12112   // diagnose if we implicitly define an assignment operator that assigns
12113   // two base classes, both of which move-assign the same virtual base.
12114   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12115       Class->getNumBases() < 2)
12116     return;
12117 
12118   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12119   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12120   VBaseMap VBases;
12121 
12122   for (auto &BI : Class->bases()) {
12123     Worklist.push_back(&BI);
12124     while (!Worklist.empty()) {
12125       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12126       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12127 
12128       // If the base has no non-trivial move assignment operators,
12129       // we don't care about moves from it.
12130       if (!Base->hasNonTrivialMoveAssignment())
12131         continue;
12132 
12133       // If there's nothing virtual here, skip it.
12134       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12135         continue;
12136 
12137       // If we're not actually going to call a move assignment for this base,
12138       // or the selected move assignment is trivial, skip it.
12139       Sema::SpecialMemberOverloadResult SMOR =
12140         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12141                               /*ConstArg*/false, /*VolatileArg*/false,
12142                               /*RValueThis*/true, /*ConstThis*/false,
12143                               /*VolatileThis*/false);
12144       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12145           !SMOR.getMethod()->isMoveAssignmentOperator())
12146         continue;
12147 
12148       if (BaseSpec->isVirtual()) {
12149         // We're going to move-assign this virtual base, and its move
12150         // assignment operator is not trivial. If this can happen for
12151         // multiple distinct direct bases of Class, diagnose it. (If it
12152         // only happens in one base, we'll diagnose it when synthesizing
12153         // that base class's move assignment operator.)
12154         CXXBaseSpecifier *&Existing =
12155             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12156                 .first->second;
12157         if (Existing && Existing != &BI) {
12158           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12159             << Class << Base;
12160           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12161               << (Base->getCanonicalDecl() ==
12162                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12163               << Base << Existing->getType() << Existing->getSourceRange();
12164           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12165               << (Base->getCanonicalDecl() ==
12166                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12167               << Base << BI.getType() << BaseSpec->getSourceRange();
12168 
12169           // Only diagnose each vbase once.
12170           Existing = nullptr;
12171         }
12172       } else {
12173         // Only walk over bases that have defaulted move assignment operators.
12174         // We assume that any user-provided move assignment operator handles
12175         // the multiple-moves-of-vbase case itself somehow.
12176         if (!SMOR.getMethod()->isDefaulted())
12177           continue;
12178 
12179         // We're going to move the base classes of Base. Add them to the list.
12180         for (auto &BI : Base->bases())
12181           Worklist.push_back(&BI);
12182       }
12183     }
12184   }
12185 }
12186 
12187 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12188                                         CXXMethodDecl *MoveAssignOperator) {
12189   assert((MoveAssignOperator->isDefaulted() &&
12190           MoveAssignOperator->isOverloadedOperator() &&
12191           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12192           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12193           !MoveAssignOperator->isDeleted()) &&
12194          "DefineImplicitMoveAssignment called for wrong function");
12195   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12196     return;
12197 
12198   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12199   if (ClassDecl->isInvalidDecl()) {
12200     MoveAssignOperator->setInvalidDecl();
12201     return;
12202   }
12203 
12204   // C++0x [class.copy]p28:
12205   //   The implicitly-defined or move assignment operator for a non-union class
12206   //   X performs memberwise move assignment of its subobjects. The direct base
12207   //   classes of X are assigned first, in the order of their declaration in the
12208   //   base-specifier-list, and then the immediate non-static data members of X
12209   //   are assigned, in the order in which they were declared in the class
12210   //   definition.
12211 
12212   // Issue a warning if our implicit move assignment operator will move
12213   // from a virtual base more than once.
12214   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12215 
12216   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12217 
12218   // The exception specification is needed because we are defining the
12219   // function.
12220   ResolveExceptionSpec(CurrentLocation,
12221                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12222 
12223   // Add a context note for diagnostics produced after this point.
12224   Scope.addContextNote(CurrentLocation);
12225 
12226   // The statements that form the synthesized function body.
12227   SmallVector<Stmt*, 8> Statements;
12228 
12229   // The parameter for the "other" object, which we are move from.
12230   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12231   QualType OtherRefType = Other->getType()->
12232       getAs<RValueReferenceType>()->getPointeeType();
12233   assert(!OtherRefType.getQualifiers() &&
12234          "Bad argument type of defaulted move assignment");
12235 
12236   // Our location for everything implicitly-generated.
12237   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12238                            ? MoveAssignOperator->getEndLoc()
12239                            : MoveAssignOperator->getLocation();
12240 
12241   // Builds a reference to the "other" object.
12242   RefBuilder OtherRef(Other, OtherRefType);
12243   // Cast to rvalue.
12244   MoveCastBuilder MoveOther(OtherRef);
12245 
12246   // Builds the "this" pointer.
12247   ThisBuilder This;
12248 
12249   // Assign base classes.
12250   bool Invalid = false;
12251   for (auto &Base : ClassDecl->bases()) {
12252     // C++11 [class.copy]p28:
12253     //   It is unspecified whether subobjects representing virtual base classes
12254     //   are assigned more than once by the implicitly-defined copy assignment
12255     //   operator.
12256     // FIXME: Do not assign to a vbase that will be assigned by some other base
12257     // class. For a move-assignment, this can result in the vbase being moved
12258     // multiple times.
12259 
12260     // Form the assignment:
12261     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12262     QualType BaseType = Base.getType().getUnqualifiedType();
12263     if (!BaseType->isRecordType()) {
12264       Invalid = true;
12265       continue;
12266     }
12267 
12268     CXXCastPath BasePath;
12269     BasePath.push_back(&Base);
12270 
12271     // Construct the "from" expression, which is an implicit cast to the
12272     // appropriately-qualified base type.
12273     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12274 
12275     // Dereference "this".
12276     DerefBuilder DerefThis(This);
12277 
12278     // Implicitly cast "this" to the appropriately-qualified base type.
12279     CastBuilder To(DerefThis,
12280                    Context.getCVRQualifiedType(
12281                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12282                    VK_LValue, BasePath);
12283 
12284     // Build the move.
12285     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12286                                             To, From,
12287                                             /*CopyingBaseSubobject=*/true,
12288                                             /*Copying=*/false);
12289     if (Move.isInvalid()) {
12290       MoveAssignOperator->setInvalidDecl();
12291       return;
12292     }
12293 
12294     // Success! Record the move.
12295     Statements.push_back(Move.getAs<Expr>());
12296   }
12297 
12298   // Assign non-static members.
12299   for (auto *Field : ClassDecl->fields()) {
12300     // FIXME: We should form some kind of AST representation for the implied
12301     // memcpy in a union copy operation.
12302     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12303       continue;
12304 
12305     if (Field->isInvalidDecl()) {
12306       Invalid = true;
12307       continue;
12308     }
12309 
12310     // Check for members of reference type; we can't move those.
12311     if (Field->getType()->isReferenceType()) {
12312       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12313         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12314       Diag(Field->getLocation(), diag::note_declared_at);
12315       Invalid = true;
12316       continue;
12317     }
12318 
12319     // Check for members of const-qualified, non-class type.
12320     QualType BaseType = Context.getBaseElementType(Field->getType());
12321     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12322       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12323         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12324       Diag(Field->getLocation(), diag::note_declared_at);
12325       Invalid = true;
12326       continue;
12327     }
12328 
12329     // Suppress assigning zero-width bitfields.
12330     if (Field->isZeroLengthBitField(Context))
12331       continue;
12332 
12333     QualType FieldType = Field->getType().getNonReferenceType();
12334     if (FieldType->isIncompleteArrayType()) {
12335       assert(ClassDecl->hasFlexibleArrayMember() &&
12336              "Incomplete array type is not valid");
12337       continue;
12338     }
12339 
12340     // Build references to the field in the object we're copying from and to.
12341     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12342                               LookupMemberName);
12343     MemberLookup.addDecl(Field);
12344     MemberLookup.resolveKind();
12345     MemberBuilder From(MoveOther, OtherRefType,
12346                        /*IsArrow=*/false, MemberLookup);
12347     MemberBuilder To(This, getCurrentThisType(),
12348                      /*IsArrow=*/true, MemberLookup);
12349 
12350     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12351         "Member reference with rvalue base must be rvalue except for reference "
12352         "members, which aren't allowed for move assignment.");
12353 
12354     // Build the move of this field.
12355     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12356                                             To, From,
12357                                             /*CopyingBaseSubobject=*/false,
12358                                             /*Copying=*/false);
12359     if (Move.isInvalid()) {
12360       MoveAssignOperator->setInvalidDecl();
12361       return;
12362     }
12363 
12364     // Success! Record the copy.
12365     Statements.push_back(Move.getAs<Stmt>());
12366   }
12367 
12368   if (!Invalid) {
12369     // Add a "return *this;"
12370     ExprResult ThisObj =
12371         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12372 
12373     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12374     if (Return.isInvalid())
12375       Invalid = true;
12376     else
12377       Statements.push_back(Return.getAs<Stmt>());
12378   }
12379 
12380   if (Invalid) {
12381     MoveAssignOperator->setInvalidDecl();
12382     return;
12383   }
12384 
12385   StmtResult Body;
12386   {
12387     CompoundScopeRAII CompoundScope(*this);
12388     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12389                              /*isStmtExpr=*/false);
12390     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12391   }
12392   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12393   MoveAssignOperator->markUsed(Context);
12394 
12395   if (ASTMutationListener *L = getASTMutationListener()) {
12396     L->CompletedImplicitDefinition(MoveAssignOperator);
12397   }
12398 }
12399 
12400 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12401                                                     CXXRecordDecl *ClassDecl) {
12402   // C++ [class.copy]p4:
12403   //   If the class definition does not explicitly declare a copy
12404   //   constructor, one is declared implicitly.
12405   assert(ClassDecl->needsImplicitCopyConstructor());
12406 
12407   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12408   if (DSM.isAlreadyBeingDeclared())
12409     return nullptr;
12410 
12411   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12412   QualType ArgType = ClassType;
12413   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12414   if (Const)
12415     ArgType = ArgType.withConst();
12416   ArgType = Context.getLValueReferenceType(ArgType);
12417 
12418   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12419                                                      CXXCopyConstructor,
12420                                                      Const);
12421 
12422   DeclarationName Name
12423     = Context.DeclarationNames.getCXXConstructorName(
12424                                            Context.getCanonicalType(ClassType));
12425   SourceLocation ClassLoc = ClassDecl->getLocation();
12426   DeclarationNameInfo NameInfo(Name, ClassLoc);
12427 
12428   //   An implicitly-declared copy constructor is an inline public
12429   //   member of its class.
12430   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12431       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12432       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12433       Constexpr);
12434   CopyConstructor->setAccess(AS_public);
12435   CopyConstructor->setDefaulted();
12436 
12437   if (getLangOpts().CUDA) {
12438     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12439                                             CopyConstructor,
12440                                             /* ConstRHS */ Const,
12441                                             /* Diagnose */ false);
12442   }
12443 
12444   // Build an exception specification pointing back at this member.
12445   FunctionProtoType::ExtProtoInfo EPI =
12446       getImplicitMethodEPI(*this, CopyConstructor);
12447   CopyConstructor->setType(
12448       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12449 
12450   // Add the parameter to the constructor.
12451   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12452                                                ClassLoc, ClassLoc,
12453                                                /*IdentifierInfo=*/nullptr,
12454                                                ArgType, /*TInfo=*/nullptr,
12455                                                SC_None, nullptr);
12456   CopyConstructor->setParams(FromParam);
12457 
12458   CopyConstructor->setTrivial(
12459       ClassDecl->needsOverloadResolutionForCopyConstructor()
12460           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12461           : ClassDecl->hasTrivialCopyConstructor());
12462 
12463   CopyConstructor->setTrivialForCall(
12464       ClassDecl->hasAttr<TrivialABIAttr>() ||
12465       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12466            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12467              TAH_ConsiderTrivialABI)
12468            : ClassDecl->hasTrivialCopyConstructorForCall()));
12469 
12470   // Note that we have declared this constructor.
12471   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12472 
12473   Scope *S = getScopeForContext(ClassDecl);
12474   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12475 
12476   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12477     ClassDecl->setImplicitCopyConstructorIsDeleted();
12478     SetDeclDeleted(CopyConstructor, ClassLoc);
12479   }
12480 
12481   if (S)
12482     PushOnScopeChains(CopyConstructor, S, false);
12483   ClassDecl->addDecl(CopyConstructor);
12484 
12485   return CopyConstructor;
12486 }
12487 
12488 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12489                                          CXXConstructorDecl *CopyConstructor) {
12490   assert((CopyConstructor->isDefaulted() &&
12491           CopyConstructor->isCopyConstructor() &&
12492           !CopyConstructor->doesThisDeclarationHaveABody() &&
12493           !CopyConstructor->isDeleted()) &&
12494          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12495   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12496     return;
12497 
12498   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12499   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12500 
12501   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12502 
12503   // The exception specification is needed because we are defining the
12504   // function.
12505   ResolveExceptionSpec(CurrentLocation,
12506                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12507   MarkVTableUsed(CurrentLocation, ClassDecl);
12508 
12509   // Add a context note for diagnostics produced after this point.
12510   Scope.addContextNote(CurrentLocation);
12511 
12512   // C++11 [class.copy]p7:
12513   //   The [definition of an implicitly declared copy constructor] is
12514   //   deprecated if the class has a user-declared copy assignment operator
12515   //   or a user-declared destructor.
12516   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12517     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12518 
12519   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12520     CopyConstructor->setInvalidDecl();
12521   }  else {
12522     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12523                              ? CopyConstructor->getEndLoc()
12524                              : CopyConstructor->getLocation();
12525     Sema::CompoundScopeRAII CompoundScope(*this);
12526     CopyConstructor->setBody(
12527         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12528     CopyConstructor->markUsed(Context);
12529   }
12530 
12531   if (ASTMutationListener *L = getASTMutationListener()) {
12532     L->CompletedImplicitDefinition(CopyConstructor);
12533   }
12534 }
12535 
12536 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12537                                                     CXXRecordDecl *ClassDecl) {
12538   assert(ClassDecl->needsImplicitMoveConstructor());
12539 
12540   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12541   if (DSM.isAlreadyBeingDeclared())
12542     return nullptr;
12543 
12544   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12545   QualType ArgType = Context.getRValueReferenceType(ClassType);
12546 
12547   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12548                                                      CXXMoveConstructor,
12549                                                      false);
12550 
12551   DeclarationName Name
12552     = Context.DeclarationNames.getCXXConstructorName(
12553                                            Context.getCanonicalType(ClassType));
12554   SourceLocation ClassLoc = ClassDecl->getLocation();
12555   DeclarationNameInfo NameInfo(Name, ClassLoc);
12556 
12557   // C++11 [class.copy]p11:
12558   //   An implicitly-declared copy/move constructor is an inline public
12559   //   member of its class.
12560   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12561       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12562       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12563       Constexpr);
12564   MoveConstructor->setAccess(AS_public);
12565   MoveConstructor->setDefaulted();
12566 
12567   if (getLangOpts().CUDA) {
12568     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12569                                             MoveConstructor,
12570                                             /* ConstRHS */ false,
12571                                             /* Diagnose */ false);
12572   }
12573 
12574   // Build an exception specification pointing back at this member.
12575   FunctionProtoType::ExtProtoInfo EPI =
12576       getImplicitMethodEPI(*this, MoveConstructor);
12577   MoveConstructor->setType(
12578       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12579 
12580   // Add the parameter to the constructor.
12581   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12582                                                ClassLoc, ClassLoc,
12583                                                /*IdentifierInfo=*/nullptr,
12584                                                ArgType, /*TInfo=*/nullptr,
12585                                                SC_None, nullptr);
12586   MoveConstructor->setParams(FromParam);
12587 
12588   MoveConstructor->setTrivial(
12589       ClassDecl->needsOverloadResolutionForMoveConstructor()
12590           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12591           : ClassDecl->hasTrivialMoveConstructor());
12592 
12593   MoveConstructor->setTrivialForCall(
12594       ClassDecl->hasAttr<TrivialABIAttr>() ||
12595       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12596            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12597                                     TAH_ConsiderTrivialABI)
12598            : ClassDecl->hasTrivialMoveConstructorForCall()));
12599 
12600   // Note that we have declared this constructor.
12601   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12602 
12603   Scope *S = getScopeForContext(ClassDecl);
12604   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12605 
12606   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12607     ClassDecl->setImplicitMoveConstructorIsDeleted();
12608     SetDeclDeleted(MoveConstructor, ClassLoc);
12609   }
12610 
12611   if (S)
12612     PushOnScopeChains(MoveConstructor, S, false);
12613   ClassDecl->addDecl(MoveConstructor);
12614 
12615   return MoveConstructor;
12616 }
12617 
12618 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12619                                          CXXConstructorDecl *MoveConstructor) {
12620   assert((MoveConstructor->isDefaulted() &&
12621           MoveConstructor->isMoveConstructor() &&
12622           !MoveConstructor->doesThisDeclarationHaveABody() &&
12623           !MoveConstructor->isDeleted()) &&
12624          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12625   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12626     return;
12627 
12628   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12629   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12630 
12631   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12632 
12633   // The exception specification is needed because we are defining the
12634   // function.
12635   ResolveExceptionSpec(CurrentLocation,
12636                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12637   MarkVTableUsed(CurrentLocation, ClassDecl);
12638 
12639   // Add a context note for diagnostics produced after this point.
12640   Scope.addContextNote(CurrentLocation);
12641 
12642   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12643     MoveConstructor->setInvalidDecl();
12644   } else {
12645     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12646                              ? MoveConstructor->getEndLoc()
12647                              : MoveConstructor->getLocation();
12648     Sema::CompoundScopeRAII CompoundScope(*this);
12649     MoveConstructor->setBody(ActOnCompoundStmt(
12650         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12651     MoveConstructor->markUsed(Context);
12652   }
12653 
12654   if (ASTMutationListener *L = getASTMutationListener()) {
12655     L->CompletedImplicitDefinition(MoveConstructor);
12656   }
12657 }
12658 
12659 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12660   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12661 }
12662 
12663 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12664                             SourceLocation CurrentLocation,
12665                             CXXConversionDecl *Conv) {
12666   SynthesizedFunctionScope Scope(*this, Conv);
12667   assert(!Conv->getReturnType()->isUndeducedType());
12668 
12669   CXXRecordDecl *Lambda = Conv->getParent();
12670   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12671   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12672 
12673   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12674     CallOp = InstantiateFunctionDeclaration(
12675         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12676     if (!CallOp)
12677       return;
12678 
12679     Invoker = InstantiateFunctionDeclaration(
12680         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12681     if (!Invoker)
12682       return;
12683   }
12684 
12685   if (CallOp->isInvalidDecl())
12686     return;
12687 
12688   // Mark the call operator referenced (and add to pending instantiations
12689   // if necessary).
12690   // For both the conversion and static-invoker template specializations
12691   // we construct their body's in this function, so no need to add them
12692   // to the PendingInstantiations.
12693   MarkFunctionReferenced(CurrentLocation, CallOp);
12694 
12695   // Fill in the __invoke function with a dummy implementation. IR generation
12696   // will fill in the actual details. Update its type in case it contained
12697   // an 'auto'.
12698   Invoker->markUsed(Context);
12699   Invoker->setReferenced();
12700   Invoker->setType(Conv->getReturnType()->getPointeeType());
12701   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12702 
12703   // Construct the body of the conversion function { return __invoke; }.
12704   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12705                                        VK_LValue, Conv->getLocation()).get();
12706   assert(FunctionRef && "Can't refer to __invoke function?");
12707   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12708   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12709                                      Conv->getLocation()));
12710   Conv->markUsed(Context);
12711   Conv->setReferenced();
12712 
12713   if (ASTMutationListener *L = getASTMutationListener()) {
12714     L->CompletedImplicitDefinition(Conv);
12715     L->CompletedImplicitDefinition(Invoker);
12716   }
12717 }
12718 
12719 
12720 
12721 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12722        SourceLocation CurrentLocation,
12723        CXXConversionDecl *Conv)
12724 {
12725   assert(!Conv->getParent()->isGenericLambda());
12726 
12727   SynthesizedFunctionScope Scope(*this, Conv);
12728 
12729   // Copy-initialize the lambda object as needed to capture it.
12730   Expr *This = ActOnCXXThis(CurrentLocation).get();
12731   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12732 
12733   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12734                                                         Conv->getLocation(),
12735                                                         Conv, DerefThis);
12736 
12737   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12738   // behavior.  Note that only the general conversion function does this
12739   // (since it's unusable otherwise); in the case where we inline the
12740   // block literal, it has block literal lifetime semantics.
12741   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12742     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12743                                           CK_CopyAndAutoreleaseBlockObject,
12744                                           BuildBlock.get(), nullptr, VK_RValue);
12745 
12746   if (BuildBlock.isInvalid()) {
12747     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12748     Conv->setInvalidDecl();
12749     return;
12750   }
12751 
12752   // Create the return statement that returns the block from the conversion
12753   // function.
12754   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12755   if (Return.isInvalid()) {
12756     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12757     Conv->setInvalidDecl();
12758     return;
12759   }
12760 
12761   // Set the body of the conversion function.
12762   Stmt *ReturnS = Return.get();
12763   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12764                                      Conv->getLocation()));
12765   Conv->markUsed(Context);
12766 
12767   // We're done; notify the mutation listener, if any.
12768   if (ASTMutationListener *L = getASTMutationListener()) {
12769     L->CompletedImplicitDefinition(Conv);
12770   }
12771 }
12772 
12773 /// Determine whether the given list arguments contains exactly one
12774 /// "real" (non-default) argument.
12775 static bool hasOneRealArgument(MultiExprArg Args) {
12776   switch (Args.size()) {
12777   case 0:
12778     return false;
12779 
12780   default:
12781     if (!Args[1]->isDefaultArgument())
12782       return false;
12783 
12784     LLVM_FALLTHROUGH;
12785   case 1:
12786     return !Args[0]->isDefaultArgument();
12787   }
12788 
12789   return false;
12790 }
12791 
12792 ExprResult
12793 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12794                             NamedDecl *FoundDecl,
12795                             CXXConstructorDecl *Constructor,
12796                             MultiExprArg ExprArgs,
12797                             bool HadMultipleCandidates,
12798                             bool IsListInitialization,
12799                             bool IsStdInitListInitialization,
12800                             bool RequiresZeroInit,
12801                             unsigned ConstructKind,
12802                             SourceRange ParenRange) {
12803   bool Elidable = false;
12804 
12805   // C++0x [class.copy]p34:
12806   //   When certain criteria are met, an implementation is allowed to
12807   //   omit the copy/move construction of a class object, even if the
12808   //   copy/move constructor and/or destructor for the object have
12809   //   side effects. [...]
12810   //     - when a temporary class object that has not been bound to a
12811   //       reference (12.2) would be copied/moved to a class object
12812   //       with the same cv-unqualified type, the copy/move operation
12813   //       can be omitted by constructing the temporary object
12814   //       directly into the target of the omitted copy/move
12815   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12816       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12817     Expr *SubExpr = ExprArgs[0];
12818     Elidable = SubExpr->isTemporaryObject(
12819         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12820   }
12821 
12822   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12823                                FoundDecl, Constructor,
12824                                Elidable, ExprArgs, HadMultipleCandidates,
12825                                IsListInitialization,
12826                                IsStdInitListInitialization, RequiresZeroInit,
12827                                ConstructKind, ParenRange);
12828 }
12829 
12830 ExprResult
12831 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12832                             NamedDecl *FoundDecl,
12833                             CXXConstructorDecl *Constructor,
12834                             bool Elidable,
12835                             MultiExprArg ExprArgs,
12836                             bool HadMultipleCandidates,
12837                             bool IsListInitialization,
12838                             bool IsStdInitListInitialization,
12839                             bool RequiresZeroInit,
12840                             unsigned ConstructKind,
12841                             SourceRange ParenRange) {
12842   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12843     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12844     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12845       return ExprError();
12846   }
12847 
12848   return BuildCXXConstructExpr(
12849       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12850       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12851       RequiresZeroInit, ConstructKind, ParenRange);
12852 }
12853 
12854 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12855 /// including handling of its default argument expressions.
12856 ExprResult
12857 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12858                             CXXConstructorDecl *Constructor,
12859                             bool Elidable,
12860                             MultiExprArg ExprArgs,
12861                             bool HadMultipleCandidates,
12862                             bool IsListInitialization,
12863                             bool IsStdInitListInitialization,
12864                             bool RequiresZeroInit,
12865                             unsigned ConstructKind,
12866                             SourceRange ParenRange) {
12867   assert(declaresSameEntity(
12868              Constructor->getParent(),
12869              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12870          "given constructor for wrong type");
12871   MarkFunctionReferenced(ConstructLoc, Constructor);
12872   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12873     return ExprError();
12874 
12875   return CXXConstructExpr::Create(
12876       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12877       ExprArgs, HadMultipleCandidates, IsListInitialization,
12878       IsStdInitListInitialization, RequiresZeroInit,
12879       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12880       ParenRange);
12881 }
12882 
12883 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12884   assert(Field->hasInClassInitializer());
12885 
12886   // If we already have the in-class initializer nothing needs to be done.
12887   if (Field->getInClassInitializer())
12888     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12889 
12890   // If we might have already tried and failed to instantiate, don't try again.
12891   if (Field->isInvalidDecl())
12892     return ExprError();
12893 
12894   // Maybe we haven't instantiated the in-class initializer. Go check the
12895   // pattern FieldDecl to see if it has one.
12896   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12897 
12898   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12899     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12900     DeclContext::lookup_result Lookup =
12901         ClassPattern->lookup(Field->getDeclName());
12902 
12903     // Lookup can return at most two results: the pattern for the field, or the
12904     // injected class name of the parent record. No other member can have the
12905     // same name as the field.
12906     // In modules mode, lookup can return multiple results (coming from
12907     // different modules).
12908     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12909            "more than two lookup results for field name");
12910     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12911     if (!Pattern) {
12912       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12913              "cannot have other non-field member with same name");
12914       for (auto L : Lookup)
12915         if (isa<FieldDecl>(L)) {
12916           Pattern = cast<FieldDecl>(L);
12917           break;
12918         }
12919       assert(Pattern && "We must have set the Pattern!");
12920     }
12921 
12922     if (!Pattern->hasInClassInitializer() ||
12923         InstantiateInClassInitializer(Loc, Field, Pattern,
12924                                       getTemplateInstantiationArgs(Field))) {
12925       // Don't diagnose this again.
12926       Field->setInvalidDecl();
12927       return ExprError();
12928     }
12929     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12930   }
12931 
12932   // DR1351:
12933   //   If the brace-or-equal-initializer of a non-static data member
12934   //   invokes a defaulted default constructor of its class or of an
12935   //   enclosing class in a potentially evaluated subexpression, the
12936   //   program is ill-formed.
12937   //
12938   // This resolution is unworkable: the exception specification of the
12939   // default constructor can be needed in an unevaluated context, in
12940   // particular, in the operand of a noexcept-expression, and we can be
12941   // unable to compute an exception specification for an enclosed class.
12942   //
12943   // Any attempt to resolve the exception specification of a defaulted default
12944   // constructor before the initializer is lexically complete will ultimately
12945   // come here at which point we can diagnose it.
12946   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12947   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12948       << OutermostClass << Field;
12949   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
12950   // Recover by marking the field invalid, unless we're in a SFINAE context.
12951   if (!isSFINAEContext())
12952     Field->setInvalidDecl();
12953   return ExprError();
12954 }
12955 
12956 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12957   if (VD->isInvalidDecl()) return;
12958 
12959   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12960   if (ClassDecl->isInvalidDecl()) return;
12961   if (ClassDecl->hasIrrelevantDestructor()) return;
12962   if (ClassDecl->isDependentContext()) return;
12963 
12964   if (VD->isNoDestroy(getASTContext()))
12965     return;
12966 
12967   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12968   MarkFunctionReferenced(VD->getLocation(), Destructor);
12969   CheckDestructorAccess(VD->getLocation(), Destructor,
12970                         PDiag(diag::err_access_dtor_var)
12971                         << VD->getDeclName()
12972                         << VD->getType());
12973   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12974 
12975   if (Destructor->isTrivial()) return;
12976   if (!VD->hasGlobalStorage()) return;
12977 
12978   // Emit warning for non-trivial dtor in global scope (a real global,
12979   // class-static, function-static).
12980   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12981 
12982   // TODO: this should be re-enabled for static locals by !CXAAtExit
12983   if (!VD->isStaticLocal())
12984     Diag(VD->getLocation(), diag::warn_global_destructor);
12985 }
12986 
12987 /// Given a constructor and the set of arguments provided for the
12988 /// constructor, convert the arguments and add any required default arguments
12989 /// to form a proper call to this constructor.
12990 ///
12991 /// \returns true if an error occurred, false otherwise.
12992 bool
12993 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12994                               MultiExprArg ArgsPtr,
12995                               SourceLocation Loc,
12996                               SmallVectorImpl<Expr*> &ConvertedArgs,
12997                               bool AllowExplicit,
12998                               bool IsListInitialization) {
12999   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13000   unsigned NumArgs = ArgsPtr.size();
13001   Expr **Args = ArgsPtr.data();
13002 
13003   const FunctionProtoType *Proto
13004     = Constructor->getType()->getAs<FunctionProtoType>();
13005   assert(Proto && "Constructor without a prototype?");
13006   unsigned NumParams = Proto->getNumParams();
13007 
13008   // If too few arguments are available, we'll fill in the rest with defaults.
13009   if (NumArgs < NumParams)
13010     ConvertedArgs.reserve(NumParams);
13011   else
13012     ConvertedArgs.reserve(NumArgs);
13013 
13014   VariadicCallType CallType =
13015     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13016   SmallVector<Expr *, 8> AllArgs;
13017   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13018                                         Proto, 0,
13019                                         llvm::makeArrayRef(Args, NumArgs),
13020                                         AllArgs,
13021                                         CallType, AllowExplicit,
13022                                         IsListInitialization);
13023   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13024 
13025   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13026 
13027   CheckConstructorCall(Constructor,
13028                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13029                        Proto, Loc);
13030 
13031   return Invalid;
13032 }
13033 
13034 static inline bool
13035 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13036                                        const FunctionDecl *FnDecl) {
13037   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13038   if (isa<NamespaceDecl>(DC)) {
13039     return SemaRef.Diag(FnDecl->getLocation(),
13040                         diag::err_operator_new_delete_declared_in_namespace)
13041       << FnDecl->getDeclName();
13042   }
13043 
13044   if (isa<TranslationUnitDecl>(DC) &&
13045       FnDecl->getStorageClass() == SC_Static) {
13046     return SemaRef.Diag(FnDecl->getLocation(),
13047                         diag::err_operator_new_delete_declared_static)
13048       << FnDecl->getDeclName();
13049   }
13050 
13051   return false;
13052 }
13053 
13054 static QualType
13055 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13056   QualType QTy = PtrTy->getPointeeType();
13057   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13058   return SemaRef.Context.getPointerType(QTy);
13059 }
13060 
13061 static inline bool
13062 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13063                             CanQualType ExpectedResultType,
13064                             CanQualType ExpectedFirstParamType,
13065                             unsigned DependentParamTypeDiag,
13066                             unsigned InvalidParamTypeDiag) {
13067   QualType ResultType =
13068       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13069 
13070   // Check that the result type is not dependent.
13071   if (ResultType->isDependentType())
13072     return SemaRef.Diag(FnDecl->getLocation(),
13073                         diag::err_operator_new_delete_dependent_result_type)
13074     << FnDecl->getDeclName() << ExpectedResultType;
13075 
13076   // OpenCL C++: the operator is valid on any address space.
13077   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13078     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13079       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13080     }
13081   }
13082 
13083   // Check that the result type is what we expect.
13084   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13085     return SemaRef.Diag(FnDecl->getLocation(),
13086                         diag::err_operator_new_delete_invalid_result_type)
13087     << FnDecl->getDeclName() << ExpectedResultType;
13088 
13089   // A function template must have at least 2 parameters.
13090   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13091     return SemaRef.Diag(FnDecl->getLocation(),
13092                       diag::err_operator_new_delete_template_too_few_parameters)
13093         << FnDecl->getDeclName();
13094 
13095   // The function decl must have at least 1 parameter.
13096   if (FnDecl->getNumParams() == 0)
13097     return SemaRef.Diag(FnDecl->getLocation(),
13098                         diag::err_operator_new_delete_too_few_parameters)
13099       << FnDecl->getDeclName();
13100 
13101   // Check the first parameter type is not dependent.
13102   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13103   if (FirstParamType->isDependentType())
13104     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13105       << FnDecl->getDeclName() << ExpectedFirstParamType;
13106 
13107   // Check that the first parameter type is what we expect.
13108   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13109     // OpenCL C++: the operator is valid on any address space.
13110     if (auto *PtrTy =
13111             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13112       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13113     }
13114   }
13115   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13116       ExpectedFirstParamType)
13117     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13118     << FnDecl->getDeclName() << ExpectedFirstParamType;
13119 
13120   return false;
13121 }
13122 
13123 static bool
13124 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13125   // C++ [basic.stc.dynamic.allocation]p1:
13126   //   A program is ill-formed if an allocation function is declared in a
13127   //   namespace scope other than global scope or declared static in global
13128   //   scope.
13129   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13130     return true;
13131 
13132   CanQualType SizeTy =
13133     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13134 
13135   // C++ [basic.stc.dynamic.allocation]p1:
13136   //  The return type shall be void*. The first parameter shall have type
13137   //  std::size_t.
13138   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13139                                   SizeTy,
13140                                   diag::err_operator_new_dependent_param_type,
13141                                   diag::err_operator_new_param_type))
13142     return true;
13143 
13144   // C++ [basic.stc.dynamic.allocation]p1:
13145   //  The first parameter shall not have an associated default argument.
13146   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13147     return SemaRef.Diag(FnDecl->getLocation(),
13148                         diag::err_operator_new_default_arg)
13149       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13150 
13151   return false;
13152 }
13153 
13154 static bool
13155 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13156   // C++ [basic.stc.dynamic.deallocation]p1:
13157   //   A program is ill-formed if deallocation functions are declared in a
13158   //   namespace scope other than global scope or declared static in global
13159   //   scope.
13160   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13161     return true;
13162 
13163   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13164 
13165   // C++ P0722:
13166   //   Within a class C, the first parameter of a destroying operator delete
13167   //   shall be of type C *. The first parameter of any other deallocation
13168   //   function shall be of type void *.
13169   CanQualType ExpectedFirstParamType =
13170       MD && MD->isDestroyingOperatorDelete()
13171           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13172                 SemaRef.Context.getRecordType(MD->getParent())))
13173           : SemaRef.Context.VoidPtrTy;
13174 
13175   // C++ [basic.stc.dynamic.deallocation]p2:
13176   //   Each deallocation function shall return void
13177   if (CheckOperatorNewDeleteTypes(
13178           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13179           diag::err_operator_delete_dependent_param_type,
13180           diag::err_operator_delete_param_type))
13181     return true;
13182 
13183   // C++ P0722:
13184   //   A destroying operator delete shall be a usual deallocation function.
13185   if (MD && !MD->getParent()->isDependentContext() &&
13186       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
13187     SemaRef.Diag(MD->getLocation(),
13188                  diag::err_destroying_operator_delete_not_usual);
13189     return true;
13190   }
13191 
13192   return false;
13193 }
13194 
13195 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13196 /// of this overloaded operator is well-formed. If so, returns false;
13197 /// otherwise, emits appropriate diagnostics and returns true.
13198 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13199   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13200          "Expected an overloaded operator declaration");
13201 
13202   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13203 
13204   // C++ [over.oper]p5:
13205   //   The allocation and deallocation functions, operator new,
13206   //   operator new[], operator delete and operator delete[], are
13207   //   described completely in 3.7.3. The attributes and restrictions
13208   //   found in the rest of this subclause do not apply to them unless
13209   //   explicitly stated in 3.7.3.
13210   if (Op == OO_Delete || Op == OO_Array_Delete)
13211     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13212 
13213   if (Op == OO_New || Op == OO_Array_New)
13214     return CheckOperatorNewDeclaration(*this, FnDecl);
13215 
13216   // C++ [over.oper]p6:
13217   //   An operator function shall either be a non-static member
13218   //   function or be a non-member function and have at least one
13219   //   parameter whose type is a class, a reference to a class, an
13220   //   enumeration, or a reference to an enumeration.
13221   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13222     if (MethodDecl->isStatic())
13223       return Diag(FnDecl->getLocation(),
13224                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13225   } else {
13226     bool ClassOrEnumParam = false;
13227     for (auto Param : FnDecl->parameters()) {
13228       QualType ParamType = Param->getType().getNonReferenceType();
13229       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13230           ParamType->isEnumeralType()) {
13231         ClassOrEnumParam = true;
13232         break;
13233       }
13234     }
13235 
13236     if (!ClassOrEnumParam)
13237       return Diag(FnDecl->getLocation(),
13238                   diag::err_operator_overload_needs_class_or_enum)
13239         << FnDecl->getDeclName();
13240   }
13241 
13242   // C++ [over.oper]p8:
13243   //   An operator function cannot have default arguments (8.3.6),
13244   //   except where explicitly stated below.
13245   //
13246   // Only the function-call operator allows default arguments
13247   // (C++ [over.call]p1).
13248   if (Op != OO_Call) {
13249     for (auto Param : FnDecl->parameters()) {
13250       if (Param->hasDefaultArg())
13251         return Diag(Param->getLocation(),
13252                     diag::err_operator_overload_default_arg)
13253           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13254     }
13255   }
13256 
13257   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13258     { false, false, false }
13259 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13260     , { Unary, Binary, MemberOnly }
13261 #include "clang/Basic/OperatorKinds.def"
13262   };
13263 
13264   bool CanBeUnaryOperator = OperatorUses[Op][0];
13265   bool CanBeBinaryOperator = OperatorUses[Op][1];
13266   bool MustBeMemberOperator = OperatorUses[Op][2];
13267 
13268   // C++ [over.oper]p8:
13269   //   [...] Operator functions cannot have more or fewer parameters
13270   //   than the number required for the corresponding operator, as
13271   //   described in the rest of this subclause.
13272   unsigned NumParams = FnDecl->getNumParams()
13273                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13274   if (Op != OO_Call &&
13275       ((NumParams == 1 && !CanBeUnaryOperator) ||
13276        (NumParams == 2 && !CanBeBinaryOperator) ||
13277        (NumParams < 1) || (NumParams > 2))) {
13278     // We have the wrong number of parameters.
13279     unsigned ErrorKind;
13280     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13281       ErrorKind = 2;  // 2 -> unary or binary.
13282     } else if (CanBeUnaryOperator) {
13283       ErrorKind = 0;  // 0 -> unary
13284     } else {
13285       assert(CanBeBinaryOperator &&
13286              "All non-call overloaded operators are unary or binary!");
13287       ErrorKind = 1;  // 1 -> binary
13288     }
13289 
13290     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13291       << FnDecl->getDeclName() << NumParams << ErrorKind;
13292   }
13293 
13294   // Overloaded operators other than operator() cannot be variadic.
13295   if (Op != OO_Call &&
13296       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13297     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13298       << FnDecl->getDeclName();
13299   }
13300 
13301   // Some operators must be non-static member functions.
13302   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13303     return Diag(FnDecl->getLocation(),
13304                 diag::err_operator_overload_must_be_member)
13305       << FnDecl->getDeclName();
13306   }
13307 
13308   // C++ [over.inc]p1:
13309   //   The user-defined function called operator++ implements the
13310   //   prefix and postfix ++ operator. If this function is a member
13311   //   function with no parameters, or a non-member function with one
13312   //   parameter of class or enumeration type, it defines the prefix
13313   //   increment operator ++ for objects of that type. If the function
13314   //   is a member function with one parameter (which shall be of type
13315   //   int) or a non-member function with two parameters (the second
13316   //   of which shall be of type int), it defines the postfix
13317   //   increment operator ++ for objects of that type.
13318   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13319     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13320     QualType ParamType = LastParam->getType();
13321 
13322     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13323         !ParamType->isDependentType())
13324       return Diag(LastParam->getLocation(),
13325                   diag::err_operator_overload_post_incdec_must_be_int)
13326         << LastParam->getType() << (Op == OO_MinusMinus);
13327   }
13328 
13329   return false;
13330 }
13331 
13332 static bool
13333 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13334                                           FunctionTemplateDecl *TpDecl) {
13335   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13336 
13337   // Must have one or two template parameters.
13338   if (TemplateParams->size() == 1) {
13339     NonTypeTemplateParmDecl *PmDecl =
13340         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13341 
13342     // The template parameter must be a char parameter pack.
13343     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13344         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13345       return false;
13346 
13347   } else if (TemplateParams->size() == 2) {
13348     TemplateTypeParmDecl *PmType =
13349         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13350     NonTypeTemplateParmDecl *PmArgs =
13351         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13352 
13353     // The second template parameter must be a parameter pack with the
13354     // first template parameter as its type.
13355     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13356         PmArgs->isTemplateParameterPack()) {
13357       const TemplateTypeParmType *TArgs =
13358           PmArgs->getType()->getAs<TemplateTypeParmType>();
13359       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13360           TArgs->getIndex() == PmType->getIndex()) {
13361         if (!SemaRef.inTemplateInstantiation())
13362           SemaRef.Diag(TpDecl->getLocation(),
13363                        diag::ext_string_literal_operator_template);
13364         return false;
13365       }
13366     }
13367   }
13368 
13369   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13370                diag::err_literal_operator_template)
13371       << TpDecl->getTemplateParameters()->getSourceRange();
13372   return true;
13373 }
13374 
13375 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13376 /// of this literal operator function is well-formed. If so, returns
13377 /// false; otherwise, emits appropriate diagnostics and returns true.
13378 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13379   if (isa<CXXMethodDecl>(FnDecl)) {
13380     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13381       << FnDecl->getDeclName();
13382     return true;
13383   }
13384 
13385   if (FnDecl->isExternC()) {
13386     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13387     if (const LinkageSpecDecl *LSD =
13388             FnDecl->getDeclContext()->getExternCContext())
13389       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13390     return true;
13391   }
13392 
13393   // This might be the definition of a literal operator template.
13394   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13395 
13396   // This might be a specialization of a literal operator template.
13397   if (!TpDecl)
13398     TpDecl = FnDecl->getPrimaryTemplate();
13399 
13400   // template <char...> type operator "" name() and
13401   // template <class T, T...> type operator "" name() are the only valid
13402   // template signatures, and the only valid signatures with no parameters.
13403   if (TpDecl) {
13404     if (FnDecl->param_size() != 0) {
13405       Diag(FnDecl->getLocation(),
13406            diag::err_literal_operator_template_with_params);
13407       return true;
13408     }
13409 
13410     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13411       return true;
13412 
13413   } else if (FnDecl->param_size() == 1) {
13414     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13415 
13416     QualType ParamType = Param->getType().getUnqualifiedType();
13417 
13418     // Only unsigned long long int, long double, any character type, and const
13419     // char * are allowed as the only parameters.
13420     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13421         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13422         Context.hasSameType(ParamType, Context.CharTy) ||
13423         Context.hasSameType(ParamType, Context.WideCharTy) ||
13424         Context.hasSameType(ParamType, Context.Char8Ty) ||
13425         Context.hasSameType(ParamType, Context.Char16Ty) ||
13426         Context.hasSameType(ParamType, Context.Char32Ty)) {
13427     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13428       QualType InnerType = Ptr->getPointeeType();
13429 
13430       // Pointer parameter must be a const char *.
13431       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13432                                 Context.CharTy) &&
13433             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13434         Diag(Param->getSourceRange().getBegin(),
13435              diag::err_literal_operator_param)
13436             << ParamType << "'const char *'" << Param->getSourceRange();
13437         return true;
13438       }
13439 
13440     } else if (ParamType->isRealFloatingType()) {
13441       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13442           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13443       return true;
13444 
13445     } else if (ParamType->isIntegerType()) {
13446       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13447           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13448       return true;
13449 
13450     } else {
13451       Diag(Param->getSourceRange().getBegin(),
13452            diag::err_literal_operator_invalid_param)
13453           << ParamType << Param->getSourceRange();
13454       return true;
13455     }
13456 
13457   } else if (FnDecl->param_size() == 2) {
13458     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13459 
13460     // First, verify that the first parameter is correct.
13461 
13462     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13463 
13464     // Two parameter function must have a pointer to const as a
13465     // first parameter; let's strip those qualifiers.
13466     const PointerType *PT = FirstParamType->getAs<PointerType>();
13467 
13468     if (!PT) {
13469       Diag((*Param)->getSourceRange().getBegin(),
13470            diag::err_literal_operator_param)
13471           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13472       return true;
13473     }
13474 
13475     QualType PointeeType = PT->getPointeeType();
13476     // First parameter must be const
13477     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13478       Diag((*Param)->getSourceRange().getBegin(),
13479            diag::err_literal_operator_param)
13480           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13481       return true;
13482     }
13483 
13484     QualType InnerType = PointeeType.getUnqualifiedType();
13485     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13486     // const char32_t* are allowed as the first parameter to a two-parameter
13487     // function
13488     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13489           Context.hasSameType(InnerType, Context.WideCharTy) ||
13490           Context.hasSameType(InnerType, Context.Char8Ty) ||
13491           Context.hasSameType(InnerType, Context.Char16Ty) ||
13492           Context.hasSameType(InnerType, Context.Char32Ty))) {
13493       Diag((*Param)->getSourceRange().getBegin(),
13494            diag::err_literal_operator_param)
13495           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13496       return true;
13497     }
13498 
13499     // Move on to the second and final parameter.
13500     ++Param;
13501 
13502     // The second parameter must be a std::size_t.
13503     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13504     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13505       Diag((*Param)->getSourceRange().getBegin(),
13506            diag::err_literal_operator_param)
13507           << SecondParamType << Context.getSizeType()
13508           << (*Param)->getSourceRange();
13509       return true;
13510     }
13511   } else {
13512     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13513     return true;
13514   }
13515 
13516   // Parameters are good.
13517 
13518   // A parameter-declaration-clause containing a default argument is not
13519   // equivalent to any of the permitted forms.
13520   for (auto Param : FnDecl->parameters()) {
13521     if (Param->hasDefaultArg()) {
13522       Diag(Param->getDefaultArgRange().getBegin(),
13523            diag::err_literal_operator_default_argument)
13524         << Param->getDefaultArgRange();
13525       break;
13526     }
13527   }
13528 
13529   StringRef LiteralName
13530     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13531   if (LiteralName[0] != '_' &&
13532       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13533     // C++11 [usrlit.suffix]p1:
13534     //   Literal suffix identifiers that do not start with an underscore
13535     //   are reserved for future standardization.
13536     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13537       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13538   }
13539 
13540   return false;
13541 }
13542 
13543 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13544 /// linkage specification, including the language and (if present)
13545 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13546 /// language string literal. LBraceLoc, if valid, provides the location of
13547 /// the '{' brace. Otherwise, this linkage specification does not
13548 /// have any braces.
13549 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13550                                            Expr *LangStr,
13551                                            SourceLocation LBraceLoc) {
13552   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13553   if (!Lit->isAscii()) {
13554     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13555       << LangStr->getSourceRange();
13556     return nullptr;
13557   }
13558 
13559   StringRef Lang = Lit->getString();
13560   LinkageSpecDecl::LanguageIDs Language;
13561   if (Lang == "C")
13562     Language = LinkageSpecDecl::lang_c;
13563   else if (Lang == "C++")
13564     Language = LinkageSpecDecl::lang_cxx;
13565   else {
13566     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13567       << LangStr->getSourceRange();
13568     return nullptr;
13569   }
13570 
13571   // FIXME: Add all the various semantics of linkage specifications
13572 
13573   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13574                                                LangStr->getExprLoc(), Language,
13575                                                LBraceLoc.isValid());
13576   CurContext->addDecl(D);
13577   PushDeclContext(S, D);
13578   return D;
13579 }
13580 
13581 /// ActOnFinishLinkageSpecification - Complete the definition of
13582 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13583 /// valid, it's the position of the closing '}' brace in a linkage
13584 /// specification that uses braces.
13585 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13586                                             Decl *LinkageSpec,
13587                                             SourceLocation RBraceLoc) {
13588   if (RBraceLoc.isValid()) {
13589     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13590     LSDecl->setRBraceLoc(RBraceLoc);
13591   }
13592   PopDeclContext();
13593   return LinkageSpec;
13594 }
13595 
13596 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13597                                   const ParsedAttributesView &AttrList,
13598                                   SourceLocation SemiLoc) {
13599   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13600   // Attribute declarations appertain to empty declaration so we handle
13601   // them here.
13602   ProcessDeclAttributeList(S, ED, AttrList);
13603 
13604   CurContext->addDecl(ED);
13605   return ED;
13606 }
13607 
13608 /// Perform semantic analysis for the variable declaration that
13609 /// occurs within a C++ catch clause, returning the newly-created
13610 /// variable.
13611 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13612                                          TypeSourceInfo *TInfo,
13613                                          SourceLocation StartLoc,
13614                                          SourceLocation Loc,
13615                                          IdentifierInfo *Name) {
13616   bool Invalid = false;
13617   QualType ExDeclType = TInfo->getType();
13618 
13619   // Arrays and functions decay.
13620   if (ExDeclType->isArrayType())
13621     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13622   else if (ExDeclType->isFunctionType())
13623     ExDeclType = Context.getPointerType(ExDeclType);
13624 
13625   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13626   // The exception-declaration shall not denote a pointer or reference to an
13627   // incomplete type, other than [cv] void*.
13628   // N2844 forbids rvalue references.
13629   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13630     Diag(Loc, diag::err_catch_rvalue_ref);
13631     Invalid = true;
13632   }
13633 
13634   if (ExDeclType->isVariablyModifiedType()) {
13635     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13636     Invalid = true;
13637   }
13638 
13639   QualType BaseType = ExDeclType;
13640   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13641   unsigned DK = diag::err_catch_incomplete;
13642   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13643     BaseType = Ptr->getPointeeType();
13644     Mode = 1;
13645     DK = diag::err_catch_incomplete_ptr;
13646   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13647     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13648     BaseType = Ref->getPointeeType();
13649     Mode = 2;
13650     DK = diag::err_catch_incomplete_ref;
13651   }
13652   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13653       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13654     Invalid = true;
13655 
13656   if (!Invalid && !ExDeclType->isDependentType() &&
13657       RequireNonAbstractType(Loc, ExDeclType,
13658                              diag::err_abstract_type_in_decl,
13659                              AbstractVariableType))
13660     Invalid = true;
13661 
13662   // Only the non-fragile NeXT runtime currently supports C++ catches
13663   // of ObjC types, and no runtime supports catching ObjC types by value.
13664   if (!Invalid && getLangOpts().ObjC1) {
13665     QualType T = ExDeclType;
13666     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13667       T = RT->getPointeeType();
13668 
13669     if (T->isObjCObjectType()) {
13670       Diag(Loc, diag::err_objc_object_catch);
13671       Invalid = true;
13672     } else if (T->isObjCObjectPointerType()) {
13673       // FIXME: should this be a test for macosx-fragile specifically?
13674       if (getLangOpts().ObjCRuntime.isFragile())
13675         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13676     }
13677   }
13678 
13679   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13680                                     ExDeclType, TInfo, SC_None);
13681   ExDecl->setExceptionVariable(true);
13682 
13683   // In ARC, infer 'retaining' for variables of retainable type.
13684   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13685     Invalid = true;
13686 
13687   if (!Invalid && !ExDeclType->isDependentType()) {
13688     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13689       // Insulate this from anything else we might currently be parsing.
13690       EnterExpressionEvaluationContext scope(
13691           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13692 
13693       // C++ [except.handle]p16:
13694       //   The object declared in an exception-declaration or, if the
13695       //   exception-declaration does not specify a name, a temporary (12.2) is
13696       //   copy-initialized (8.5) from the exception object. [...]
13697       //   The object is destroyed when the handler exits, after the destruction
13698       //   of any automatic objects initialized within the handler.
13699       //
13700       // We just pretend to initialize the object with itself, then make sure
13701       // it can be destroyed later.
13702       QualType initType = Context.getExceptionObjectType(ExDeclType);
13703 
13704       InitializedEntity entity =
13705         InitializedEntity::InitializeVariable(ExDecl);
13706       InitializationKind initKind =
13707         InitializationKind::CreateCopy(Loc, SourceLocation());
13708 
13709       Expr *opaqueValue =
13710         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13711       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13712       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13713       if (result.isInvalid())
13714         Invalid = true;
13715       else {
13716         // If the constructor used was non-trivial, set this as the
13717         // "initializer".
13718         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13719         if (!construct->getConstructor()->isTrivial()) {
13720           Expr *init = MaybeCreateExprWithCleanups(construct);
13721           ExDecl->setInit(init);
13722         }
13723 
13724         // And make sure it's destructable.
13725         FinalizeVarWithDestructor(ExDecl, recordType);
13726       }
13727     }
13728   }
13729 
13730   if (Invalid)
13731     ExDecl->setInvalidDecl();
13732 
13733   return ExDecl;
13734 }
13735 
13736 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13737 /// handler.
13738 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13739   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13740   bool Invalid = D.isInvalidType();
13741 
13742   // Check for unexpanded parameter packs.
13743   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13744                                       UPPC_ExceptionType)) {
13745     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13746                                              D.getIdentifierLoc());
13747     Invalid = true;
13748   }
13749 
13750   IdentifierInfo *II = D.getIdentifier();
13751   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13752                                              LookupOrdinaryName,
13753                                              ForVisibleRedeclaration)) {
13754     // The scope should be freshly made just for us. There is just no way
13755     // it contains any previous declaration, except for function parameters in
13756     // a function-try-block's catch statement.
13757     assert(!S->isDeclScope(PrevDecl));
13758     if (isDeclInScope(PrevDecl, CurContext, S)) {
13759       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13760         << D.getIdentifier();
13761       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13762       Invalid = true;
13763     } else if (PrevDecl->isTemplateParameter())
13764       // Maybe we will complain about the shadowed template parameter.
13765       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13766   }
13767 
13768   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13769     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13770       << D.getCXXScopeSpec().getRange();
13771     Invalid = true;
13772   }
13773 
13774   VarDecl *ExDecl = BuildExceptionDeclaration(
13775       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13776   if (Invalid)
13777     ExDecl->setInvalidDecl();
13778 
13779   // Add the exception declaration into this scope.
13780   if (II)
13781     PushOnScopeChains(ExDecl, S);
13782   else
13783     CurContext->addDecl(ExDecl);
13784 
13785   ProcessDeclAttributes(S, ExDecl, D);
13786   return ExDecl;
13787 }
13788 
13789 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13790                                          Expr *AssertExpr,
13791                                          Expr *AssertMessageExpr,
13792                                          SourceLocation RParenLoc) {
13793   StringLiteral *AssertMessage =
13794       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13795 
13796   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13797     return nullptr;
13798 
13799   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13800                                       AssertMessage, RParenLoc, false);
13801 }
13802 
13803 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13804                                          Expr *AssertExpr,
13805                                          StringLiteral *AssertMessage,
13806                                          SourceLocation RParenLoc,
13807                                          bool Failed) {
13808   assert(AssertExpr != nullptr && "Expected non-null condition");
13809   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13810       !Failed) {
13811     // In a static_assert-declaration, the constant-expression shall be a
13812     // constant expression that can be contextually converted to bool.
13813     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13814     if (Converted.isInvalid())
13815       Failed = true;
13816 
13817     llvm::APSInt Cond;
13818     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13819           diag::err_static_assert_expression_is_not_constant,
13820           /*AllowFold=*/false).isInvalid())
13821       Failed = true;
13822 
13823     if (!Failed && !Cond) {
13824       SmallString<256> MsgBuffer;
13825       llvm::raw_svector_ostream Msg(MsgBuffer);
13826       if (AssertMessage)
13827         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13828 
13829       Expr *InnerCond = nullptr;
13830       std::string InnerCondDescription;
13831       std::tie(InnerCond, InnerCondDescription) =
13832         findFailedBooleanCondition(Converted.get(),
13833                                    /*AllowTopLevelCond=*/false);
13834       if (InnerCond) {
13835         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13836           << InnerCondDescription << !AssertMessage
13837           << Msg.str() << InnerCond->getSourceRange();
13838       } else {
13839         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13840           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13841       }
13842       Failed = true;
13843     }
13844   }
13845 
13846   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13847                                                   /*DiscardedValue*/false,
13848                                                   /*IsConstexpr*/true);
13849   if (FullAssertExpr.isInvalid())
13850     Failed = true;
13851   else
13852     AssertExpr = FullAssertExpr.get();
13853 
13854   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13855                                         AssertExpr, AssertMessage, RParenLoc,
13856                                         Failed);
13857 
13858   CurContext->addDecl(Decl);
13859   return Decl;
13860 }
13861 
13862 /// Perform semantic analysis of the given friend type declaration.
13863 ///
13864 /// \returns A friend declaration that.
13865 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13866                                       SourceLocation FriendLoc,
13867                                       TypeSourceInfo *TSInfo) {
13868   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13869 
13870   QualType T = TSInfo->getType();
13871   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13872 
13873   // C++03 [class.friend]p2:
13874   //   An elaborated-type-specifier shall be used in a friend declaration
13875   //   for a class.*
13876   //
13877   //   * The class-key of the elaborated-type-specifier is required.
13878   if (!CodeSynthesisContexts.empty()) {
13879     // Do not complain about the form of friend template types during any kind
13880     // of code synthesis. For template instantiation, we will have complained
13881     // when the template was defined.
13882   } else {
13883     if (!T->isElaboratedTypeSpecifier()) {
13884       // If we evaluated the type to a record type, suggest putting
13885       // a tag in front.
13886       if (const RecordType *RT = T->getAs<RecordType>()) {
13887         RecordDecl *RD = RT->getDecl();
13888 
13889         SmallString<16> InsertionText(" ");
13890         InsertionText += RD->getKindName();
13891 
13892         Diag(TypeRange.getBegin(),
13893              getLangOpts().CPlusPlus11 ?
13894                diag::warn_cxx98_compat_unelaborated_friend_type :
13895                diag::ext_unelaborated_friend_type)
13896           << (unsigned) RD->getTagKind()
13897           << T
13898           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13899                                         InsertionText);
13900       } else {
13901         Diag(FriendLoc,
13902              getLangOpts().CPlusPlus11 ?
13903                diag::warn_cxx98_compat_nonclass_type_friend :
13904                diag::ext_nonclass_type_friend)
13905           << T
13906           << TypeRange;
13907       }
13908     } else if (T->getAs<EnumType>()) {
13909       Diag(FriendLoc,
13910            getLangOpts().CPlusPlus11 ?
13911              diag::warn_cxx98_compat_enum_friend :
13912              diag::ext_enum_friend)
13913         << T
13914         << TypeRange;
13915     }
13916 
13917     // C++11 [class.friend]p3:
13918     //   A friend declaration that does not declare a function shall have one
13919     //   of the following forms:
13920     //     friend elaborated-type-specifier ;
13921     //     friend simple-type-specifier ;
13922     //     friend typename-specifier ;
13923     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13924       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13925   }
13926 
13927   //   If the type specifier in a friend declaration designates a (possibly
13928   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13929   //   the friend declaration is ignored.
13930   return FriendDecl::Create(Context, CurContext,
13931                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
13932                             FriendLoc);
13933 }
13934 
13935 /// Handle a friend tag declaration where the scope specifier was
13936 /// templated.
13937 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13938                                     unsigned TagSpec, SourceLocation TagLoc,
13939                                     CXXScopeSpec &SS, IdentifierInfo *Name,
13940                                     SourceLocation NameLoc,
13941                                     const ParsedAttributesView &Attr,
13942                                     MultiTemplateParamsArg TempParamLists) {
13943   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13944 
13945   bool IsMemberSpecialization = false;
13946   bool Invalid = false;
13947 
13948   if (TemplateParameterList *TemplateParams =
13949           MatchTemplateParametersToScopeSpecifier(
13950               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13951               IsMemberSpecialization, Invalid)) {
13952     if (TemplateParams->size() > 0) {
13953       // This is a declaration of a class template.
13954       if (Invalid)
13955         return nullptr;
13956 
13957       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13958                                 NameLoc, Attr, TemplateParams, AS_public,
13959                                 /*ModulePrivateLoc=*/SourceLocation(),
13960                                 FriendLoc, TempParamLists.size() - 1,
13961                                 TempParamLists.data()).get();
13962     } else {
13963       // The "template<>" header is extraneous.
13964       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13965         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13966       IsMemberSpecialization = true;
13967     }
13968   }
13969 
13970   if (Invalid) return nullptr;
13971 
13972   bool isAllExplicitSpecializations = true;
13973   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13974     if (TempParamLists[I]->size()) {
13975       isAllExplicitSpecializations = false;
13976       break;
13977     }
13978   }
13979 
13980   // FIXME: don't ignore attributes.
13981 
13982   // If it's explicit specializations all the way down, just forget
13983   // about the template header and build an appropriate non-templated
13984   // friend.  TODO: for source fidelity, remember the headers.
13985   if (isAllExplicitSpecializations) {
13986     if (SS.isEmpty()) {
13987       bool Owned = false;
13988       bool IsDependent = false;
13989       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13990                       Attr, AS_public,
13991                       /*ModulePrivateLoc=*/SourceLocation(),
13992                       MultiTemplateParamsArg(), Owned, IsDependent,
13993                       /*ScopedEnumKWLoc=*/SourceLocation(),
13994                       /*ScopedEnumUsesClassTag=*/false,
13995                       /*UnderlyingType=*/TypeResult(),
13996                       /*IsTypeSpecifier=*/false,
13997                       /*IsTemplateParamOrArg=*/false);
13998     }
13999 
14000     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14001     ElaboratedTypeKeyword Keyword
14002       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14003     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14004                                    *Name, NameLoc);
14005     if (T.isNull())
14006       return nullptr;
14007 
14008     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14009     if (isa<DependentNameType>(T)) {
14010       DependentNameTypeLoc TL =
14011           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14012       TL.setElaboratedKeywordLoc(TagLoc);
14013       TL.setQualifierLoc(QualifierLoc);
14014       TL.setNameLoc(NameLoc);
14015     } else {
14016       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14017       TL.setElaboratedKeywordLoc(TagLoc);
14018       TL.setQualifierLoc(QualifierLoc);
14019       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14020     }
14021 
14022     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14023                                             TSI, FriendLoc, TempParamLists);
14024     Friend->setAccess(AS_public);
14025     CurContext->addDecl(Friend);
14026     return Friend;
14027   }
14028 
14029   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14030 
14031 
14032 
14033   // Handle the case of a templated-scope friend class.  e.g.
14034   //   template <class T> class A<T>::B;
14035   // FIXME: we don't support these right now.
14036   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14037     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14038   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14039   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14040   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14041   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14042   TL.setElaboratedKeywordLoc(TagLoc);
14043   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14044   TL.setNameLoc(NameLoc);
14045 
14046   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14047                                           TSI, FriendLoc, TempParamLists);
14048   Friend->setAccess(AS_public);
14049   Friend->setUnsupportedFriend(true);
14050   CurContext->addDecl(Friend);
14051   return Friend;
14052 }
14053 
14054 /// Handle a friend type declaration.  This works in tandem with
14055 /// ActOnTag.
14056 ///
14057 /// Notes on friend class templates:
14058 ///
14059 /// We generally treat friend class declarations as if they were
14060 /// declaring a class.  So, for example, the elaborated type specifier
14061 /// in a friend declaration is required to obey the restrictions of a
14062 /// class-head (i.e. no typedefs in the scope chain), template
14063 /// parameters are required to match up with simple template-ids, &c.
14064 /// However, unlike when declaring a template specialization, it's
14065 /// okay to refer to a template specialization without an empty
14066 /// template parameter declaration, e.g.
14067 ///   friend class A<T>::B<unsigned>;
14068 /// We permit this as a special case; if there are any template
14069 /// parameters present at all, require proper matching, i.e.
14070 ///   template <> template \<class T> friend class A<int>::B;
14071 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14072                                 MultiTemplateParamsArg TempParams) {
14073   SourceLocation Loc = DS.getBeginLoc();
14074 
14075   assert(DS.isFriendSpecified());
14076   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14077 
14078   // C++ [class.friend]p3:
14079   // A friend declaration that does not declare a function shall have one of
14080   // the following forms:
14081   //     friend elaborated-type-specifier ;
14082   //     friend simple-type-specifier ;
14083   //     friend typename-specifier ;
14084   //
14085   // Any declaration with a type qualifier does not have that form. (It's
14086   // legal to specify a qualified type as a friend, you just can't write the
14087   // keywords.)
14088   if (DS.getTypeQualifiers()) {
14089     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14090       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14091     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14092       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14093     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14094       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14095     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14096       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14097     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14098       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14099   }
14100 
14101   // Try to convert the decl specifier to a type.  This works for
14102   // friend templates because ActOnTag never produces a ClassTemplateDecl
14103   // for a TUK_Friend.
14104   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14105   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14106   QualType T = TSI->getType();
14107   if (TheDeclarator.isInvalidType())
14108     return nullptr;
14109 
14110   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14111     return nullptr;
14112 
14113   // This is definitely an error in C++98.  It's probably meant to
14114   // be forbidden in C++0x, too, but the specification is just
14115   // poorly written.
14116   //
14117   // The problem is with declarations like the following:
14118   //   template <T> friend A<T>::foo;
14119   // where deciding whether a class C is a friend or not now hinges
14120   // on whether there exists an instantiation of A that causes
14121   // 'foo' to equal C.  There are restrictions on class-heads
14122   // (which we declare (by fiat) elaborated friend declarations to
14123   // be) that makes this tractable.
14124   //
14125   // FIXME: handle "template <> friend class A<T>;", which
14126   // is possibly well-formed?  Who even knows?
14127   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14128     Diag(Loc, diag::err_tagless_friend_type_template)
14129       << DS.getSourceRange();
14130     return nullptr;
14131   }
14132 
14133   // C++98 [class.friend]p1: A friend of a class is a function
14134   //   or class that is not a member of the class . . .
14135   // This is fixed in DR77, which just barely didn't make the C++03
14136   // deadline.  It's also a very silly restriction that seriously
14137   // affects inner classes and which nobody else seems to implement;
14138   // thus we never diagnose it, not even in -pedantic.
14139   //
14140   // But note that we could warn about it: it's always useless to
14141   // friend one of your own members (it's not, however, worthless to
14142   // friend a member of an arbitrary specialization of your template).
14143 
14144   Decl *D;
14145   if (!TempParams.empty())
14146     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14147                                    TempParams,
14148                                    TSI,
14149                                    DS.getFriendSpecLoc());
14150   else
14151     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14152 
14153   if (!D)
14154     return nullptr;
14155 
14156   D->setAccess(AS_public);
14157   CurContext->addDecl(D);
14158 
14159   return D;
14160 }
14161 
14162 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14163                                         MultiTemplateParamsArg TemplateParams) {
14164   const DeclSpec &DS = D.getDeclSpec();
14165 
14166   assert(DS.isFriendSpecified());
14167   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14168 
14169   SourceLocation Loc = D.getIdentifierLoc();
14170   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14171 
14172   // C++ [class.friend]p1
14173   //   A friend of a class is a function or class....
14174   // Note that this sees through typedefs, which is intended.
14175   // It *doesn't* see through dependent types, which is correct
14176   // according to [temp.arg.type]p3:
14177   //   If a declaration acquires a function type through a
14178   //   type dependent on a template-parameter and this causes
14179   //   a declaration that does not use the syntactic form of a
14180   //   function declarator to have a function type, the program
14181   //   is ill-formed.
14182   if (!TInfo->getType()->isFunctionType()) {
14183     Diag(Loc, diag::err_unexpected_friend);
14184 
14185     // It might be worthwhile to try to recover by creating an
14186     // appropriate declaration.
14187     return nullptr;
14188   }
14189 
14190   // C++ [namespace.memdef]p3
14191   //  - If a friend declaration in a non-local class first declares a
14192   //    class or function, the friend class or function is a member
14193   //    of the innermost enclosing namespace.
14194   //  - The name of the friend is not found by simple name lookup
14195   //    until a matching declaration is provided in that namespace
14196   //    scope (either before or after the class declaration granting
14197   //    friendship).
14198   //  - If a friend function is called, its name may be found by the
14199   //    name lookup that considers functions from namespaces and
14200   //    classes associated with the types of the function arguments.
14201   //  - When looking for a prior declaration of a class or a function
14202   //    declared as a friend, scopes outside the innermost enclosing
14203   //    namespace scope are not considered.
14204 
14205   CXXScopeSpec &SS = D.getCXXScopeSpec();
14206   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14207   DeclarationName Name = NameInfo.getName();
14208   assert(Name);
14209 
14210   // Check for unexpanded parameter packs.
14211   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14212       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14213       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14214     return nullptr;
14215 
14216   // The context we found the declaration in, or in which we should
14217   // create the declaration.
14218   DeclContext *DC;
14219   Scope *DCScope = S;
14220   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14221                         ForExternalRedeclaration);
14222 
14223   // There are five cases here.
14224   //   - There's no scope specifier and we're in a local class. Only look
14225   //     for functions declared in the immediately-enclosing block scope.
14226   // We recover from invalid scope qualifiers as if they just weren't there.
14227   FunctionDecl *FunctionContainingLocalClass = nullptr;
14228   if ((SS.isInvalid() || !SS.isSet()) &&
14229       (FunctionContainingLocalClass =
14230            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14231     // C++11 [class.friend]p11:
14232     //   If a friend declaration appears in a local class and the name
14233     //   specified is an unqualified name, a prior declaration is
14234     //   looked up without considering scopes that are outside the
14235     //   innermost enclosing non-class scope. For a friend function
14236     //   declaration, if there is no prior declaration, the program is
14237     //   ill-formed.
14238 
14239     // Find the innermost enclosing non-class scope. This is the block
14240     // scope containing the local class definition (or for a nested class,
14241     // the outer local class).
14242     DCScope = S->getFnParent();
14243 
14244     // Look up the function name in the scope.
14245     Previous.clear(LookupLocalFriendName);
14246     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14247 
14248     if (!Previous.empty()) {
14249       // All possible previous declarations must have the same context:
14250       // either they were declared at block scope or they are members of
14251       // one of the enclosing local classes.
14252       DC = Previous.getRepresentativeDecl()->getDeclContext();
14253     } else {
14254       // This is ill-formed, but provide the context that we would have
14255       // declared the function in, if we were permitted to, for error recovery.
14256       DC = FunctionContainingLocalClass;
14257     }
14258     adjustContextForLocalExternDecl(DC);
14259 
14260     // C++ [class.friend]p6:
14261     //   A function can be defined in a friend declaration of a class if and
14262     //   only if the class is a non-local class (9.8), the function name is
14263     //   unqualified, and the function has namespace scope.
14264     if (D.isFunctionDefinition()) {
14265       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14266     }
14267 
14268   //   - There's no scope specifier, in which case we just go to the
14269   //     appropriate scope and look for a function or function template
14270   //     there as appropriate.
14271   } else if (SS.isInvalid() || !SS.isSet()) {
14272     // C++11 [namespace.memdef]p3:
14273     //   If the name in a friend declaration is neither qualified nor
14274     //   a template-id and the declaration is a function or an
14275     //   elaborated-type-specifier, the lookup to determine whether
14276     //   the entity has been previously declared shall not consider
14277     //   any scopes outside the innermost enclosing namespace.
14278     bool isTemplateId =
14279         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14280 
14281     // Find the appropriate context according to the above.
14282     DC = CurContext;
14283 
14284     // Skip class contexts.  If someone can cite chapter and verse
14285     // for this behavior, that would be nice --- it's what GCC and
14286     // EDG do, and it seems like a reasonable intent, but the spec
14287     // really only says that checks for unqualified existing
14288     // declarations should stop at the nearest enclosing namespace,
14289     // not that they should only consider the nearest enclosing
14290     // namespace.
14291     while (DC->isRecord())
14292       DC = DC->getParent();
14293 
14294     DeclContext *LookupDC = DC;
14295     while (LookupDC->isTransparentContext())
14296       LookupDC = LookupDC->getParent();
14297 
14298     while (true) {
14299       LookupQualifiedName(Previous, LookupDC);
14300 
14301       if (!Previous.empty()) {
14302         DC = LookupDC;
14303         break;
14304       }
14305 
14306       if (isTemplateId) {
14307         if (isa<TranslationUnitDecl>(LookupDC)) break;
14308       } else {
14309         if (LookupDC->isFileContext()) break;
14310       }
14311       LookupDC = LookupDC->getParent();
14312     }
14313 
14314     DCScope = getScopeForDeclContext(S, DC);
14315 
14316   //   - There's a non-dependent scope specifier, in which case we
14317   //     compute it and do a previous lookup there for a function
14318   //     or function template.
14319   } else if (!SS.getScopeRep()->isDependent()) {
14320     DC = computeDeclContext(SS);
14321     if (!DC) return nullptr;
14322 
14323     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14324 
14325     LookupQualifiedName(Previous, DC);
14326 
14327     // Ignore things found implicitly in the wrong scope.
14328     // TODO: better diagnostics for this case.  Suggesting the right
14329     // qualified scope would be nice...
14330     LookupResult::Filter F = Previous.makeFilter();
14331     while (F.hasNext()) {
14332       NamedDecl *D = F.next();
14333       if (!DC->InEnclosingNamespaceSetOf(
14334               D->getDeclContext()->getRedeclContext()))
14335         F.erase();
14336     }
14337     F.done();
14338 
14339     if (Previous.empty()) {
14340       D.setInvalidType();
14341       Diag(Loc, diag::err_qualified_friend_not_found)
14342           << Name << TInfo->getType();
14343       return nullptr;
14344     }
14345 
14346     // C++ [class.friend]p1: A friend of a class is a function or
14347     //   class that is not a member of the class . . .
14348     if (DC->Equals(CurContext))
14349       Diag(DS.getFriendSpecLoc(),
14350            getLangOpts().CPlusPlus11 ?
14351              diag::warn_cxx98_compat_friend_is_member :
14352              diag::err_friend_is_member);
14353 
14354     if (D.isFunctionDefinition()) {
14355       // C++ [class.friend]p6:
14356       //   A function can be defined in a friend declaration of a class if and
14357       //   only if the class is a non-local class (9.8), the function name is
14358       //   unqualified, and the function has namespace scope.
14359       SemaDiagnosticBuilder DB
14360         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14361 
14362       DB << SS.getScopeRep();
14363       if (DC->isFileContext())
14364         DB << FixItHint::CreateRemoval(SS.getRange());
14365       SS.clear();
14366     }
14367 
14368   //   - There's a scope specifier that does not match any template
14369   //     parameter lists, in which case we use some arbitrary context,
14370   //     create a method or method template, and wait for instantiation.
14371   //   - There's a scope specifier that does match some template
14372   //     parameter lists, which we don't handle right now.
14373   } else {
14374     if (D.isFunctionDefinition()) {
14375       // C++ [class.friend]p6:
14376       //   A function can be defined in a friend declaration of a class if and
14377       //   only if the class is a non-local class (9.8), the function name is
14378       //   unqualified, and the function has namespace scope.
14379       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14380         << SS.getScopeRep();
14381     }
14382 
14383     DC = CurContext;
14384     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14385   }
14386 
14387   if (!DC->isRecord()) {
14388     int DiagArg = -1;
14389     switch (D.getName().getKind()) {
14390     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14391     case UnqualifiedIdKind::IK_ConstructorName:
14392       DiagArg = 0;
14393       break;
14394     case UnqualifiedIdKind::IK_DestructorName:
14395       DiagArg = 1;
14396       break;
14397     case UnqualifiedIdKind::IK_ConversionFunctionId:
14398       DiagArg = 2;
14399       break;
14400     case UnqualifiedIdKind::IK_DeductionGuideName:
14401       DiagArg = 3;
14402       break;
14403     case UnqualifiedIdKind::IK_Identifier:
14404     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14405     case UnqualifiedIdKind::IK_LiteralOperatorId:
14406     case UnqualifiedIdKind::IK_OperatorFunctionId:
14407     case UnqualifiedIdKind::IK_TemplateId:
14408       break;
14409     }
14410     // This implies that it has to be an operator or function.
14411     if (DiagArg >= 0) {
14412       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14413       return nullptr;
14414     }
14415   }
14416 
14417   // FIXME: This is an egregious hack to cope with cases where the scope stack
14418   // does not contain the declaration context, i.e., in an out-of-line
14419   // definition of a class.
14420   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14421   if (!DCScope) {
14422     FakeDCScope.setEntity(DC);
14423     DCScope = &FakeDCScope;
14424   }
14425 
14426   bool AddToScope = true;
14427   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14428                                           TemplateParams, AddToScope);
14429   if (!ND) return nullptr;
14430 
14431   assert(ND->getLexicalDeclContext() == CurContext);
14432 
14433   // If we performed typo correction, we might have added a scope specifier
14434   // and changed the decl context.
14435   DC = ND->getDeclContext();
14436 
14437   // Add the function declaration to the appropriate lookup tables,
14438   // adjusting the redeclarations list as necessary.  We don't
14439   // want to do this yet if the friending class is dependent.
14440   //
14441   // Also update the scope-based lookup if the target context's
14442   // lookup context is in lexical scope.
14443   if (!CurContext->isDependentContext()) {
14444     DC = DC->getRedeclContext();
14445     DC->makeDeclVisibleInContext(ND);
14446     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14447       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14448   }
14449 
14450   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14451                                        D.getIdentifierLoc(), ND,
14452                                        DS.getFriendSpecLoc());
14453   FrD->setAccess(AS_public);
14454   CurContext->addDecl(FrD);
14455 
14456   if (ND->isInvalidDecl()) {
14457     FrD->setInvalidDecl();
14458   } else {
14459     if (DC->isRecord()) CheckFriendAccess(ND);
14460 
14461     FunctionDecl *FD;
14462     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14463       FD = FTD->getTemplatedDecl();
14464     else
14465       FD = cast<FunctionDecl>(ND);
14466 
14467     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14468     // default argument expression, that declaration shall be a definition
14469     // and shall be the only declaration of the function or function
14470     // template in the translation unit.
14471     if (functionDeclHasDefaultArgument(FD)) {
14472       // We can't look at FD->getPreviousDecl() because it may not have been set
14473       // if we're in a dependent context. If the function is known to be a
14474       // redeclaration, we will have narrowed Previous down to the right decl.
14475       if (D.isRedeclaration()) {
14476         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14477         Diag(Previous.getRepresentativeDecl()->getLocation(),
14478              diag::note_previous_declaration);
14479       } else if (!D.isFunctionDefinition())
14480         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14481     }
14482 
14483     // Mark templated-scope function declarations as unsupported.
14484     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14485       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14486         << SS.getScopeRep() << SS.getRange()
14487         << cast<CXXRecordDecl>(CurContext);
14488       FrD->setUnsupportedFriend(true);
14489     }
14490   }
14491 
14492   return ND;
14493 }
14494 
14495 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14496   AdjustDeclIfTemplate(Dcl);
14497 
14498   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14499   if (!Fn) {
14500     Diag(DelLoc, diag::err_deleted_non_function);
14501     return;
14502   }
14503 
14504   // Deleted function does not have a body.
14505   Fn->setWillHaveBody(false);
14506 
14507   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14508     // Don't consider the implicit declaration we generate for explicit
14509     // specializations. FIXME: Do not generate these implicit declarations.
14510     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14511          Prev->getPreviousDecl()) &&
14512         !Prev->isDefined()) {
14513       Diag(DelLoc, diag::err_deleted_decl_not_first);
14514       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14515            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14516                               : diag::note_previous_declaration);
14517     }
14518     // If the declaration wasn't the first, we delete the function anyway for
14519     // recovery.
14520     Fn = Fn->getCanonicalDecl();
14521   }
14522 
14523   // dllimport/dllexport cannot be deleted.
14524   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14525     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14526     Fn->setInvalidDecl();
14527   }
14528 
14529   if (Fn->isDeleted())
14530     return;
14531 
14532   // See if we're deleting a function which is already known to override a
14533   // non-deleted virtual function.
14534   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14535     bool IssuedDiagnostic = false;
14536     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14537       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14538         if (!IssuedDiagnostic) {
14539           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14540           IssuedDiagnostic = true;
14541         }
14542         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14543       }
14544     }
14545     // If this function was implicitly deleted because it was defaulted,
14546     // explain why it was deleted.
14547     if (IssuedDiagnostic && MD->isDefaulted())
14548       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14549                                 /*Diagnose*/true);
14550   }
14551 
14552   // C++11 [basic.start.main]p3:
14553   //   A program that defines main as deleted [...] is ill-formed.
14554   if (Fn->isMain())
14555     Diag(DelLoc, diag::err_deleted_main);
14556 
14557   // C++11 [dcl.fct.def.delete]p4:
14558   //  A deleted function is implicitly inline.
14559   Fn->setImplicitlyInline();
14560   Fn->setDeletedAsWritten();
14561 }
14562 
14563 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14564   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14565 
14566   if (MD) {
14567     if (MD->getParent()->isDependentType()) {
14568       MD->setDefaulted();
14569       MD->setExplicitlyDefaulted();
14570       return;
14571     }
14572 
14573     CXXSpecialMember Member = getSpecialMember(MD);
14574     if (Member == CXXInvalid) {
14575       if (!MD->isInvalidDecl())
14576         Diag(DefaultLoc, diag::err_default_special_members);
14577       return;
14578     }
14579 
14580     MD->setDefaulted();
14581     MD->setExplicitlyDefaulted();
14582 
14583     // Unset that we will have a body for this function. We might not,
14584     // if it turns out to be trivial, and we don't need this marking now
14585     // that we've marked it as defaulted.
14586     MD->setWillHaveBody(false);
14587 
14588     // If this definition appears within the record, do the checking when
14589     // the record is complete.
14590     const FunctionDecl *Primary = MD;
14591     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14592       // Ask the template instantiation pattern that actually had the
14593       // '= default' on it.
14594       Primary = Pattern;
14595 
14596     // If the method was defaulted on its first declaration, we will have
14597     // already performed the checking in CheckCompletedCXXClass. Such a
14598     // declaration doesn't trigger an implicit definition.
14599     if (Primary->getCanonicalDecl()->isDefaulted())
14600       return;
14601 
14602     CheckExplicitlyDefaultedSpecialMember(MD);
14603 
14604     if (!MD->isInvalidDecl())
14605       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14606   } else {
14607     Diag(DefaultLoc, diag::err_default_special_members);
14608   }
14609 }
14610 
14611 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14612   for (Stmt *SubStmt : S->children()) {
14613     if (!SubStmt)
14614       continue;
14615     if (isa<ReturnStmt>(SubStmt))
14616       Self.Diag(SubStmt->getBeginLoc(),
14617                 diag::err_return_in_constructor_handler);
14618     if (!isa<Expr>(SubStmt))
14619       SearchForReturnInStmt(Self, SubStmt);
14620   }
14621 }
14622 
14623 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14624   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14625     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14626     SearchForReturnInStmt(*this, Handler);
14627   }
14628 }
14629 
14630 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14631                                              const CXXMethodDecl *Old) {
14632   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14633   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14634 
14635   if (OldFT->hasExtParameterInfos()) {
14636     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14637       // A parameter of the overriding method should be annotated with noescape
14638       // if the corresponding parameter of the overridden method is annotated.
14639       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14640           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14641         Diag(New->getParamDecl(I)->getLocation(),
14642              diag::warn_overriding_method_missing_noescape);
14643         Diag(Old->getParamDecl(I)->getLocation(),
14644              diag::note_overridden_marked_noescape);
14645       }
14646   }
14647 
14648   // Virtual overrides must have the same code_seg.
14649   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14650   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14651   if ((NewCSA || OldCSA) &&
14652       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14653     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14654     Diag(Old->getLocation(), diag::note_previous_declaration);
14655     return true;
14656   }
14657 
14658   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14659 
14660   // If the calling conventions match, everything is fine
14661   if (NewCC == OldCC)
14662     return false;
14663 
14664   // If the calling conventions mismatch because the new function is static,
14665   // suppress the calling convention mismatch error; the error about static
14666   // function override (err_static_overrides_virtual from
14667   // Sema::CheckFunctionDeclaration) is more clear.
14668   if (New->getStorageClass() == SC_Static)
14669     return false;
14670 
14671   Diag(New->getLocation(),
14672        diag::err_conflicting_overriding_cc_attributes)
14673     << New->getDeclName() << New->getType() << Old->getType();
14674   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14675   return true;
14676 }
14677 
14678 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14679                                              const CXXMethodDecl *Old) {
14680   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14681   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14682 
14683   if (Context.hasSameType(NewTy, OldTy) ||
14684       NewTy->isDependentType() || OldTy->isDependentType())
14685     return false;
14686 
14687   // Check if the return types are covariant
14688   QualType NewClassTy, OldClassTy;
14689 
14690   /// Both types must be pointers or references to classes.
14691   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14692     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14693       NewClassTy = NewPT->getPointeeType();
14694       OldClassTy = OldPT->getPointeeType();
14695     }
14696   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14697     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14698       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14699         NewClassTy = NewRT->getPointeeType();
14700         OldClassTy = OldRT->getPointeeType();
14701       }
14702     }
14703   }
14704 
14705   // The return types aren't either both pointers or references to a class type.
14706   if (NewClassTy.isNull()) {
14707     Diag(New->getLocation(),
14708          diag::err_different_return_type_for_overriding_virtual_function)
14709         << New->getDeclName() << NewTy << OldTy
14710         << New->getReturnTypeSourceRange();
14711     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14712         << Old->getReturnTypeSourceRange();
14713 
14714     return true;
14715   }
14716 
14717   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14718     // C++14 [class.virtual]p8:
14719     //   If the class type in the covariant return type of D::f differs from
14720     //   that of B::f, the class type in the return type of D::f shall be
14721     //   complete at the point of declaration of D::f or shall be the class
14722     //   type D.
14723     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14724       if (!RT->isBeingDefined() &&
14725           RequireCompleteType(New->getLocation(), NewClassTy,
14726                               diag::err_covariant_return_incomplete,
14727                               New->getDeclName()))
14728         return true;
14729     }
14730 
14731     // Check if the new class derives from the old class.
14732     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14733       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14734           << New->getDeclName() << NewTy << OldTy
14735           << New->getReturnTypeSourceRange();
14736       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14737           << Old->getReturnTypeSourceRange();
14738       return true;
14739     }
14740 
14741     // Check if we the conversion from derived to base is valid.
14742     if (CheckDerivedToBaseConversion(
14743             NewClassTy, OldClassTy,
14744             diag::err_covariant_return_inaccessible_base,
14745             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14746             New->getLocation(), New->getReturnTypeSourceRange(),
14747             New->getDeclName(), nullptr)) {
14748       // FIXME: this note won't trigger for delayed access control
14749       // diagnostics, and it's impossible to get an undelayed error
14750       // here from access control during the original parse because
14751       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14752       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14753           << Old->getReturnTypeSourceRange();
14754       return true;
14755     }
14756   }
14757 
14758   // The qualifiers of the return types must be the same.
14759   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14760     Diag(New->getLocation(),
14761          diag::err_covariant_return_type_different_qualifications)
14762         << New->getDeclName() << NewTy << OldTy
14763         << New->getReturnTypeSourceRange();
14764     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14765         << Old->getReturnTypeSourceRange();
14766     return true;
14767   }
14768 
14769 
14770   // The new class type must have the same or less qualifiers as the old type.
14771   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14772     Diag(New->getLocation(),
14773          diag::err_covariant_return_type_class_type_more_qualified)
14774         << New->getDeclName() << NewTy << OldTy
14775         << New->getReturnTypeSourceRange();
14776     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14777         << Old->getReturnTypeSourceRange();
14778     return true;
14779   }
14780 
14781   return false;
14782 }
14783 
14784 /// Mark the given method pure.
14785 ///
14786 /// \param Method the method to be marked pure.
14787 ///
14788 /// \param InitRange the source range that covers the "0" initializer.
14789 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14790   SourceLocation EndLoc = InitRange.getEnd();
14791   if (EndLoc.isValid())
14792     Method->setRangeEnd(EndLoc);
14793 
14794   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14795     Method->setPure();
14796     return false;
14797   }
14798 
14799   if (!Method->isInvalidDecl())
14800     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14801       << Method->getDeclName() << InitRange;
14802   return true;
14803 }
14804 
14805 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14806   if (D->getFriendObjectKind())
14807     Diag(D->getLocation(), diag::err_pure_friend);
14808   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14809     CheckPureMethod(M, ZeroLoc);
14810   else
14811     Diag(D->getLocation(), diag::err_illegal_initializer);
14812 }
14813 
14814 /// Determine whether the given declaration is a global variable or
14815 /// static data member.
14816 static bool isNonlocalVariable(const Decl *D) {
14817   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14818     return Var->hasGlobalStorage();
14819 
14820   return false;
14821 }
14822 
14823 /// Invoked when we are about to parse an initializer for the declaration
14824 /// 'Dcl'.
14825 ///
14826 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14827 /// static data member of class X, names should be looked up in the scope of
14828 /// class X. If the declaration had a scope specifier, a scope will have
14829 /// been created and passed in for this purpose. Otherwise, S will be null.
14830 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14831   // If there is no declaration, there was an error parsing it.
14832   if (!D || D->isInvalidDecl())
14833     return;
14834 
14835   // We will always have a nested name specifier here, but this declaration
14836   // might not be out of line if the specifier names the current namespace:
14837   //   extern int n;
14838   //   int ::n = 0;
14839   if (S && D->isOutOfLine())
14840     EnterDeclaratorContext(S, D->getDeclContext());
14841 
14842   // If we are parsing the initializer for a static data member, push a
14843   // new expression evaluation context that is associated with this static
14844   // data member.
14845   if (isNonlocalVariable(D))
14846     PushExpressionEvaluationContext(
14847         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14848 }
14849 
14850 /// Invoked after we are finished parsing an initializer for the declaration D.
14851 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14852   // If there is no declaration, there was an error parsing it.
14853   if (!D || D->isInvalidDecl())
14854     return;
14855 
14856   if (isNonlocalVariable(D))
14857     PopExpressionEvaluationContext();
14858 
14859   if (S && D->isOutOfLine())
14860     ExitDeclaratorContext(S);
14861 }
14862 
14863 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14864 /// C++ if/switch/while/for statement.
14865 /// e.g: "if (int x = f()) {...}"
14866 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14867   // C++ 6.4p2:
14868   // The declarator shall not specify a function or an array.
14869   // The type-specifier-seq shall not contain typedef and shall not declare a
14870   // new class or enumeration.
14871   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14872          "Parser allowed 'typedef' as storage class of condition decl.");
14873 
14874   Decl *Dcl = ActOnDeclarator(S, D);
14875   if (!Dcl)
14876     return true;
14877 
14878   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14879     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14880       << D.getSourceRange();
14881     return true;
14882   }
14883 
14884   return Dcl;
14885 }
14886 
14887 void Sema::LoadExternalVTableUses() {
14888   if (!ExternalSource)
14889     return;
14890 
14891   SmallVector<ExternalVTableUse, 4> VTables;
14892   ExternalSource->ReadUsedVTables(VTables);
14893   SmallVector<VTableUse, 4> NewUses;
14894   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14895     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14896       = VTablesUsed.find(VTables[I].Record);
14897     // Even if a definition wasn't required before, it may be required now.
14898     if (Pos != VTablesUsed.end()) {
14899       if (!Pos->second && VTables[I].DefinitionRequired)
14900         Pos->second = true;
14901       continue;
14902     }
14903 
14904     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14905     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14906   }
14907 
14908   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14909 }
14910 
14911 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14912                           bool DefinitionRequired) {
14913   // Ignore any vtable uses in unevaluated operands or for classes that do
14914   // not have a vtable.
14915   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14916       CurContext->isDependentContext() || isUnevaluatedContext())
14917     return;
14918   // Do not mark as used if compiling for the device outside of the target
14919   // region.
14920   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
14921       !isInOpenMPDeclareTargetContext() && !getCurFunctionDecl())
14922     return;
14923 
14924   // Try to insert this class into the map.
14925   LoadExternalVTableUses();
14926   Class = Class->getCanonicalDecl();
14927   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14928     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14929   if (!Pos.second) {
14930     // If we already had an entry, check to see if we are promoting this vtable
14931     // to require a definition. If so, we need to reappend to the VTableUses
14932     // list, since we may have already processed the first entry.
14933     if (DefinitionRequired && !Pos.first->second) {
14934       Pos.first->second = true;
14935     } else {
14936       // Otherwise, we can early exit.
14937       return;
14938     }
14939   } else {
14940     // The Microsoft ABI requires that we perform the destructor body
14941     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14942     // the deleting destructor is emitted with the vtable, not with the
14943     // destructor definition as in the Itanium ABI.
14944     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14945       CXXDestructorDecl *DD = Class->getDestructor();
14946       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14947         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14948           // If this is an out-of-line declaration, marking it referenced will
14949           // not do anything. Manually call CheckDestructor to look up operator
14950           // delete().
14951           ContextRAII SavedContext(*this, DD);
14952           CheckDestructor(DD);
14953         } else {
14954           MarkFunctionReferenced(Loc, Class->getDestructor());
14955         }
14956       }
14957     }
14958   }
14959 
14960   // Local classes need to have their virtual members marked
14961   // immediately. For all other classes, we mark their virtual members
14962   // at the end of the translation unit.
14963   if (Class->isLocalClass())
14964     MarkVirtualMembersReferenced(Loc, Class);
14965   else
14966     VTableUses.push_back(std::make_pair(Class, Loc));
14967 }
14968 
14969 bool Sema::DefineUsedVTables() {
14970   LoadExternalVTableUses();
14971   if (VTableUses.empty())
14972     return false;
14973 
14974   // Note: The VTableUses vector could grow as a result of marking
14975   // the members of a class as "used", so we check the size each
14976   // time through the loop and prefer indices (which are stable) to
14977   // iterators (which are not).
14978   bool DefinedAnything = false;
14979   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14980     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14981     if (!Class)
14982       continue;
14983     TemplateSpecializationKind ClassTSK =
14984         Class->getTemplateSpecializationKind();
14985 
14986     SourceLocation Loc = VTableUses[I].second;
14987 
14988     bool DefineVTable = true;
14989 
14990     // If this class has a key function, but that key function is
14991     // defined in another translation unit, we don't need to emit the
14992     // vtable even though we're using it.
14993     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14994     if (KeyFunction && !KeyFunction->hasBody()) {
14995       // The key function is in another translation unit.
14996       DefineVTable = false;
14997       TemplateSpecializationKind TSK =
14998           KeyFunction->getTemplateSpecializationKind();
14999       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15000              TSK != TSK_ImplicitInstantiation &&
15001              "Instantiations don't have key functions");
15002       (void)TSK;
15003     } else if (!KeyFunction) {
15004       // If we have a class with no key function that is the subject
15005       // of an explicit instantiation declaration, suppress the
15006       // vtable; it will live with the explicit instantiation
15007       // definition.
15008       bool IsExplicitInstantiationDeclaration =
15009           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15010       for (auto R : Class->redecls()) {
15011         TemplateSpecializationKind TSK
15012           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15013         if (TSK == TSK_ExplicitInstantiationDeclaration)
15014           IsExplicitInstantiationDeclaration = true;
15015         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15016           IsExplicitInstantiationDeclaration = false;
15017           break;
15018         }
15019       }
15020 
15021       if (IsExplicitInstantiationDeclaration)
15022         DefineVTable = false;
15023     }
15024 
15025     // The exception specifications for all virtual members may be needed even
15026     // if we are not providing an authoritative form of the vtable in this TU.
15027     // We may choose to emit it available_externally anyway.
15028     if (!DefineVTable) {
15029       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15030       continue;
15031     }
15032 
15033     // Mark all of the virtual members of this class as referenced, so
15034     // that we can build a vtable. Then, tell the AST consumer that a
15035     // vtable for this class is required.
15036     DefinedAnything = true;
15037     MarkVirtualMembersReferenced(Loc, Class);
15038     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15039     if (VTablesUsed[Canonical])
15040       Consumer.HandleVTable(Class);
15041 
15042     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15043     // no key function or the key function is inlined. Don't warn in C++ ABIs
15044     // that lack key functions, since the user won't be able to make one.
15045     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15046         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15047       const FunctionDecl *KeyFunctionDef = nullptr;
15048       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15049                            KeyFunctionDef->isInlined())) {
15050         Diag(Class->getLocation(),
15051              ClassTSK == TSK_ExplicitInstantiationDefinition
15052                  ? diag::warn_weak_template_vtable
15053                  : diag::warn_weak_vtable)
15054             << Class;
15055       }
15056     }
15057   }
15058   VTableUses.clear();
15059 
15060   return DefinedAnything;
15061 }
15062 
15063 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15064                                                  const CXXRecordDecl *RD) {
15065   for (const auto *I : RD->methods())
15066     if (I->isVirtual() && !I->isPure())
15067       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15068 }
15069 
15070 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15071                                         const CXXRecordDecl *RD) {
15072   // Mark all functions which will appear in RD's vtable as used.
15073   CXXFinalOverriderMap FinalOverriders;
15074   RD->getFinalOverriders(FinalOverriders);
15075   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15076                                             E = FinalOverriders.end();
15077        I != E; ++I) {
15078     for (OverridingMethods::const_iterator OI = I->second.begin(),
15079                                            OE = I->second.end();
15080          OI != OE; ++OI) {
15081       assert(OI->second.size() > 0 && "no final overrider");
15082       CXXMethodDecl *Overrider = OI->second.front().Method;
15083 
15084       // C++ [basic.def.odr]p2:
15085       //   [...] A virtual member function is used if it is not pure. [...]
15086       if (!Overrider->isPure())
15087         MarkFunctionReferenced(Loc, Overrider);
15088     }
15089   }
15090 
15091   // Only classes that have virtual bases need a VTT.
15092   if (RD->getNumVBases() == 0)
15093     return;
15094 
15095   for (const auto &I : RD->bases()) {
15096     const CXXRecordDecl *Base =
15097         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15098     if (Base->getNumVBases() == 0)
15099       continue;
15100     MarkVirtualMembersReferenced(Loc, Base);
15101   }
15102 }
15103 
15104 /// SetIvarInitializers - This routine builds initialization ASTs for the
15105 /// Objective-C implementation whose ivars need be initialized.
15106 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15107   if (!getLangOpts().CPlusPlus)
15108     return;
15109   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15110     SmallVector<ObjCIvarDecl*, 8> ivars;
15111     CollectIvarsToConstructOrDestruct(OID, ivars);
15112     if (ivars.empty())
15113       return;
15114     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15115     for (unsigned i = 0; i < ivars.size(); i++) {
15116       FieldDecl *Field = ivars[i];
15117       if (Field->isInvalidDecl())
15118         continue;
15119 
15120       CXXCtorInitializer *Member;
15121       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15122       InitializationKind InitKind =
15123         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15124 
15125       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15126       ExprResult MemberInit =
15127         InitSeq.Perform(*this, InitEntity, InitKind, None);
15128       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15129       // Note, MemberInit could actually come back empty if no initialization
15130       // is required (e.g., because it would call a trivial default constructor)
15131       if (!MemberInit.get() || MemberInit.isInvalid())
15132         continue;
15133 
15134       Member =
15135         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15136                                          SourceLocation(),
15137                                          MemberInit.getAs<Expr>(),
15138                                          SourceLocation());
15139       AllToInit.push_back(Member);
15140 
15141       // Be sure that the destructor is accessible and is marked as referenced.
15142       if (const RecordType *RecordTy =
15143               Context.getBaseElementType(Field->getType())
15144                   ->getAs<RecordType>()) {
15145         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15146         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15147           MarkFunctionReferenced(Field->getLocation(), Destructor);
15148           CheckDestructorAccess(Field->getLocation(), Destructor,
15149                             PDiag(diag::err_access_dtor_ivar)
15150                               << Context.getBaseElementType(Field->getType()));
15151         }
15152       }
15153     }
15154     ObjCImplementation->setIvarInitializers(Context,
15155                                             AllToInit.data(), AllToInit.size());
15156   }
15157 }
15158 
15159 static
15160 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15161                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15162                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15163                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15164                            Sema &S) {
15165   if (Ctor->isInvalidDecl())
15166     return;
15167 
15168   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15169 
15170   // Target may not be determinable yet, for instance if this is a dependent
15171   // call in an uninstantiated template.
15172   if (Target) {
15173     const FunctionDecl *FNTarget = nullptr;
15174     (void)Target->hasBody(FNTarget);
15175     Target = const_cast<CXXConstructorDecl*>(
15176       cast_or_null<CXXConstructorDecl>(FNTarget));
15177   }
15178 
15179   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15180                      // Avoid dereferencing a null pointer here.
15181                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15182 
15183   if (!Current.insert(Canonical).second)
15184     return;
15185 
15186   // We know that beyond here, we aren't chaining into a cycle.
15187   if (!Target || !Target->isDelegatingConstructor() ||
15188       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15189     Valid.insert(Current.begin(), Current.end());
15190     Current.clear();
15191   // We've hit a cycle.
15192   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15193              Current.count(TCanonical)) {
15194     // If we haven't diagnosed this cycle yet, do so now.
15195     if (!Invalid.count(TCanonical)) {
15196       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15197              diag::warn_delegating_ctor_cycle)
15198         << Ctor;
15199 
15200       // Don't add a note for a function delegating directly to itself.
15201       if (TCanonical != Canonical)
15202         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15203 
15204       CXXConstructorDecl *C = Target;
15205       while (C->getCanonicalDecl() != Canonical) {
15206         const FunctionDecl *FNTarget = nullptr;
15207         (void)C->getTargetConstructor()->hasBody(FNTarget);
15208         assert(FNTarget && "Ctor cycle through bodiless function");
15209 
15210         C = const_cast<CXXConstructorDecl*>(
15211           cast<CXXConstructorDecl>(FNTarget));
15212         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15213       }
15214     }
15215 
15216     Invalid.insert(Current.begin(), Current.end());
15217     Current.clear();
15218   } else {
15219     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15220   }
15221 }
15222 
15223 
15224 void Sema::CheckDelegatingCtorCycles() {
15225   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15226 
15227   for (DelegatingCtorDeclsType::iterator
15228          I = DelegatingCtorDecls.begin(ExternalSource),
15229          E = DelegatingCtorDecls.end();
15230        I != E; ++I)
15231     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15232 
15233   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15234     (*CI)->setInvalidDecl();
15235 }
15236 
15237 namespace {
15238   /// AST visitor that finds references to the 'this' expression.
15239   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15240     Sema &S;
15241 
15242   public:
15243     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15244 
15245     bool VisitCXXThisExpr(CXXThisExpr *E) {
15246       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15247         << E->isImplicit();
15248       return false;
15249     }
15250   };
15251 }
15252 
15253 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15254   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15255   if (!TSInfo)
15256     return false;
15257 
15258   TypeLoc TL = TSInfo->getTypeLoc();
15259   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15260   if (!ProtoTL)
15261     return false;
15262 
15263   // C++11 [expr.prim.general]p3:
15264   //   [The expression this] shall not appear before the optional
15265   //   cv-qualifier-seq and it shall not appear within the declaration of a
15266   //   static member function (although its type and value category are defined
15267   //   within a static member function as they are within a non-static member
15268   //   function). [ Note: this is because declaration matching does not occur
15269   //  until the complete declarator is known. - end note ]
15270   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15271   FindCXXThisExpr Finder(*this);
15272 
15273   // If the return type came after the cv-qualifier-seq, check it now.
15274   if (Proto->hasTrailingReturn() &&
15275       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15276     return true;
15277 
15278   // Check the exception specification.
15279   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15280     return true;
15281 
15282   return checkThisInStaticMemberFunctionAttributes(Method);
15283 }
15284 
15285 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15286   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15287   if (!TSInfo)
15288     return false;
15289 
15290   TypeLoc TL = TSInfo->getTypeLoc();
15291   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15292   if (!ProtoTL)
15293     return false;
15294 
15295   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15296   FindCXXThisExpr Finder(*this);
15297 
15298   switch (Proto->getExceptionSpecType()) {
15299   case EST_Unparsed:
15300   case EST_Uninstantiated:
15301   case EST_Unevaluated:
15302   case EST_BasicNoexcept:
15303   case EST_DynamicNone:
15304   case EST_MSAny:
15305   case EST_None:
15306     break;
15307 
15308   case EST_DependentNoexcept:
15309   case EST_NoexceptFalse:
15310   case EST_NoexceptTrue:
15311     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15312       return true;
15313     LLVM_FALLTHROUGH;
15314 
15315   case EST_Dynamic:
15316     for (const auto &E : Proto->exceptions()) {
15317       if (!Finder.TraverseType(E))
15318         return true;
15319     }
15320     break;
15321   }
15322 
15323   return false;
15324 }
15325 
15326 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15327   FindCXXThisExpr Finder(*this);
15328 
15329   // Check attributes.
15330   for (const auto *A : Method->attrs()) {
15331     // FIXME: This should be emitted by tblgen.
15332     Expr *Arg = nullptr;
15333     ArrayRef<Expr *> Args;
15334     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15335       Arg = G->getArg();
15336     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15337       Arg = G->getArg();
15338     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15339       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15340     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15341       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15342     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15343       Arg = ETLF->getSuccessValue();
15344       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15345     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15346       Arg = STLF->getSuccessValue();
15347       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15348     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15349       Arg = LR->getArg();
15350     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15351       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15352     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15353       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15354     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15355       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15356     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15357       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15358     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15359       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15360 
15361     if (Arg && !Finder.TraverseStmt(Arg))
15362       return true;
15363 
15364     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15365       if (!Finder.TraverseStmt(Args[I]))
15366         return true;
15367     }
15368   }
15369 
15370   return false;
15371 }
15372 
15373 void Sema::checkExceptionSpecification(
15374     bool IsTopLevel, ExceptionSpecificationType EST,
15375     ArrayRef<ParsedType> DynamicExceptions,
15376     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15377     SmallVectorImpl<QualType> &Exceptions,
15378     FunctionProtoType::ExceptionSpecInfo &ESI) {
15379   Exceptions.clear();
15380   ESI.Type = EST;
15381   if (EST == EST_Dynamic) {
15382     Exceptions.reserve(DynamicExceptions.size());
15383     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15384       // FIXME: Preserve type source info.
15385       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15386 
15387       if (IsTopLevel) {
15388         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15389         collectUnexpandedParameterPacks(ET, Unexpanded);
15390         if (!Unexpanded.empty()) {
15391           DiagnoseUnexpandedParameterPacks(
15392               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15393               Unexpanded);
15394           continue;
15395         }
15396       }
15397 
15398       // Check that the type is valid for an exception spec, and
15399       // drop it if not.
15400       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15401         Exceptions.push_back(ET);
15402     }
15403     ESI.Exceptions = Exceptions;
15404     return;
15405   }
15406 
15407   if (isComputedNoexcept(EST)) {
15408     assert((NoexceptExpr->isTypeDependent() ||
15409             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15410             Context.BoolTy) &&
15411            "Parser should have made sure that the expression is boolean");
15412     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15413       ESI.Type = EST_BasicNoexcept;
15414       return;
15415     }
15416 
15417     ESI.NoexceptExpr = NoexceptExpr;
15418     return;
15419   }
15420 }
15421 
15422 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15423              ExceptionSpecificationType EST,
15424              SourceRange SpecificationRange,
15425              ArrayRef<ParsedType> DynamicExceptions,
15426              ArrayRef<SourceRange> DynamicExceptionRanges,
15427              Expr *NoexceptExpr) {
15428   if (!MethodD)
15429     return;
15430 
15431   // Dig out the method we're referring to.
15432   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15433     MethodD = FunTmpl->getTemplatedDecl();
15434 
15435   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15436   if (!Method)
15437     return;
15438 
15439   // Check the exception specification.
15440   llvm::SmallVector<QualType, 4> Exceptions;
15441   FunctionProtoType::ExceptionSpecInfo ESI;
15442   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15443                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15444                               ESI);
15445 
15446   // Update the exception specification on the function type.
15447   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15448 
15449   if (Method->isStatic())
15450     checkThisInStaticMemberFunctionExceptionSpec(Method);
15451 
15452   if (Method->isVirtual()) {
15453     // Check overrides, which we previously had to delay.
15454     for (const CXXMethodDecl *O : Method->overridden_methods())
15455       CheckOverridingFunctionExceptionSpec(Method, O);
15456   }
15457 }
15458 
15459 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15460 ///
15461 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15462                                        SourceLocation DeclStart, Declarator &D,
15463                                        Expr *BitWidth,
15464                                        InClassInitStyle InitStyle,
15465                                        AccessSpecifier AS,
15466                                        const ParsedAttr &MSPropertyAttr) {
15467   IdentifierInfo *II = D.getIdentifier();
15468   if (!II) {
15469     Diag(DeclStart, diag::err_anonymous_property);
15470     return nullptr;
15471   }
15472   SourceLocation Loc = D.getIdentifierLoc();
15473 
15474   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15475   QualType T = TInfo->getType();
15476   if (getLangOpts().CPlusPlus) {
15477     CheckExtraCXXDefaultArguments(D);
15478 
15479     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15480                                         UPPC_DataMemberType)) {
15481       D.setInvalidType();
15482       T = Context.IntTy;
15483       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15484     }
15485   }
15486 
15487   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15488 
15489   if (D.getDeclSpec().isInlineSpecified())
15490     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15491         << getLangOpts().CPlusPlus17;
15492   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15493     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15494          diag::err_invalid_thread)
15495       << DeclSpec::getSpecifierName(TSCS);
15496 
15497   // Check to see if this name was declared as a member previously
15498   NamedDecl *PrevDecl = nullptr;
15499   LookupResult Previous(*this, II, Loc, LookupMemberName,
15500                         ForVisibleRedeclaration);
15501   LookupName(Previous, S);
15502   switch (Previous.getResultKind()) {
15503   case LookupResult::Found:
15504   case LookupResult::FoundUnresolvedValue:
15505     PrevDecl = Previous.getAsSingle<NamedDecl>();
15506     break;
15507 
15508   case LookupResult::FoundOverloaded:
15509     PrevDecl = Previous.getRepresentativeDecl();
15510     break;
15511 
15512   case LookupResult::NotFound:
15513   case LookupResult::NotFoundInCurrentInstantiation:
15514   case LookupResult::Ambiguous:
15515     break;
15516   }
15517 
15518   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15519     // Maybe we will complain about the shadowed template parameter.
15520     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15521     // Just pretend that we didn't see the previous declaration.
15522     PrevDecl = nullptr;
15523   }
15524 
15525   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15526     PrevDecl = nullptr;
15527 
15528   SourceLocation TSSL = D.getBeginLoc();
15529   MSPropertyDecl *NewPD =
15530       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15531                              MSPropertyAttr.getPropertyDataGetter(),
15532                              MSPropertyAttr.getPropertyDataSetter());
15533   ProcessDeclAttributes(TUScope, NewPD, D);
15534   NewPD->setAccess(AS);
15535 
15536   if (NewPD->isInvalidDecl())
15537     Record->setInvalidDecl();
15538 
15539   if (D.getDeclSpec().isModulePrivateSpecified())
15540     NewPD->setModulePrivate();
15541 
15542   if (NewPD->isInvalidDecl() && PrevDecl) {
15543     // Don't introduce NewFD into scope; there's already something
15544     // with the same name in the same scope.
15545   } else if (II) {
15546     PushOnScopeChains(NewPD, S);
15547   } else
15548     Record->addDecl(NewPD);
15549 
15550   return NewPD;
15551 }
15552