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 /// Handle a C++ member initializer.
3781 MemInitResult
3782 Sema::BuildMemInitializer(Decl *ConstructorD,
3783                           Scope *S,
3784                           CXXScopeSpec &SS,
3785                           IdentifierInfo *MemberOrBase,
3786                           ParsedType TemplateTypeTy,
3787                           const DeclSpec &DS,
3788                           SourceLocation IdLoc,
3789                           Expr *Init,
3790                           SourceLocation EllipsisLoc) {
3791   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3792   if (!Res.isUsable())
3793     return true;
3794   Init = Res.get();
3795 
3796   if (!ConstructorD)
3797     return true;
3798 
3799   AdjustDeclIfTemplate(ConstructorD);
3800 
3801   CXXConstructorDecl *Constructor
3802     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3803   if (!Constructor) {
3804     // The user wrote a constructor initializer on a function that is
3805     // not a C++ constructor. Ignore the error for now, because we may
3806     // have more member initializers coming; we'll diagnose it just
3807     // once in ActOnMemInitializers.
3808     return true;
3809   }
3810 
3811   CXXRecordDecl *ClassDecl = Constructor->getParent();
3812 
3813   // C++ [class.base.init]p2:
3814   //   Names in a mem-initializer-id are looked up in the scope of the
3815   //   constructor's class and, if not found in that scope, are looked
3816   //   up in the scope containing the constructor's definition.
3817   //   [Note: if the constructor's class contains a member with the
3818   //   same name as a direct or virtual base class of the class, a
3819   //   mem-initializer-id naming the member or base class and composed
3820   //   of a single identifier refers to the class member. A
3821   //   mem-initializer-id for the hidden base class may be specified
3822   //   using a qualified name. ]
3823   if (!SS.getScopeRep() && !TemplateTypeTy) {
3824     // Look for a member, first.
3825     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3826     if (!Result.empty()) {
3827       ValueDecl *Member;
3828       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3829           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3830         if (EllipsisLoc.isValid())
3831           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3832             << MemberOrBase
3833             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3834 
3835         return BuildMemberInitializer(Member, Init, IdLoc);
3836       }
3837     }
3838   }
3839   // It didn't name a member, so see if it names a class.
3840   QualType BaseType;
3841   TypeSourceInfo *TInfo = nullptr;
3842 
3843   if (TemplateTypeTy) {
3844     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3845   } else if (DS.getTypeSpecType() == TST_decltype) {
3846     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3847   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3848     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3849     return true;
3850   } else {
3851     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3852     LookupParsedName(R, S, &SS);
3853 
3854     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3855     if (!TyD) {
3856       if (R.isAmbiguous()) return true;
3857 
3858       // We don't want access-control diagnostics here.
3859       R.suppressDiagnostics();
3860 
3861       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3862         bool NotUnknownSpecialization = false;
3863         DeclContext *DC = computeDeclContext(SS, false);
3864         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3865           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3866 
3867         if (!NotUnknownSpecialization) {
3868           // When the scope specifier can refer to a member of an unknown
3869           // specialization, we take it as a type name.
3870           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3871                                        SS.getWithLocInContext(Context),
3872                                        *MemberOrBase, IdLoc);
3873           if (BaseType.isNull())
3874             return true;
3875 
3876           TInfo = Context.CreateTypeSourceInfo(BaseType);
3877           DependentNameTypeLoc TL =
3878               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3879           if (!TL.isNull()) {
3880             TL.setNameLoc(IdLoc);
3881             TL.setElaboratedKeywordLoc(SourceLocation());
3882             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3883           }
3884 
3885           R.clear();
3886           R.setLookupName(MemberOrBase);
3887         }
3888       }
3889 
3890       // If no results were found, try to correct typos.
3891       TypoCorrection Corr;
3892       if (R.empty() && BaseType.isNull() &&
3893           (Corr = CorrectTypo(
3894                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3895                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3896                CTK_ErrorRecovery, ClassDecl))) {
3897         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3898           // We have found a non-static data member with a similar
3899           // name to what was typed; complain and initialize that
3900           // member.
3901           diagnoseTypo(Corr,
3902                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3903                          << MemberOrBase << true);
3904           return BuildMemberInitializer(Member, Init, IdLoc);
3905         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3906           const CXXBaseSpecifier *DirectBaseSpec;
3907           const CXXBaseSpecifier *VirtualBaseSpec;
3908           if (FindBaseInitializer(*this, ClassDecl,
3909                                   Context.getTypeDeclType(Type),
3910                                   DirectBaseSpec, VirtualBaseSpec)) {
3911             // We have found a direct or virtual base class with a
3912             // similar name to what was typed; complain and initialize
3913             // that base class.
3914             diagnoseTypo(Corr,
3915                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3916                            << MemberOrBase << false,
3917                          PDiag() /*Suppress note, we provide our own.*/);
3918 
3919             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3920                                                               : VirtualBaseSpec;
3921             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3922                 << BaseSpec->getType() << BaseSpec->getSourceRange();
3923 
3924             TyD = Type;
3925           }
3926         }
3927       }
3928 
3929       if (!TyD && BaseType.isNull()) {
3930         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3931           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3932         return true;
3933       }
3934     }
3935 
3936     if (BaseType.isNull()) {
3937       BaseType = Context.getTypeDeclType(TyD);
3938       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3939       if (SS.isSet()) {
3940         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3941                                              BaseType);
3942         TInfo = Context.CreateTypeSourceInfo(BaseType);
3943         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3944         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3945         TL.setElaboratedKeywordLoc(SourceLocation());
3946         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3947       }
3948     }
3949   }
3950 
3951   if (!TInfo)
3952     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3953 
3954   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3955 }
3956 
3957 MemInitResult
3958 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3959                              SourceLocation IdLoc) {
3960   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3961   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3962   assert((DirectMember || IndirectMember) &&
3963          "Member must be a FieldDecl or IndirectFieldDecl");
3964 
3965   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3966     return true;
3967 
3968   if (Member->isInvalidDecl())
3969     return true;
3970 
3971   MultiExprArg Args;
3972   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3973     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3974   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3975     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3976   } else {
3977     // Template instantiation doesn't reconstruct ParenListExprs for us.
3978     Args = Init;
3979   }
3980 
3981   SourceRange InitRange = Init->getSourceRange();
3982 
3983   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3984     // Can't check initialization for a member of dependent type or when
3985     // any of the arguments are type-dependent expressions.
3986     DiscardCleanupsInEvaluationContext();
3987   } else {
3988     bool InitList = false;
3989     if (isa<InitListExpr>(Init)) {
3990       InitList = true;
3991       Args = Init;
3992     }
3993 
3994     // Initialize the member.
3995     InitializedEntity MemberEntity =
3996       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3997                    : InitializedEntity::InitializeMember(IndirectMember,
3998                                                          nullptr);
3999     InitializationKind Kind =
4000         InitList ? InitializationKind::CreateDirectList(
4001                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4002                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4003                                                     InitRange.getEnd());
4004 
4005     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4006     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4007                                             nullptr);
4008     if (MemberInit.isInvalid())
4009       return true;
4010 
4011     // C++11 [class.base.init]p7:
4012     //   The initialization of each base and member constitutes a
4013     //   full-expression.
4014     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4015     if (MemberInit.isInvalid())
4016       return true;
4017 
4018     Init = MemberInit.get();
4019   }
4020 
4021   if (DirectMember) {
4022     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4023                                             InitRange.getBegin(), Init,
4024                                             InitRange.getEnd());
4025   } else {
4026     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4027                                             InitRange.getBegin(), Init,
4028                                             InitRange.getEnd());
4029   }
4030 }
4031 
4032 MemInitResult
4033 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4034                                  CXXRecordDecl *ClassDecl) {
4035   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4036   if (!LangOpts.CPlusPlus11)
4037     return Diag(NameLoc, diag::err_delegating_ctor)
4038       << TInfo->getTypeLoc().getLocalSourceRange();
4039   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4040 
4041   bool InitList = true;
4042   MultiExprArg Args = Init;
4043   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4044     InitList = false;
4045     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4046   }
4047 
4048   SourceRange InitRange = Init->getSourceRange();
4049   // Initialize the object.
4050   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4051                                      QualType(ClassDecl->getTypeForDecl(), 0));
4052   InitializationKind Kind =
4053       InitList ? InitializationKind::CreateDirectList(
4054                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4055                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4056                                                   InitRange.getEnd());
4057   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4058   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4059                                               Args, nullptr);
4060   if (DelegationInit.isInvalid())
4061     return true;
4062 
4063   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4064          "Delegating constructor with no target?");
4065 
4066   // C++11 [class.base.init]p7:
4067   //   The initialization of each base and member constitutes a
4068   //   full-expression.
4069   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4070                                        InitRange.getBegin());
4071   if (DelegationInit.isInvalid())
4072     return true;
4073 
4074   // If we are in a dependent context, template instantiation will
4075   // perform this type-checking again. Just save the arguments that we
4076   // received in a ParenListExpr.
4077   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4078   // of the information that we have about the base
4079   // initializer. However, deconstructing the ASTs is a dicey process,
4080   // and this approach is far more likely to get the corner cases right.
4081   if (CurContext->isDependentContext())
4082     DelegationInit = Init;
4083 
4084   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4085                                           DelegationInit.getAs<Expr>(),
4086                                           InitRange.getEnd());
4087 }
4088 
4089 MemInitResult
4090 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4091                            Expr *Init, CXXRecordDecl *ClassDecl,
4092                            SourceLocation EllipsisLoc) {
4093   SourceLocation BaseLoc
4094     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4095 
4096   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4097     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4098              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4099 
4100   // C++ [class.base.init]p2:
4101   //   [...] Unless the mem-initializer-id names a nonstatic data
4102   //   member of the constructor's class or a direct or virtual base
4103   //   of that class, the mem-initializer is ill-formed. A
4104   //   mem-initializer-list can initialize a base class using any
4105   //   name that denotes that base class type.
4106   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4107 
4108   SourceRange InitRange = Init->getSourceRange();
4109   if (EllipsisLoc.isValid()) {
4110     // This is a pack expansion.
4111     if (!BaseType->containsUnexpandedParameterPack())  {
4112       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4113         << SourceRange(BaseLoc, InitRange.getEnd());
4114 
4115       EllipsisLoc = SourceLocation();
4116     }
4117   } else {
4118     // Check for any unexpanded parameter packs.
4119     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4120       return true;
4121 
4122     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4123       return true;
4124   }
4125 
4126   // Check for direct and virtual base classes.
4127   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4128   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4129   if (!Dependent) {
4130     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4131                                        BaseType))
4132       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4133 
4134     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4135                         VirtualBaseSpec);
4136 
4137     // C++ [base.class.init]p2:
4138     // Unless the mem-initializer-id names a nonstatic data member of the
4139     // constructor's class or a direct or virtual base of that class, the
4140     // mem-initializer is ill-formed.
4141     if (!DirectBaseSpec && !VirtualBaseSpec) {
4142       // If the class has any dependent bases, then it's possible that
4143       // one of those types will resolve to the same type as
4144       // BaseType. Therefore, just treat this as a dependent base
4145       // class initialization.  FIXME: Should we try to check the
4146       // initialization anyway? It seems odd.
4147       if (ClassDecl->hasAnyDependentBases())
4148         Dependent = true;
4149       else
4150         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4151           << BaseType << Context.getTypeDeclType(ClassDecl)
4152           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4153     }
4154   }
4155 
4156   if (Dependent) {
4157     DiscardCleanupsInEvaluationContext();
4158 
4159     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4160                                             /*IsVirtual=*/false,
4161                                             InitRange.getBegin(), Init,
4162                                             InitRange.getEnd(), EllipsisLoc);
4163   }
4164 
4165   // C++ [base.class.init]p2:
4166   //   If a mem-initializer-id is ambiguous because it designates both
4167   //   a direct non-virtual base class and an inherited virtual base
4168   //   class, the mem-initializer is ill-formed.
4169   if (DirectBaseSpec && VirtualBaseSpec)
4170     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4171       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4172 
4173   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4174   if (!BaseSpec)
4175     BaseSpec = VirtualBaseSpec;
4176 
4177   // Initialize the base.
4178   bool InitList = true;
4179   MultiExprArg Args = Init;
4180   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4181     InitList = false;
4182     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4183   }
4184 
4185   InitializedEntity BaseEntity =
4186     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4187   InitializationKind Kind =
4188       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4189                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4190                                                   InitRange.getEnd());
4191   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4192   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4193   if (BaseInit.isInvalid())
4194     return true;
4195 
4196   // C++11 [class.base.init]p7:
4197   //   The initialization of each base and member constitutes a
4198   //   full-expression.
4199   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4200   if (BaseInit.isInvalid())
4201     return true;
4202 
4203   // If we are in a dependent context, template instantiation will
4204   // perform this type-checking again. Just save the arguments that we
4205   // received in a ParenListExpr.
4206   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4207   // of the information that we have about the base
4208   // initializer. However, deconstructing the ASTs is a dicey process,
4209   // and this approach is far more likely to get the corner cases right.
4210   if (CurContext->isDependentContext())
4211     BaseInit = Init;
4212 
4213   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4214                                           BaseSpec->isVirtual(),
4215                                           InitRange.getBegin(),
4216                                           BaseInit.getAs<Expr>(),
4217                                           InitRange.getEnd(), EllipsisLoc);
4218 }
4219 
4220 // Create a static_cast\<T&&>(expr).
4221 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4222   if (T.isNull()) T = E->getType();
4223   QualType TargetType = SemaRef.BuildReferenceType(
4224       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4225   SourceLocation ExprLoc = E->getBeginLoc();
4226   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4227       TargetType, ExprLoc);
4228 
4229   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4230                                    SourceRange(ExprLoc, ExprLoc),
4231                                    E->getSourceRange()).get();
4232 }
4233 
4234 /// ImplicitInitializerKind - How an implicit base or member initializer should
4235 /// initialize its base or member.
4236 enum ImplicitInitializerKind {
4237   IIK_Default,
4238   IIK_Copy,
4239   IIK_Move,
4240   IIK_Inherit
4241 };
4242 
4243 static bool
4244 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4245                              ImplicitInitializerKind ImplicitInitKind,
4246                              CXXBaseSpecifier *BaseSpec,
4247                              bool IsInheritedVirtualBase,
4248                              CXXCtorInitializer *&CXXBaseInit) {
4249   InitializedEntity InitEntity
4250     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4251                                         IsInheritedVirtualBase);
4252 
4253   ExprResult BaseInit;
4254 
4255   switch (ImplicitInitKind) {
4256   case IIK_Inherit:
4257   case IIK_Default: {
4258     InitializationKind InitKind
4259       = InitializationKind::CreateDefault(Constructor->getLocation());
4260     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4261     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4262     break;
4263   }
4264 
4265   case IIK_Move:
4266   case IIK_Copy: {
4267     bool Moving = ImplicitInitKind == IIK_Move;
4268     ParmVarDecl *Param = Constructor->getParamDecl(0);
4269     QualType ParamType = Param->getType().getNonReferenceType();
4270 
4271     Expr *CopyCtorArg =
4272       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4273                           SourceLocation(), Param, false,
4274                           Constructor->getLocation(), ParamType,
4275                           VK_LValue, nullptr);
4276 
4277     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4278 
4279     // Cast to the base class to avoid ambiguities.
4280     QualType ArgTy =
4281       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4282                                        ParamType.getQualifiers());
4283 
4284     if (Moving) {
4285       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4286     }
4287 
4288     CXXCastPath BasePath;
4289     BasePath.push_back(BaseSpec);
4290     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4291                                             CK_UncheckedDerivedToBase,
4292                                             Moving ? VK_XValue : VK_LValue,
4293                                             &BasePath).get();
4294 
4295     InitializationKind InitKind
4296       = InitializationKind::CreateDirect(Constructor->getLocation(),
4297                                          SourceLocation(), SourceLocation());
4298     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4299     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4300     break;
4301   }
4302   }
4303 
4304   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4305   if (BaseInit.isInvalid())
4306     return true;
4307 
4308   CXXBaseInit =
4309     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4310                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4311                                                         SourceLocation()),
4312                                              BaseSpec->isVirtual(),
4313                                              SourceLocation(),
4314                                              BaseInit.getAs<Expr>(),
4315                                              SourceLocation(),
4316                                              SourceLocation());
4317 
4318   return false;
4319 }
4320 
4321 static bool RefersToRValueRef(Expr *MemRef) {
4322   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4323   return Referenced->getType()->isRValueReferenceType();
4324 }
4325 
4326 static bool
4327 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4328                                ImplicitInitializerKind ImplicitInitKind,
4329                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4330                                CXXCtorInitializer *&CXXMemberInit) {
4331   if (Field->isInvalidDecl())
4332     return true;
4333 
4334   SourceLocation Loc = Constructor->getLocation();
4335 
4336   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4337     bool Moving = ImplicitInitKind == IIK_Move;
4338     ParmVarDecl *Param = Constructor->getParamDecl(0);
4339     QualType ParamType = Param->getType().getNonReferenceType();
4340 
4341     // Suppress copying zero-width bitfields.
4342     if (Field->isZeroLengthBitField(SemaRef.Context))
4343       return false;
4344 
4345     Expr *MemberExprBase =
4346       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4347                           SourceLocation(), Param, false,
4348                           Loc, ParamType, VK_LValue, nullptr);
4349 
4350     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4351 
4352     if (Moving) {
4353       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4354     }
4355 
4356     // Build a reference to this field within the parameter.
4357     CXXScopeSpec SS;
4358     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4359                               Sema::LookupMemberName);
4360     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4361                                   : cast<ValueDecl>(Field), AS_public);
4362     MemberLookup.resolveKind();
4363     ExprResult CtorArg
4364       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4365                                          ParamType, Loc,
4366                                          /*IsArrow=*/false,
4367                                          SS,
4368                                          /*TemplateKWLoc=*/SourceLocation(),
4369                                          /*FirstQualifierInScope=*/nullptr,
4370                                          MemberLookup,
4371                                          /*TemplateArgs=*/nullptr,
4372                                          /*S*/nullptr);
4373     if (CtorArg.isInvalid())
4374       return true;
4375 
4376     // C++11 [class.copy]p15:
4377     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4378     //     with static_cast<T&&>(x.m);
4379     if (RefersToRValueRef(CtorArg.get())) {
4380       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4381     }
4382 
4383     InitializedEntity Entity =
4384         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4385                                                        /*Implicit*/ true)
4386                  : InitializedEntity::InitializeMember(Field, nullptr,
4387                                                        /*Implicit*/ true);
4388 
4389     // Direct-initialize to use the copy constructor.
4390     InitializationKind InitKind =
4391       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4392 
4393     Expr *CtorArgE = CtorArg.getAs<Expr>();
4394     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4395     ExprResult MemberInit =
4396         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4397     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4398     if (MemberInit.isInvalid())
4399       return true;
4400 
4401     if (Indirect)
4402       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4403           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4404     else
4405       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4406           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4407     return false;
4408   }
4409 
4410   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4411          "Unhandled implicit init kind!");
4412 
4413   QualType FieldBaseElementType =
4414     SemaRef.Context.getBaseElementType(Field->getType());
4415 
4416   if (FieldBaseElementType->isRecordType()) {
4417     InitializedEntity InitEntity =
4418         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4419                                                        /*Implicit*/ true)
4420                  : InitializedEntity::InitializeMember(Field, nullptr,
4421                                                        /*Implicit*/ true);
4422     InitializationKind InitKind =
4423       InitializationKind::CreateDefault(Loc);
4424 
4425     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4426     ExprResult MemberInit =
4427       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4428 
4429     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4430     if (MemberInit.isInvalid())
4431       return true;
4432 
4433     if (Indirect)
4434       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4435                                                                Indirect, Loc,
4436                                                                Loc,
4437                                                                MemberInit.get(),
4438                                                                Loc);
4439     else
4440       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4441                                                                Field, Loc, Loc,
4442                                                                MemberInit.get(),
4443                                                                Loc);
4444     return false;
4445   }
4446 
4447   if (!Field->getParent()->isUnion()) {
4448     if (FieldBaseElementType->isReferenceType()) {
4449       SemaRef.Diag(Constructor->getLocation(),
4450                    diag::err_uninitialized_member_in_ctor)
4451       << (int)Constructor->isImplicit()
4452       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4453       << 0 << Field->getDeclName();
4454       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4455       return true;
4456     }
4457 
4458     if (FieldBaseElementType.isConstQualified()) {
4459       SemaRef.Diag(Constructor->getLocation(),
4460                    diag::err_uninitialized_member_in_ctor)
4461       << (int)Constructor->isImplicit()
4462       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4463       << 1 << Field->getDeclName();
4464       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4465       return true;
4466     }
4467   }
4468 
4469   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4470     // ARC and Weak:
4471     //   Default-initialize Objective-C pointers to NULL.
4472     CXXMemberInit
4473       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4474                                                  Loc, Loc,
4475                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4476                                                  Loc);
4477     return false;
4478   }
4479 
4480   // Nothing to initialize.
4481   CXXMemberInit = nullptr;
4482   return false;
4483 }
4484 
4485 namespace {
4486 struct BaseAndFieldInfo {
4487   Sema &S;
4488   CXXConstructorDecl *Ctor;
4489   bool AnyErrorsInInits;
4490   ImplicitInitializerKind IIK;
4491   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4492   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4493   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4494 
4495   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4496     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4497     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4498     if (Ctor->getInheritedConstructor())
4499       IIK = IIK_Inherit;
4500     else if (Generated && Ctor->isCopyConstructor())
4501       IIK = IIK_Copy;
4502     else if (Generated && Ctor->isMoveConstructor())
4503       IIK = IIK_Move;
4504     else
4505       IIK = IIK_Default;
4506   }
4507 
4508   bool isImplicitCopyOrMove() const {
4509     switch (IIK) {
4510     case IIK_Copy:
4511     case IIK_Move:
4512       return true;
4513 
4514     case IIK_Default:
4515     case IIK_Inherit:
4516       return false;
4517     }
4518 
4519     llvm_unreachable("Invalid ImplicitInitializerKind!");
4520   }
4521 
4522   bool addFieldInitializer(CXXCtorInitializer *Init) {
4523     AllToInit.push_back(Init);
4524 
4525     // Check whether this initializer makes the field "used".
4526     if (Init->getInit()->HasSideEffects(S.Context))
4527       S.UnusedPrivateFields.remove(Init->getAnyMember());
4528 
4529     return false;
4530   }
4531 
4532   bool isInactiveUnionMember(FieldDecl *Field) {
4533     RecordDecl *Record = Field->getParent();
4534     if (!Record->isUnion())
4535       return false;
4536 
4537     if (FieldDecl *Active =
4538             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4539       return Active != Field->getCanonicalDecl();
4540 
4541     // In an implicit copy or move constructor, ignore any in-class initializer.
4542     if (isImplicitCopyOrMove())
4543       return true;
4544 
4545     // If there's no explicit initialization, the field is active only if it
4546     // has an in-class initializer...
4547     if (Field->hasInClassInitializer())
4548       return false;
4549     // ... or it's an anonymous struct or union whose class has an in-class
4550     // initializer.
4551     if (!Field->isAnonymousStructOrUnion())
4552       return true;
4553     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4554     return !FieldRD->hasInClassInitializer();
4555   }
4556 
4557   /// Determine whether the given field is, or is within, a union member
4558   /// that is inactive (because there was an initializer given for a different
4559   /// member of the union, or because the union was not initialized at all).
4560   bool isWithinInactiveUnionMember(FieldDecl *Field,
4561                                    IndirectFieldDecl *Indirect) {
4562     if (!Indirect)
4563       return isInactiveUnionMember(Field);
4564 
4565     for (auto *C : Indirect->chain()) {
4566       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4567       if (Field && isInactiveUnionMember(Field))
4568         return true;
4569     }
4570     return false;
4571   }
4572 };
4573 }
4574 
4575 /// Determine whether the given type is an incomplete or zero-lenfgth
4576 /// array type.
4577 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4578   if (T->isIncompleteArrayType())
4579     return true;
4580 
4581   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4582     if (!ArrayT->getSize())
4583       return true;
4584 
4585     T = ArrayT->getElementType();
4586   }
4587 
4588   return false;
4589 }
4590 
4591 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4592                                     FieldDecl *Field,
4593                                     IndirectFieldDecl *Indirect = nullptr) {
4594   if (Field->isInvalidDecl())
4595     return false;
4596 
4597   // Overwhelmingly common case: we have a direct initializer for this field.
4598   if (CXXCtorInitializer *Init =
4599           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4600     return Info.addFieldInitializer(Init);
4601 
4602   // C++11 [class.base.init]p8:
4603   //   if the entity is a non-static data member that has a
4604   //   brace-or-equal-initializer and either
4605   //   -- the constructor's class is a union and no other variant member of that
4606   //      union is designated by a mem-initializer-id or
4607   //   -- the constructor's class is not a union, and, if the entity is a member
4608   //      of an anonymous union, no other member of that union is designated by
4609   //      a mem-initializer-id,
4610   //   the entity is initialized as specified in [dcl.init].
4611   //
4612   // We also apply the same rules to handle anonymous structs within anonymous
4613   // unions.
4614   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4615     return false;
4616 
4617   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4618     ExprResult DIE =
4619         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4620     if (DIE.isInvalid())
4621       return true;
4622 
4623     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4624     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4625 
4626     CXXCtorInitializer *Init;
4627     if (Indirect)
4628       Init = new (SemaRef.Context)
4629           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4630                              SourceLocation(), DIE.get(), SourceLocation());
4631     else
4632       Init = new (SemaRef.Context)
4633           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4634                              SourceLocation(), DIE.get(), SourceLocation());
4635     return Info.addFieldInitializer(Init);
4636   }
4637 
4638   // Don't initialize incomplete or zero-length arrays.
4639   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4640     return false;
4641 
4642   // Don't try to build an implicit initializer if there were semantic
4643   // errors in any of the initializers (and therefore we might be
4644   // missing some that the user actually wrote).
4645   if (Info.AnyErrorsInInits)
4646     return false;
4647 
4648   CXXCtorInitializer *Init = nullptr;
4649   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4650                                      Indirect, Init))
4651     return true;
4652 
4653   if (!Init)
4654     return false;
4655 
4656   return Info.addFieldInitializer(Init);
4657 }
4658 
4659 bool
4660 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4661                                CXXCtorInitializer *Initializer) {
4662   assert(Initializer->isDelegatingInitializer());
4663   Constructor->setNumCtorInitializers(1);
4664   CXXCtorInitializer **initializer =
4665     new (Context) CXXCtorInitializer*[1];
4666   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4667   Constructor->setCtorInitializers(initializer);
4668 
4669   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4670     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4671     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4672   }
4673 
4674   DelegatingCtorDecls.push_back(Constructor);
4675 
4676   DiagnoseUninitializedFields(*this, Constructor);
4677 
4678   return false;
4679 }
4680 
4681 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4682                                ArrayRef<CXXCtorInitializer *> Initializers) {
4683   if (Constructor->isDependentContext()) {
4684     // Just store the initializers as written, they will be checked during
4685     // instantiation.
4686     if (!Initializers.empty()) {
4687       Constructor->setNumCtorInitializers(Initializers.size());
4688       CXXCtorInitializer **baseOrMemberInitializers =
4689         new (Context) CXXCtorInitializer*[Initializers.size()];
4690       memcpy(baseOrMemberInitializers, Initializers.data(),
4691              Initializers.size() * sizeof(CXXCtorInitializer*));
4692       Constructor->setCtorInitializers(baseOrMemberInitializers);
4693     }
4694 
4695     // Let template instantiation know whether we had errors.
4696     if (AnyErrors)
4697       Constructor->setInvalidDecl();
4698 
4699     return false;
4700   }
4701 
4702   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4703 
4704   // We need to build the initializer AST according to order of construction
4705   // and not what user specified in the Initializers list.
4706   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4707   if (!ClassDecl)
4708     return true;
4709 
4710   bool HadError = false;
4711 
4712   for (unsigned i = 0; i < Initializers.size(); i++) {
4713     CXXCtorInitializer *Member = Initializers[i];
4714 
4715     if (Member->isBaseInitializer())
4716       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4717     else {
4718       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4719 
4720       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4721         for (auto *C : F->chain()) {
4722           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4723           if (FD && FD->getParent()->isUnion())
4724             Info.ActiveUnionMember.insert(std::make_pair(
4725                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4726         }
4727       } else if (FieldDecl *FD = Member->getMember()) {
4728         if (FD->getParent()->isUnion())
4729           Info.ActiveUnionMember.insert(std::make_pair(
4730               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4731       }
4732     }
4733   }
4734 
4735   // Keep track of the direct virtual bases.
4736   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4737   for (auto &I : ClassDecl->bases()) {
4738     if (I.isVirtual())
4739       DirectVBases.insert(&I);
4740   }
4741 
4742   // Push virtual bases before others.
4743   for (auto &VBase : ClassDecl->vbases()) {
4744     if (CXXCtorInitializer *Value
4745         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4746       // [class.base.init]p7, per DR257:
4747       //   A mem-initializer where the mem-initializer-id names a virtual base
4748       //   class is ignored during execution of a constructor of any class that
4749       //   is not the most derived class.
4750       if (ClassDecl->isAbstract()) {
4751         // FIXME: Provide a fixit to remove the base specifier. This requires
4752         // tracking the location of the associated comma for a base specifier.
4753         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4754           << VBase.getType() << ClassDecl;
4755         DiagnoseAbstractType(ClassDecl);
4756       }
4757 
4758       Info.AllToInit.push_back(Value);
4759     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4760       // [class.base.init]p8, per DR257:
4761       //   If a given [...] base class is not named by a mem-initializer-id
4762       //   [...] and the entity is not a virtual base class of an abstract
4763       //   class, then [...] the entity is default-initialized.
4764       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4765       CXXCtorInitializer *CXXBaseInit;
4766       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4767                                        &VBase, IsInheritedVirtualBase,
4768                                        CXXBaseInit)) {
4769         HadError = true;
4770         continue;
4771       }
4772 
4773       Info.AllToInit.push_back(CXXBaseInit);
4774     }
4775   }
4776 
4777   // Non-virtual bases.
4778   for (auto &Base : ClassDecl->bases()) {
4779     // Virtuals are in the virtual base list and already constructed.
4780     if (Base.isVirtual())
4781       continue;
4782 
4783     if (CXXCtorInitializer *Value
4784           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4785       Info.AllToInit.push_back(Value);
4786     } else if (!AnyErrors) {
4787       CXXCtorInitializer *CXXBaseInit;
4788       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4789                                        &Base, /*IsInheritedVirtualBase=*/false,
4790                                        CXXBaseInit)) {
4791         HadError = true;
4792         continue;
4793       }
4794 
4795       Info.AllToInit.push_back(CXXBaseInit);
4796     }
4797   }
4798 
4799   // Fields.
4800   for (auto *Mem : ClassDecl->decls()) {
4801     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4802       // C++ [class.bit]p2:
4803       //   A declaration for a bit-field that omits the identifier declares an
4804       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4805       //   initialized.
4806       if (F->isUnnamedBitfield())
4807         continue;
4808 
4809       // If we're not generating the implicit copy/move constructor, then we'll
4810       // handle anonymous struct/union fields based on their individual
4811       // indirect fields.
4812       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4813         continue;
4814 
4815       if (CollectFieldInitializer(*this, Info, F))
4816         HadError = true;
4817       continue;
4818     }
4819 
4820     // Beyond this point, we only consider default initialization.
4821     if (Info.isImplicitCopyOrMove())
4822       continue;
4823 
4824     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4825       if (F->getType()->isIncompleteArrayType()) {
4826         assert(ClassDecl->hasFlexibleArrayMember() &&
4827                "Incomplete array type is not valid");
4828         continue;
4829       }
4830 
4831       // Initialize each field of an anonymous struct individually.
4832       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4833         HadError = true;
4834 
4835       continue;
4836     }
4837   }
4838 
4839   unsigned NumInitializers = Info.AllToInit.size();
4840   if (NumInitializers > 0) {
4841     Constructor->setNumCtorInitializers(NumInitializers);
4842     CXXCtorInitializer **baseOrMemberInitializers =
4843       new (Context) CXXCtorInitializer*[NumInitializers];
4844     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4845            NumInitializers * sizeof(CXXCtorInitializer*));
4846     Constructor->setCtorInitializers(baseOrMemberInitializers);
4847 
4848     // Constructors implicitly reference the base and member
4849     // destructors.
4850     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4851                                            Constructor->getParent());
4852   }
4853 
4854   return HadError;
4855 }
4856 
4857 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4858   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4859     const RecordDecl *RD = RT->getDecl();
4860     if (RD->isAnonymousStructOrUnion()) {
4861       for (auto *Field : RD->fields())
4862         PopulateKeysForFields(Field, IdealInits);
4863       return;
4864     }
4865   }
4866   IdealInits.push_back(Field->getCanonicalDecl());
4867 }
4868 
4869 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4870   return Context.getCanonicalType(BaseType).getTypePtr();
4871 }
4872 
4873 static const void *GetKeyForMember(ASTContext &Context,
4874                                    CXXCtorInitializer *Member) {
4875   if (!Member->isAnyMemberInitializer())
4876     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4877 
4878   return Member->getAnyMember()->getCanonicalDecl();
4879 }
4880 
4881 static void DiagnoseBaseOrMemInitializerOrder(
4882     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4883     ArrayRef<CXXCtorInitializer *> Inits) {
4884   if (Constructor->getDeclContext()->isDependentContext())
4885     return;
4886 
4887   // Don't check initializers order unless the warning is enabled at the
4888   // location of at least one initializer.
4889   bool ShouldCheckOrder = false;
4890   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4891     CXXCtorInitializer *Init = Inits[InitIndex];
4892     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4893                                  Init->getSourceLocation())) {
4894       ShouldCheckOrder = true;
4895       break;
4896     }
4897   }
4898   if (!ShouldCheckOrder)
4899     return;
4900 
4901   // Build the list of bases and members in the order that they'll
4902   // actually be initialized.  The explicit initializers should be in
4903   // this same order but may be missing things.
4904   SmallVector<const void*, 32> IdealInitKeys;
4905 
4906   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4907 
4908   // 1. Virtual bases.
4909   for (const auto &VBase : ClassDecl->vbases())
4910     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4911 
4912   // 2. Non-virtual bases.
4913   for (const auto &Base : ClassDecl->bases()) {
4914     if (Base.isVirtual())
4915       continue;
4916     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4917   }
4918 
4919   // 3. Direct fields.
4920   for (auto *Field : ClassDecl->fields()) {
4921     if (Field->isUnnamedBitfield())
4922       continue;
4923 
4924     PopulateKeysForFields(Field, IdealInitKeys);
4925   }
4926 
4927   unsigned NumIdealInits = IdealInitKeys.size();
4928   unsigned IdealIndex = 0;
4929 
4930   CXXCtorInitializer *PrevInit = nullptr;
4931   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4932     CXXCtorInitializer *Init = Inits[InitIndex];
4933     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4934 
4935     // Scan forward to try to find this initializer in the idealized
4936     // initializers list.
4937     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4938       if (InitKey == IdealInitKeys[IdealIndex])
4939         break;
4940 
4941     // If we didn't find this initializer, it must be because we
4942     // scanned past it on a previous iteration.  That can only
4943     // happen if we're out of order;  emit a warning.
4944     if (IdealIndex == NumIdealInits && PrevInit) {
4945       Sema::SemaDiagnosticBuilder D =
4946         SemaRef.Diag(PrevInit->getSourceLocation(),
4947                      diag::warn_initializer_out_of_order);
4948 
4949       if (PrevInit->isAnyMemberInitializer())
4950         D << 0 << PrevInit->getAnyMember()->getDeclName();
4951       else
4952         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4953 
4954       if (Init->isAnyMemberInitializer())
4955         D << 0 << Init->getAnyMember()->getDeclName();
4956       else
4957         D << 1 << Init->getTypeSourceInfo()->getType();
4958 
4959       // Move back to the initializer's location in the ideal list.
4960       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4961         if (InitKey == IdealInitKeys[IdealIndex])
4962           break;
4963 
4964       assert(IdealIndex < NumIdealInits &&
4965              "initializer not found in initializer list");
4966     }
4967 
4968     PrevInit = Init;
4969   }
4970 }
4971 
4972 namespace {
4973 bool CheckRedundantInit(Sema &S,
4974                         CXXCtorInitializer *Init,
4975                         CXXCtorInitializer *&PrevInit) {
4976   if (!PrevInit) {
4977     PrevInit = Init;
4978     return false;
4979   }
4980 
4981   if (FieldDecl *Field = Init->getAnyMember())
4982     S.Diag(Init->getSourceLocation(),
4983            diag::err_multiple_mem_initialization)
4984       << Field->getDeclName()
4985       << Init->getSourceRange();
4986   else {
4987     const Type *BaseClass = Init->getBaseClass();
4988     assert(BaseClass && "neither field nor base");
4989     S.Diag(Init->getSourceLocation(),
4990            diag::err_multiple_base_initialization)
4991       << QualType(BaseClass, 0)
4992       << Init->getSourceRange();
4993   }
4994   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4995     << 0 << PrevInit->getSourceRange();
4996 
4997   return true;
4998 }
4999 
5000 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5001 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5002 
5003 bool CheckRedundantUnionInit(Sema &S,
5004                              CXXCtorInitializer *Init,
5005                              RedundantUnionMap &Unions) {
5006   FieldDecl *Field = Init->getAnyMember();
5007   RecordDecl *Parent = Field->getParent();
5008   NamedDecl *Child = Field;
5009 
5010   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5011     if (Parent->isUnion()) {
5012       UnionEntry &En = Unions[Parent];
5013       if (En.first && En.first != Child) {
5014         S.Diag(Init->getSourceLocation(),
5015                diag::err_multiple_mem_union_initialization)
5016           << Field->getDeclName()
5017           << Init->getSourceRange();
5018         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5019           << 0 << En.second->getSourceRange();
5020         return true;
5021       }
5022       if (!En.first) {
5023         En.first = Child;
5024         En.second = Init;
5025       }
5026       if (!Parent->isAnonymousStructOrUnion())
5027         return false;
5028     }
5029 
5030     Child = Parent;
5031     Parent = cast<RecordDecl>(Parent->getDeclContext());
5032   }
5033 
5034   return false;
5035 }
5036 }
5037 
5038 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5039 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5040                                 SourceLocation ColonLoc,
5041                                 ArrayRef<CXXCtorInitializer*> MemInits,
5042                                 bool AnyErrors) {
5043   if (!ConstructorDecl)
5044     return;
5045 
5046   AdjustDeclIfTemplate(ConstructorDecl);
5047 
5048   CXXConstructorDecl *Constructor
5049     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5050 
5051   if (!Constructor) {
5052     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5053     return;
5054   }
5055 
5056   // Mapping for the duplicate initializers check.
5057   // For member initializers, this is keyed with a FieldDecl*.
5058   // For base initializers, this is keyed with a Type*.
5059   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5060 
5061   // Mapping for the inconsistent anonymous-union initializers check.
5062   RedundantUnionMap MemberUnions;
5063 
5064   bool HadError = false;
5065   for (unsigned i = 0; i < MemInits.size(); i++) {
5066     CXXCtorInitializer *Init = MemInits[i];
5067 
5068     // Set the source order index.
5069     Init->setSourceOrder(i);
5070 
5071     if (Init->isAnyMemberInitializer()) {
5072       const void *Key = GetKeyForMember(Context, Init);
5073       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5074           CheckRedundantUnionInit(*this, Init, MemberUnions))
5075         HadError = true;
5076     } else if (Init->isBaseInitializer()) {
5077       const void *Key = GetKeyForMember(Context, Init);
5078       if (CheckRedundantInit(*this, Init, Members[Key]))
5079         HadError = true;
5080     } else {
5081       assert(Init->isDelegatingInitializer());
5082       // This must be the only initializer
5083       if (MemInits.size() != 1) {
5084         Diag(Init->getSourceLocation(),
5085              diag::err_delegating_initializer_alone)
5086           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5087         // We will treat this as being the only initializer.
5088       }
5089       SetDelegatingInitializer(Constructor, MemInits[i]);
5090       // Return immediately as the initializer is set.
5091       return;
5092     }
5093   }
5094 
5095   if (HadError)
5096     return;
5097 
5098   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5099 
5100   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5101 
5102   DiagnoseUninitializedFields(*this, Constructor);
5103 }
5104 
5105 void
5106 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5107                                              CXXRecordDecl *ClassDecl) {
5108   // Ignore dependent contexts. Also ignore unions, since their members never
5109   // have destructors implicitly called.
5110   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5111     return;
5112 
5113   // FIXME: all the access-control diagnostics are positioned on the
5114   // field/base declaration.  That's probably good; that said, the
5115   // user might reasonably want to know why the destructor is being
5116   // emitted, and we currently don't say.
5117 
5118   // Non-static data members.
5119   for (auto *Field : ClassDecl->fields()) {
5120     if (Field->isInvalidDecl())
5121       continue;
5122 
5123     // Don't destroy incomplete or zero-length arrays.
5124     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5125       continue;
5126 
5127     QualType FieldType = Context.getBaseElementType(Field->getType());
5128 
5129     const RecordType* RT = FieldType->getAs<RecordType>();
5130     if (!RT)
5131       continue;
5132 
5133     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5134     if (FieldClassDecl->isInvalidDecl())
5135       continue;
5136     if (FieldClassDecl->hasIrrelevantDestructor())
5137       continue;
5138     // The destructor for an implicit anonymous union member is never invoked.
5139     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5140       continue;
5141 
5142     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5143     assert(Dtor && "No dtor found for FieldClassDecl!");
5144     CheckDestructorAccess(Field->getLocation(), Dtor,
5145                           PDiag(diag::err_access_dtor_field)
5146                             << Field->getDeclName()
5147                             << FieldType);
5148 
5149     MarkFunctionReferenced(Location, Dtor);
5150     DiagnoseUseOfDecl(Dtor, Location);
5151   }
5152 
5153   // We only potentially invoke the destructors of potentially constructed
5154   // subobjects.
5155   bool VisitVirtualBases = !ClassDecl->isAbstract();
5156 
5157   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5158 
5159   // Bases.
5160   for (const auto &Base : ClassDecl->bases()) {
5161     // Bases are always records in a well-formed non-dependent class.
5162     const RecordType *RT = Base.getType()->getAs<RecordType>();
5163 
5164     // Remember direct virtual bases.
5165     if (Base.isVirtual()) {
5166       if (!VisitVirtualBases)
5167         continue;
5168       DirectVirtualBases.insert(RT);
5169     }
5170 
5171     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5172     // If our base class is invalid, we probably can't get its dtor anyway.
5173     if (BaseClassDecl->isInvalidDecl())
5174       continue;
5175     if (BaseClassDecl->hasIrrelevantDestructor())
5176       continue;
5177 
5178     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5179     assert(Dtor && "No dtor found for BaseClassDecl!");
5180 
5181     // FIXME: caret should be on the start of the class name
5182     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5183                           PDiag(diag::err_access_dtor_base)
5184                               << Base.getType() << Base.getSourceRange(),
5185                           Context.getTypeDeclType(ClassDecl));
5186 
5187     MarkFunctionReferenced(Location, Dtor);
5188     DiagnoseUseOfDecl(Dtor, Location);
5189   }
5190 
5191   if (!VisitVirtualBases)
5192     return;
5193 
5194   // Virtual bases.
5195   for (const auto &VBase : ClassDecl->vbases()) {
5196     // Bases are always records in a well-formed non-dependent class.
5197     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5198 
5199     // Ignore direct virtual bases.
5200     if (DirectVirtualBases.count(RT))
5201       continue;
5202 
5203     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5204     // If our base class is invalid, we probably can't get its dtor anyway.
5205     if (BaseClassDecl->isInvalidDecl())
5206       continue;
5207     if (BaseClassDecl->hasIrrelevantDestructor())
5208       continue;
5209 
5210     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5211     assert(Dtor && "No dtor found for BaseClassDecl!");
5212     if (CheckDestructorAccess(
5213             ClassDecl->getLocation(), Dtor,
5214             PDiag(diag::err_access_dtor_vbase)
5215                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5216             Context.getTypeDeclType(ClassDecl)) ==
5217         AR_accessible) {
5218       CheckDerivedToBaseConversion(
5219           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5220           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5221           SourceRange(), DeclarationName(), nullptr);
5222     }
5223 
5224     MarkFunctionReferenced(Location, Dtor);
5225     DiagnoseUseOfDecl(Dtor, Location);
5226   }
5227 }
5228 
5229 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5230   if (!CDtorDecl)
5231     return;
5232 
5233   if (CXXConstructorDecl *Constructor
5234       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5235     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5236     DiagnoseUninitializedFields(*this, Constructor);
5237   }
5238 }
5239 
5240 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5241   if (!getLangOpts().CPlusPlus)
5242     return false;
5243 
5244   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5245   if (!RD)
5246     return false;
5247 
5248   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5249   // class template specialization here, but doing so breaks a lot of code.
5250 
5251   // We can't answer whether something is abstract until it has a
5252   // definition. If it's currently being defined, we'll walk back
5253   // over all the declarations when we have a full definition.
5254   const CXXRecordDecl *Def = RD->getDefinition();
5255   if (!Def || Def->isBeingDefined())
5256     return false;
5257 
5258   return RD->isAbstract();
5259 }
5260 
5261 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5262                                   TypeDiagnoser &Diagnoser) {
5263   if (!isAbstractType(Loc, T))
5264     return false;
5265 
5266   T = Context.getBaseElementType(T);
5267   Diagnoser.diagnose(*this, Loc, T);
5268   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5269   return true;
5270 }
5271 
5272 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5273   // Check if we've already emitted the list of pure virtual functions
5274   // for this class.
5275   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5276     return;
5277 
5278   // If the diagnostic is suppressed, don't emit the notes. We're only
5279   // going to emit them once, so try to attach them to a diagnostic we're
5280   // actually going to show.
5281   if (Diags.isLastDiagnosticIgnored())
5282     return;
5283 
5284   CXXFinalOverriderMap FinalOverriders;
5285   RD->getFinalOverriders(FinalOverriders);
5286 
5287   // Keep a set of seen pure methods so we won't diagnose the same method
5288   // more than once.
5289   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5290 
5291   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5292                                    MEnd = FinalOverriders.end();
5293        M != MEnd;
5294        ++M) {
5295     for (OverridingMethods::iterator SO = M->second.begin(),
5296                                   SOEnd = M->second.end();
5297          SO != SOEnd; ++SO) {
5298       // C++ [class.abstract]p4:
5299       //   A class is abstract if it contains or inherits at least one
5300       //   pure virtual function for which the final overrider is pure
5301       //   virtual.
5302 
5303       //
5304       if (SO->second.size() != 1)
5305         continue;
5306 
5307       if (!SO->second.front().Method->isPure())
5308         continue;
5309 
5310       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5311         continue;
5312 
5313       Diag(SO->second.front().Method->getLocation(),
5314            diag::note_pure_virtual_function)
5315         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5316     }
5317   }
5318 
5319   if (!PureVirtualClassDiagSet)
5320     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5321   PureVirtualClassDiagSet->insert(RD);
5322 }
5323 
5324 namespace {
5325 struct AbstractUsageInfo {
5326   Sema &S;
5327   CXXRecordDecl *Record;
5328   CanQualType AbstractType;
5329   bool Invalid;
5330 
5331   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5332     : S(S), Record(Record),
5333       AbstractType(S.Context.getCanonicalType(
5334                    S.Context.getTypeDeclType(Record))),
5335       Invalid(false) {}
5336 
5337   void DiagnoseAbstractType() {
5338     if (Invalid) return;
5339     S.DiagnoseAbstractType(Record);
5340     Invalid = true;
5341   }
5342 
5343   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5344 };
5345 
5346 struct CheckAbstractUsage {
5347   AbstractUsageInfo &Info;
5348   const NamedDecl *Ctx;
5349 
5350   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5351     : Info(Info), Ctx(Ctx) {}
5352 
5353   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5354     switch (TL.getTypeLocClass()) {
5355 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5356 #define TYPELOC(CLASS, PARENT) \
5357     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5358 #include "clang/AST/TypeLocNodes.def"
5359     }
5360   }
5361 
5362   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5363     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5364     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5365       if (!TL.getParam(I))
5366         continue;
5367 
5368       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5369       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5370     }
5371   }
5372 
5373   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5374     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5375   }
5376 
5377   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5378     // Visit the type parameters from a permissive context.
5379     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5380       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5381       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5382         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5383           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5384       // TODO: other template argument types?
5385     }
5386   }
5387 
5388   // Visit pointee types from a permissive context.
5389 #define CheckPolymorphic(Type) \
5390   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5391     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5392   }
5393   CheckPolymorphic(PointerTypeLoc)
5394   CheckPolymorphic(ReferenceTypeLoc)
5395   CheckPolymorphic(MemberPointerTypeLoc)
5396   CheckPolymorphic(BlockPointerTypeLoc)
5397   CheckPolymorphic(AtomicTypeLoc)
5398 
5399   /// Handle all the types we haven't given a more specific
5400   /// implementation for above.
5401   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5402     // Every other kind of type that we haven't called out already
5403     // that has an inner type is either (1) sugar or (2) contains that
5404     // inner type in some way as a subobject.
5405     if (TypeLoc Next = TL.getNextTypeLoc())
5406       return Visit(Next, Sel);
5407 
5408     // If there's no inner type and we're in a permissive context,
5409     // don't diagnose.
5410     if (Sel == Sema::AbstractNone) return;
5411 
5412     // Check whether the type matches the abstract type.
5413     QualType T = TL.getType();
5414     if (T->isArrayType()) {
5415       Sel = Sema::AbstractArrayType;
5416       T = Info.S.Context.getBaseElementType(T);
5417     }
5418     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5419     if (CT != Info.AbstractType) return;
5420 
5421     // It matched; do some magic.
5422     if (Sel == Sema::AbstractArrayType) {
5423       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5424         << T << TL.getSourceRange();
5425     } else {
5426       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5427         << Sel << T << TL.getSourceRange();
5428     }
5429     Info.DiagnoseAbstractType();
5430   }
5431 };
5432 
5433 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5434                                   Sema::AbstractDiagSelID Sel) {
5435   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5436 }
5437 
5438 }
5439 
5440 /// Check for invalid uses of an abstract type in a method declaration.
5441 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5442                                     CXXMethodDecl *MD) {
5443   // No need to do the check on definitions, which require that
5444   // the return/param types be complete.
5445   if (MD->doesThisDeclarationHaveABody())
5446     return;
5447 
5448   // For safety's sake, just ignore it if we don't have type source
5449   // information.  This should never happen for non-implicit methods,
5450   // but...
5451   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5452     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5453 }
5454 
5455 /// Check for invalid uses of an abstract type within a class definition.
5456 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5457                                     CXXRecordDecl *RD) {
5458   for (auto *D : RD->decls()) {
5459     if (D->isImplicit()) continue;
5460 
5461     // Methods and method templates.
5462     if (isa<CXXMethodDecl>(D)) {
5463       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5464     } else if (isa<FunctionTemplateDecl>(D)) {
5465       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5466       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5467 
5468     // Fields and static variables.
5469     } else if (isa<FieldDecl>(D)) {
5470       FieldDecl *FD = cast<FieldDecl>(D);
5471       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5472         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5473     } else if (isa<VarDecl>(D)) {
5474       VarDecl *VD = cast<VarDecl>(D);
5475       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5476         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5477 
5478     // Nested classes and class templates.
5479     } else if (isa<CXXRecordDecl>(D)) {
5480       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5481     } else if (isa<ClassTemplateDecl>(D)) {
5482       CheckAbstractClassUsage(Info,
5483                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5484     }
5485   }
5486 }
5487 
5488 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5489   Attr *ClassAttr = getDLLAttr(Class);
5490   if (!ClassAttr)
5491     return;
5492 
5493   assert(ClassAttr->getKind() == attr::DLLExport);
5494 
5495   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5496 
5497   if (TSK == TSK_ExplicitInstantiationDeclaration)
5498     // Don't go any further if this is just an explicit instantiation
5499     // declaration.
5500     return;
5501 
5502   for (Decl *Member : Class->decls()) {
5503     // Defined static variables that are members of an exported base
5504     // class must be marked export too.
5505     auto *VD = dyn_cast<VarDecl>(Member);
5506     if (VD && Member->getAttr<DLLExportAttr>() &&
5507         VD->getStorageClass() == SC_Static &&
5508         TSK == TSK_ImplicitInstantiation)
5509       S.MarkVariableReferenced(VD->getLocation(), VD);
5510 
5511     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5512     if (!MD)
5513       continue;
5514 
5515     if (Member->getAttr<DLLExportAttr>()) {
5516       if (MD->isUserProvided()) {
5517         // Instantiate non-default class member functions ...
5518 
5519         // .. except for certain kinds of template specializations.
5520         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5521           continue;
5522 
5523         S.MarkFunctionReferenced(Class->getLocation(), MD);
5524 
5525         // The function will be passed to the consumer when its definition is
5526         // encountered.
5527       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5528                  MD->isCopyAssignmentOperator() ||
5529                  MD->isMoveAssignmentOperator()) {
5530         // Synthesize and instantiate non-trivial implicit methods, explicitly
5531         // defaulted methods, and the copy and move assignment operators. The
5532         // latter are exported even if they are trivial, because the address of
5533         // an operator can be taken and should compare equal across libraries.
5534         DiagnosticErrorTrap Trap(S.Diags);
5535         S.MarkFunctionReferenced(Class->getLocation(), MD);
5536         if (Trap.hasErrorOccurred()) {
5537           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5538               << Class << !S.getLangOpts().CPlusPlus11;
5539           break;
5540         }
5541 
5542         // There is no later point when we will see the definition of this
5543         // function, so pass it to the consumer now.
5544         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5545       }
5546     }
5547   }
5548 }
5549 
5550 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5551                                                         CXXRecordDecl *Class) {
5552   // Only the MS ABI has default constructor closures, so we don't need to do
5553   // this semantic checking anywhere else.
5554   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5555     return;
5556 
5557   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5558   for (Decl *Member : Class->decls()) {
5559     // Look for exported default constructors.
5560     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5561     if (!CD || !CD->isDefaultConstructor())
5562       continue;
5563     auto *Attr = CD->getAttr<DLLExportAttr>();
5564     if (!Attr)
5565       continue;
5566 
5567     // If the class is non-dependent, mark the default arguments as ODR-used so
5568     // that we can properly codegen the constructor closure.
5569     if (!Class->isDependentContext()) {
5570       for (ParmVarDecl *PD : CD->parameters()) {
5571         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5572         S.DiscardCleanupsInEvaluationContext();
5573       }
5574     }
5575 
5576     if (LastExportedDefaultCtor) {
5577       S.Diag(LastExportedDefaultCtor->getLocation(),
5578              diag::err_attribute_dll_ambiguous_default_ctor)
5579           << Class;
5580       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5581           << CD->getDeclName();
5582       return;
5583     }
5584     LastExportedDefaultCtor = CD;
5585   }
5586 }
5587 
5588 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5589   // Mark any compiler-generated routines with the implicit code_seg attribute.
5590   for (auto *Method : Class->methods()) {
5591     if (Method->isUserProvided())
5592       continue;
5593     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5594       Method->addAttr(A);
5595   }
5596 }
5597 
5598 /// Check class-level dllimport/dllexport attribute.
5599 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5600   Attr *ClassAttr = getDLLAttr(Class);
5601 
5602   // MSVC inherits DLL attributes to partial class template specializations.
5603   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5604     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5605       if (Attr *TemplateAttr =
5606               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5607         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5608         A->setInherited(true);
5609         ClassAttr = A;
5610       }
5611     }
5612   }
5613 
5614   if (!ClassAttr)
5615     return;
5616 
5617   if (!Class->isExternallyVisible()) {
5618     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5619         << Class << ClassAttr;
5620     return;
5621   }
5622 
5623   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5624       !ClassAttr->isInherited()) {
5625     // Diagnose dll attributes on members of class with dll attribute.
5626     for (Decl *Member : Class->decls()) {
5627       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5628         continue;
5629       InheritableAttr *MemberAttr = getDLLAttr(Member);
5630       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5631         continue;
5632 
5633       Diag(MemberAttr->getLocation(),
5634              diag::err_attribute_dll_member_of_dll_class)
5635           << MemberAttr << ClassAttr;
5636       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5637       Member->setInvalidDecl();
5638     }
5639   }
5640 
5641   if (Class->getDescribedClassTemplate())
5642     // Don't inherit dll attribute until the template is instantiated.
5643     return;
5644 
5645   // The class is either imported or exported.
5646   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5647 
5648   // Check if this was a dllimport attribute propagated from a derived class to
5649   // a base class template specialization. We don't apply these attributes to
5650   // static data members.
5651   const bool PropagatedImport =
5652       !ClassExported &&
5653       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5654 
5655   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5656 
5657   // Ignore explicit dllexport on explicit class template instantiation declarations.
5658   if (ClassExported && !ClassAttr->isInherited() &&
5659       TSK == TSK_ExplicitInstantiationDeclaration) {
5660     Class->dropAttr<DLLExportAttr>();
5661     return;
5662   }
5663 
5664   // Force declaration of implicit members so they can inherit the attribute.
5665   ForceDeclarationOfImplicitMembers(Class);
5666 
5667   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5668   // seem to be true in practice?
5669 
5670   for (Decl *Member : Class->decls()) {
5671     VarDecl *VD = dyn_cast<VarDecl>(Member);
5672     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5673 
5674     // Only methods and static fields inherit the attributes.
5675     if (!VD && !MD)
5676       continue;
5677 
5678     if (MD) {
5679       // Don't process deleted methods.
5680       if (MD->isDeleted())
5681         continue;
5682 
5683       if (MD->isInlined()) {
5684         // MinGW does not import or export inline methods.
5685         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5686             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5687           continue;
5688 
5689         // MSVC versions before 2015 don't export the move assignment operators
5690         // and move constructor, so don't attempt to import/export them if
5691         // we have a definition.
5692         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5693         if ((MD->isMoveAssignmentOperator() ||
5694              (Ctor && Ctor->isMoveConstructor())) &&
5695             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5696           continue;
5697 
5698         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5699         // operator is exported anyway.
5700         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5701             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5702           continue;
5703       }
5704     }
5705 
5706     // Don't apply dllimport attributes to static data members of class template
5707     // instantiations when the attribute is propagated from a derived class.
5708     if (VD && PropagatedImport)
5709       continue;
5710 
5711     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5712       continue;
5713 
5714     if (!getDLLAttr(Member)) {
5715       auto *NewAttr =
5716           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5717       NewAttr->setInherited(true);
5718       Member->addAttr(NewAttr);
5719 
5720       if (MD) {
5721         // Propagate DLLAttr to friend re-declarations of MD that have already
5722         // been constructed.
5723         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5724              FD = FD->getPreviousDecl()) {
5725           if (FD->getFriendObjectKind() == Decl::FOK_None)
5726             continue;
5727           assert(!getDLLAttr(FD) &&
5728                  "friend re-decl should not already have a DLLAttr");
5729           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5730           NewAttr->setInherited(true);
5731           FD->addAttr(NewAttr);
5732         }
5733       }
5734     }
5735   }
5736 
5737   if (ClassExported)
5738     DelayedDllExportClasses.push_back(Class);
5739 }
5740 
5741 /// Perform propagation of DLL attributes from a derived class to a
5742 /// templated base class for MS compatibility.
5743 void Sema::propagateDLLAttrToBaseClassTemplate(
5744     CXXRecordDecl *Class, Attr *ClassAttr,
5745     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5746   if (getDLLAttr(
5747           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5748     // If the base class template has a DLL attribute, don't try to change it.
5749     return;
5750   }
5751 
5752   auto TSK = BaseTemplateSpec->getSpecializationKind();
5753   if (!getDLLAttr(BaseTemplateSpec) &&
5754       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5755        TSK == TSK_ImplicitInstantiation)) {
5756     // The template hasn't been instantiated yet (or it has, but only as an
5757     // explicit instantiation declaration or implicit instantiation, which means
5758     // we haven't codegenned any members yet), so propagate the attribute.
5759     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5760     NewAttr->setInherited(true);
5761     BaseTemplateSpec->addAttr(NewAttr);
5762 
5763     // If this was an import, mark that we propagated it from a derived class to
5764     // a base class template specialization.
5765     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5766       ImportAttr->setPropagatedToBaseTemplate();
5767 
5768     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5769     // needs to be run again to work see the new attribute. Otherwise this will
5770     // get run whenever the template is instantiated.
5771     if (TSK != TSK_Undeclared)
5772       checkClassLevelDLLAttribute(BaseTemplateSpec);
5773 
5774     return;
5775   }
5776 
5777   if (getDLLAttr(BaseTemplateSpec)) {
5778     // The template has already been specialized or instantiated with an
5779     // attribute, explicitly or through propagation. We should not try to change
5780     // it.
5781     return;
5782   }
5783 
5784   // The template was previously instantiated or explicitly specialized without
5785   // a dll attribute, It's too late for us to add an attribute, so warn that
5786   // this is unsupported.
5787   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5788       << BaseTemplateSpec->isExplicitSpecialization();
5789   Diag(ClassAttr->getLocation(), diag::note_attribute);
5790   if (BaseTemplateSpec->isExplicitSpecialization()) {
5791     Diag(BaseTemplateSpec->getLocation(),
5792            diag::note_template_class_explicit_specialization_was_here)
5793         << BaseTemplateSpec;
5794   } else {
5795     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5796            diag::note_template_class_instantiation_was_here)
5797         << BaseTemplateSpec;
5798   }
5799 }
5800 
5801 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5802                                         SourceLocation DefaultLoc) {
5803   switch (S.getSpecialMember(MD)) {
5804   case Sema::CXXDefaultConstructor:
5805     S.DefineImplicitDefaultConstructor(DefaultLoc,
5806                                        cast<CXXConstructorDecl>(MD));
5807     break;
5808   case Sema::CXXCopyConstructor:
5809     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5810     break;
5811   case Sema::CXXCopyAssignment:
5812     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5813     break;
5814   case Sema::CXXDestructor:
5815     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5816     break;
5817   case Sema::CXXMoveConstructor:
5818     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5819     break;
5820   case Sema::CXXMoveAssignment:
5821     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5822     break;
5823   case Sema::CXXInvalid:
5824     llvm_unreachable("Invalid special member.");
5825   }
5826 }
5827 
5828 /// Determine whether a type is permitted to be passed or returned in
5829 /// registers, per C++ [class.temporary]p3.
5830 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5831                                TargetInfo::CallingConvKind CCK) {
5832   if (D->isDependentType() || D->isInvalidDecl())
5833     return false;
5834 
5835   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5836   // The PS4 platform ABI follows the behavior of Clang 3.2.
5837   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5838     return !D->hasNonTrivialDestructorForCall() &&
5839            !D->hasNonTrivialCopyConstructorForCall();
5840 
5841   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5842     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5843     bool DtorIsTrivialForCall = false;
5844 
5845     // If a class has at least one non-deleted, trivial copy constructor, it
5846     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5847     //
5848     // Note: This permits classes with non-trivial copy or move ctors to be
5849     // passed in registers, so long as they *also* have a trivial copy ctor,
5850     // which is non-conforming.
5851     if (D->needsImplicitCopyConstructor()) {
5852       if (!D->defaultedCopyConstructorIsDeleted()) {
5853         if (D->hasTrivialCopyConstructor())
5854           CopyCtorIsTrivial = true;
5855         if (D->hasTrivialCopyConstructorForCall())
5856           CopyCtorIsTrivialForCall = true;
5857       }
5858     } else {
5859       for (const CXXConstructorDecl *CD : D->ctors()) {
5860         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5861           if (CD->isTrivial())
5862             CopyCtorIsTrivial = true;
5863           if (CD->isTrivialForCall())
5864             CopyCtorIsTrivialForCall = true;
5865         }
5866       }
5867     }
5868 
5869     if (D->needsImplicitDestructor()) {
5870       if (!D->defaultedDestructorIsDeleted() &&
5871           D->hasTrivialDestructorForCall())
5872         DtorIsTrivialForCall = true;
5873     } else if (const auto *DD = D->getDestructor()) {
5874       if (!DD->isDeleted() && DD->isTrivialForCall())
5875         DtorIsTrivialForCall = true;
5876     }
5877 
5878     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5879     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5880       return true;
5881 
5882     // If a class has a destructor, we'd really like to pass it indirectly
5883     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5884     // impossible for small types, which it will pass in a single register or
5885     // stack slot. Most objects with dtors are large-ish, so handle that early.
5886     // We can't call out all large objects as being indirect because there are
5887     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5888     // how we pass large POD types.
5889 
5890     // Note: This permits small classes with nontrivial destructors to be
5891     // passed in registers, which is non-conforming.
5892     if (CopyCtorIsTrivial &&
5893         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5894       return true;
5895     return false;
5896   }
5897 
5898   // Per C++ [class.temporary]p3, the relevant condition is:
5899   //   each copy constructor, move constructor, and destructor of X is
5900   //   either trivial or deleted, and X has at least one non-deleted copy
5901   //   or move constructor
5902   bool HasNonDeletedCopyOrMove = false;
5903 
5904   if (D->needsImplicitCopyConstructor() &&
5905       !D->defaultedCopyConstructorIsDeleted()) {
5906     if (!D->hasTrivialCopyConstructorForCall())
5907       return false;
5908     HasNonDeletedCopyOrMove = true;
5909   }
5910 
5911   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5912       !D->defaultedMoveConstructorIsDeleted()) {
5913     if (!D->hasTrivialMoveConstructorForCall())
5914       return false;
5915     HasNonDeletedCopyOrMove = true;
5916   }
5917 
5918   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5919       !D->hasTrivialDestructorForCall())
5920     return false;
5921 
5922   for (const CXXMethodDecl *MD : D->methods()) {
5923     if (MD->isDeleted())
5924       continue;
5925 
5926     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5927     if (CD && CD->isCopyOrMoveConstructor())
5928       HasNonDeletedCopyOrMove = true;
5929     else if (!isa<CXXDestructorDecl>(MD))
5930       continue;
5931 
5932     if (!MD->isTrivialForCall())
5933       return false;
5934   }
5935 
5936   return HasNonDeletedCopyOrMove;
5937 }
5938 
5939 /// Perform semantic checks on a class definition that has been
5940 /// completing, introducing implicitly-declared members, checking for
5941 /// abstract types, etc.
5942 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5943   if (!Record)
5944     return;
5945 
5946   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5947     AbstractUsageInfo Info(*this, Record);
5948     CheckAbstractClassUsage(Info, Record);
5949   }
5950 
5951   // If this is not an aggregate type and has no user-declared constructor,
5952   // complain about any non-static data members of reference or const scalar
5953   // type, since they will never get initializers.
5954   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5955       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5956       !Record->isLambda()) {
5957     bool Complained = false;
5958     for (const auto *F : Record->fields()) {
5959       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5960         continue;
5961 
5962       if (F->getType()->isReferenceType() ||
5963           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5964         if (!Complained) {
5965           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5966             << Record->getTagKind() << Record;
5967           Complained = true;
5968         }
5969 
5970         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5971           << F->getType()->isReferenceType()
5972           << F->getDeclName();
5973       }
5974     }
5975   }
5976 
5977   if (Record->getIdentifier()) {
5978     // C++ [class.mem]p13:
5979     //   If T is the name of a class, then each of the following shall have a
5980     //   name different from T:
5981     //     - every member of every anonymous union that is a member of class T.
5982     //
5983     // C++ [class.mem]p14:
5984     //   In addition, if class T has a user-declared constructor (12.1), every
5985     //   non-static data member of class T shall have a name different from T.
5986     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5987     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5988          ++I) {
5989       NamedDecl *D = (*I)->getUnderlyingDecl();
5990       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
5991            Record->hasUserDeclaredConstructor()) ||
5992           isa<IndirectFieldDecl>(D)) {
5993         Diag((*I)->getLocation(), diag::err_member_name_of_class)
5994           << D->getDeclName();
5995         break;
5996       }
5997     }
5998   }
5999 
6000   // Warn if the class has virtual methods but non-virtual public destructor.
6001   if (Record->isPolymorphic() && !Record->isDependentType()) {
6002     CXXDestructorDecl *dtor = Record->getDestructor();
6003     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6004         !Record->hasAttr<FinalAttr>())
6005       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6006            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6007   }
6008 
6009   if (Record->isAbstract()) {
6010     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6011       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6012         << FA->isSpelledAsSealed();
6013       DiagnoseAbstractType(Record);
6014     }
6015   }
6016 
6017   // See if trivial_abi has to be dropped.
6018   if (Record->hasAttr<TrivialABIAttr>())
6019     checkIllFormedTrivialABIStruct(*Record);
6020 
6021   // Set HasTrivialSpecialMemberForCall if the record has attribute
6022   // "trivial_abi".
6023   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6024 
6025   if (HasTrivialABI)
6026     Record->setHasTrivialSpecialMemberForCall();
6027 
6028   bool HasMethodWithOverrideControl = false,
6029        HasOverridingMethodWithoutOverrideControl = false;
6030   if (!Record->isDependentType()) {
6031     for (auto *M : Record->methods()) {
6032       // See if a method overloads virtual methods in a base
6033       // class without overriding any.
6034       if (!M->isStatic())
6035         DiagnoseHiddenVirtualMethods(M);
6036       if (M->hasAttr<OverrideAttr>())
6037         HasMethodWithOverrideControl = true;
6038       else if (M->size_overridden_methods() > 0)
6039         HasOverridingMethodWithoutOverrideControl = true;
6040       // Check whether the explicitly-defaulted special members are valid.
6041       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6042         CheckExplicitlyDefaultedSpecialMember(M);
6043 
6044       // For an explicitly defaulted or deleted special member, we defer
6045       // determining triviality until the class is complete. That time is now!
6046       CXXSpecialMember CSM = getSpecialMember(M);
6047       if (!M->isImplicit() && !M->isUserProvided()) {
6048         if (CSM != CXXInvalid) {
6049           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6050           // Inform the class that we've finished declaring this member.
6051           Record->finishedDefaultedOrDeletedMember(M);
6052           M->setTrivialForCall(
6053               HasTrivialABI ||
6054               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6055           Record->setTrivialForCallFlags(M);
6056         }
6057       }
6058 
6059       // Set triviality for the purpose of calls if this is a user-provided
6060       // copy/move constructor or destructor.
6061       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6062            CSM == CXXDestructor) && M->isUserProvided()) {
6063         M->setTrivialForCall(HasTrivialABI);
6064         Record->setTrivialForCallFlags(M);
6065       }
6066 
6067       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6068           M->hasAttr<DLLExportAttr>()) {
6069         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6070             M->isTrivial() &&
6071             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6072              CSM == CXXDestructor))
6073           M->dropAttr<DLLExportAttr>();
6074 
6075         if (M->hasAttr<DLLExportAttr>()) {
6076           DefineImplicitSpecialMember(*this, M, M->getLocation());
6077           ActOnFinishInlineFunctionDef(M);
6078         }
6079       }
6080     }
6081   }
6082 
6083   if (HasMethodWithOverrideControl &&
6084       HasOverridingMethodWithoutOverrideControl) {
6085     // At least one method has the 'override' control declared.
6086     // Diagnose all other overridden methods which do not have 'override' specified on them.
6087     for (auto *M : Record->methods())
6088       DiagnoseAbsenceOfOverrideControl(M);
6089   }
6090 
6091   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6092   // whether this class uses any C++ features that are implemented
6093   // completely differently in MSVC, and if so, emit a diagnostic.
6094   // That diagnostic defaults to an error, but we allow projects to
6095   // map it down to a warning (or ignore it).  It's a fairly common
6096   // practice among users of the ms_struct pragma to mass-annotate
6097   // headers, sweeping up a bunch of types that the project doesn't
6098   // really rely on MSVC-compatible layout for.  We must therefore
6099   // support "ms_struct except for C++ stuff" as a secondary ABI.
6100   if (Record->isMsStruct(Context) &&
6101       (Record->isPolymorphic() || Record->getNumBases())) {
6102     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6103   }
6104 
6105   checkClassLevelDLLAttribute(Record);
6106   checkClassLevelCodeSegAttribute(Record);
6107 
6108   bool ClangABICompat4 =
6109       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6110   TargetInfo::CallingConvKind CCK =
6111       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6112   bool CanPass = canPassInRegisters(*this, Record, CCK);
6113 
6114   // Do not change ArgPassingRestrictions if it has already been set to
6115   // APK_CanNeverPassInRegs.
6116   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6117     Record->setArgPassingRestrictions(CanPass
6118                                           ? RecordDecl::APK_CanPassInRegs
6119                                           : RecordDecl::APK_CannotPassInRegs);
6120 
6121   // If canPassInRegisters returns true despite the record having a non-trivial
6122   // destructor, the record is destructed in the callee. This happens only when
6123   // the record or one of its subobjects has a field annotated with trivial_abi
6124   // or a field qualified with ObjC __strong/__weak.
6125   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6126     Record->setParamDestroyedInCallee(true);
6127   else if (Record->hasNonTrivialDestructor())
6128     Record->setParamDestroyedInCallee(CanPass);
6129 
6130   if (getLangOpts().ForceEmitVTables) {
6131     // If we want to emit all the vtables, we need to mark it as used.  This
6132     // is especially required for cases like vtable assumption loads.
6133     MarkVTableUsed(Record->getInnerLocStart(), Record);
6134   }
6135 }
6136 
6137 /// Look up the special member function that would be called by a special
6138 /// member function for a subobject of class type.
6139 ///
6140 /// \param Class The class type of the subobject.
6141 /// \param CSM The kind of special member function.
6142 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6143 /// \param ConstRHS True if this is a copy operation with a const object
6144 ///        on its RHS, that is, if the argument to the outer special member
6145 ///        function is 'const' and this is not a field marked 'mutable'.
6146 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6147     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6148     unsigned FieldQuals, bool ConstRHS) {
6149   unsigned LHSQuals = 0;
6150   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6151     LHSQuals = FieldQuals;
6152 
6153   unsigned RHSQuals = FieldQuals;
6154   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6155     RHSQuals = 0;
6156   else if (ConstRHS)
6157     RHSQuals |= Qualifiers::Const;
6158 
6159   return S.LookupSpecialMember(Class, CSM,
6160                                RHSQuals & Qualifiers::Const,
6161                                RHSQuals & Qualifiers::Volatile,
6162                                false,
6163                                LHSQuals & Qualifiers::Const,
6164                                LHSQuals & Qualifiers::Volatile);
6165 }
6166 
6167 class Sema::InheritedConstructorInfo {
6168   Sema &S;
6169   SourceLocation UseLoc;
6170 
6171   /// A mapping from the base classes through which the constructor was
6172   /// inherited to the using shadow declaration in that base class (or a null
6173   /// pointer if the constructor was declared in that base class).
6174   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6175       InheritedFromBases;
6176 
6177 public:
6178   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6179                            ConstructorUsingShadowDecl *Shadow)
6180       : S(S), UseLoc(UseLoc) {
6181     bool DiagnosedMultipleConstructedBases = false;
6182     CXXRecordDecl *ConstructedBase = nullptr;
6183     UsingDecl *ConstructedBaseUsing = nullptr;
6184 
6185     // Find the set of such base class subobjects and check that there's a
6186     // unique constructed subobject.
6187     for (auto *D : Shadow->redecls()) {
6188       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6189       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6190       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6191 
6192       InheritedFromBases.insert(
6193           std::make_pair(DNominatedBase->getCanonicalDecl(),
6194                          DShadow->getNominatedBaseClassShadowDecl()));
6195       if (DShadow->constructsVirtualBase())
6196         InheritedFromBases.insert(
6197             std::make_pair(DConstructedBase->getCanonicalDecl(),
6198                            DShadow->getConstructedBaseClassShadowDecl()));
6199       else
6200         assert(DNominatedBase == DConstructedBase);
6201 
6202       // [class.inhctor.init]p2:
6203       //   If the constructor was inherited from multiple base class subobjects
6204       //   of type B, the program is ill-formed.
6205       if (!ConstructedBase) {
6206         ConstructedBase = DConstructedBase;
6207         ConstructedBaseUsing = D->getUsingDecl();
6208       } else if (ConstructedBase != DConstructedBase &&
6209                  !Shadow->isInvalidDecl()) {
6210         if (!DiagnosedMultipleConstructedBases) {
6211           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6212               << Shadow->getTargetDecl();
6213           S.Diag(ConstructedBaseUsing->getLocation(),
6214                diag::note_ambiguous_inherited_constructor_using)
6215               << ConstructedBase;
6216           DiagnosedMultipleConstructedBases = true;
6217         }
6218         S.Diag(D->getUsingDecl()->getLocation(),
6219                diag::note_ambiguous_inherited_constructor_using)
6220             << DConstructedBase;
6221       }
6222     }
6223 
6224     if (DiagnosedMultipleConstructedBases)
6225       Shadow->setInvalidDecl();
6226   }
6227 
6228   /// Find the constructor to use for inherited construction of a base class,
6229   /// and whether that base class constructor inherits the constructor from a
6230   /// virtual base class (in which case it won't actually invoke it).
6231   std::pair<CXXConstructorDecl *, bool>
6232   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6233     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6234     if (It == InheritedFromBases.end())
6235       return std::make_pair(nullptr, false);
6236 
6237     // This is an intermediary class.
6238     if (It->second)
6239       return std::make_pair(
6240           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6241           It->second->constructsVirtualBase());
6242 
6243     // This is the base class from which the constructor was inherited.
6244     return std::make_pair(Ctor, false);
6245   }
6246 };
6247 
6248 /// Is the special member function which would be selected to perform the
6249 /// specified operation on the specified class type a constexpr constructor?
6250 static bool
6251 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6252                          Sema::CXXSpecialMember CSM, unsigned Quals,
6253                          bool ConstRHS,
6254                          CXXConstructorDecl *InheritedCtor = nullptr,
6255                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6256   // If we're inheriting a constructor, see if we need to call it for this base
6257   // class.
6258   if (InheritedCtor) {
6259     assert(CSM == Sema::CXXDefaultConstructor);
6260     auto BaseCtor =
6261         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6262     if (BaseCtor)
6263       return BaseCtor->isConstexpr();
6264   }
6265 
6266   if (CSM == Sema::CXXDefaultConstructor)
6267     return ClassDecl->hasConstexprDefaultConstructor();
6268 
6269   Sema::SpecialMemberOverloadResult SMOR =
6270       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6271   if (!SMOR.getMethod())
6272     // A constructor we wouldn't select can't be "involved in initializing"
6273     // anything.
6274     return true;
6275   return SMOR.getMethod()->isConstexpr();
6276 }
6277 
6278 /// Determine whether the specified special member function would be constexpr
6279 /// if it were implicitly defined.
6280 static bool defaultedSpecialMemberIsConstexpr(
6281     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6282     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6283     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6284   if (!S.getLangOpts().CPlusPlus11)
6285     return false;
6286 
6287   // C++11 [dcl.constexpr]p4:
6288   // In the definition of a constexpr constructor [...]
6289   bool Ctor = true;
6290   switch (CSM) {
6291   case Sema::CXXDefaultConstructor:
6292     if (Inherited)
6293       break;
6294     // Since default constructor lookup is essentially trivial (and cannot
6295     // involve, for instance, template instantiation), we compute whether a
6296     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6297     //
6298     // This is important for performance; we need to know whether the default
6299     // constructor is constexpr to determine whether the type is a literal type.
6300     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6301 
6302   case Sema::CXXCopyConstructor:
6303   case Sema::CXXMoveConstructor:
6304     // For copy or move constructors, we need to perform overload resolution.
6305     break;
6306 
6307   case Sema::CXXCopyAssignment:
6308   case Sema::CXXMoveAssignment:
6309     if (!S.getLangOpts().CPlusPlus14)
6310       return false;
6311     // In C++1y, we need to perform overload resolution.
6312     Ctor = false;
6313     break;
6314 
6315   case Sema::CXXDestructor:
6316   case Sema::CXXInvalid:
6317     return false;
6318   }
6319 
6320   //   -- if the class is a non-empty union, or for each non-empty anonymous
6321   //      union member of a non-union class, exactly one non-static data member
6322   //      shall be initialized; [DR1359]
6323   //
6324   // If we squint, this is guaranteed, since exactly one non-static data member
6325   // will be initialized (if the constructor isn't deleted), we just don't know
6326   // which one.
6327   if (Ctor && ClassDecl->isUnion())
6328     return CSM == Sema::CXXDefaultConstructor
6329                ? ClassDecl->hasInClassInitializer() ||
6330                      !ClassDecl->hasVariantMembers()
6331                : true;
6332 
6333   //   -- the class shall not have any virtual base classes;
6334   if (Ctor && ClassDecl->getNumVBases())
6335     return false;
6336 
6337   // C++1y [class.copy]p26:
6338   //   -- [the class] is a literal type, and
6339   if (!Ctor && !ClassDecl->isLiteral())
6340     return false;
6341 
6342   //   -- every constructor involved in initializing [...] base class
6343   //      sub-objects shall be a constexpr constructor;
6344   //   -- the assignment operator selected to copy/move each direct base
6345   //      class is a constexpr function, and
6346   for (const auto &B : ClassDecl->bases()) {
6347     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6348     if (!BaseType) continue;
6349 
6350     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6351     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6352                                   InheritedCtor, Inherited))
6353       return false;
6354   }
6355 
6356   //   -- every constructor involved in initializing non-static data members
6357   //      [...] shall be a constexpr constructor;
6358   //   -- every non-static data member and base class sub-object shall be
6359   //      initialized
6360   //   -- for each non-static data member of X that is of class type (or array
6361   //      thereof), the assignment operator selected to copy/move that member is
6362   //      a constexpr function
6363   for (const auto *F : ClassDecl->fields()) {
6364     if (F->isInvalidDecl())
6365       continue;
6366     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6367       continue;
6368     QualType BaseType = S.Context.getBaseElementType(F->getType());
6369     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6370       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6371       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6372                                     BaseType.getCVRQualifiers(),
6373                                     ConstArg && !F->isMutable()))
6374         return false;
6375     } else if (CSM == Sema::CXXDefaultConstructor) {
6376       return false;
6377     }
6378   }
6379 
6380   // All OK, it's constexpr!
6381   return true;
6382 }
6383 
6384 static Sema::ImplicitExceptionSpecification
6385 ComputeDefaultedSpecialMemberExceptionSpec(
6386     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6387     Sema::InheritedConstructorInfo *ICI);
6388 
6389 static Sema::ImplicitExceptionSpecification
6390 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6391   auto CSM = S.getSpecialMember(MD);
6392   if (CSM != Sema::CXXInvalid)
6393     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6394 
6395   auto *CD = cast<CXXConstructorDecl>(MD);
6396   assert(CD->getInheritedConstructor() &&
6397          "only special members have implicit exception specs");
6398   Sema::InheritedConstructorInfo ICI(
6399       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6400   return ComputeDefaultedSpecialMemberExceptionSpec(
6401       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6402 }
6403 
6404 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6405                                                             CXXMethodDecl *MD) {
6406   FunctionProtoType::ExtProtoInfo EPI;
6407 
6408   // Build an exception specification pointing back at this member.
6409   EPI.ExceptionSpec.Type = EST_Unevaluated;
6410   EPI.ExceptionSpec.SourceDecl = MD;
6411 
6412   // Set the calling convention to the default for C++ instance methods.
6413   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6414       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6415                                             /*IsCXXMethod=*/true));
6416   return EPI;
6417 }
6418 
6419 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6420   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6421   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6422     return;
6423 
6424   // Evaluate the exception specification.
6425   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6426   auto ESI = IES.getExceptionSpec();
6427 
6428   // Update the type of the special member to use it.
6429   UpdateExceptionSpec(MD, ESI);
6430 
6431   // A user-provided destructor can be defined outside the class. When that
6432   // happens, be sure to update the exception specification on both
6433   // declarations.
6434   const FunctionProtoType *CanonicalFPT =
6435     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6436   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6437     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6438 }
6439 
6440 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6441   CXXRecordDecl *RD = MD->getParent();
6442   CXXSpecialMember CSM = getSpecialMember(MD);
6443 
6444   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6445          "not an explicitly-defaulted special member");
6446 
6447   // Whether this was the first-declared instance of the constructor.
6448   // This affects whether we implicitly add an exception spec and constexpr.
6449   bool First = MD == MD->getCanonicalDecl();
6450 
6451   bool HadError = false;
6452 
6453   // C++11 [dcl.fct.def.default]p1:
6454   //   A function that is explicitly defaulted shall
6455   //     -- be a special member function (checked elsewhere),
6456   //     -- have the same type (except for ref-qualifiers, and except that a
6457   //        copy operation can take a non-const reference) as an implicit
6458   //        declaration, and
6459   //     -- not have default arguments.
6460   unsigned ExpectedParams = 1;
6461   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6462     ExpectedParams = 0;
6463   if (MD->getNumParams() != ExpectedParams) {
6464     // This also checks for default arguments: a copy or move constructor with a
6465     // default argument is classified as a default constructor, and assignment
6466     // operations and destructors can't have default arguments.
6467     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6468       << CSM << MD->getSourceRange();
6469     HadError = true;
6470   } else if (MD->isVariadic()) {
6471     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6472       << CSM << MD->getSourceRange();
6473     HadError = true;
6474   }
6475 
6476   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6477 
6478   bool CanHaveConstParam = false;
6479   if (CSM == CXXCopyConstructor)
6480     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6481   else if (CSM == CXXCopyAssignment)
6482     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6483 
6484   QualType ReturnType = Context.VoidTy;
6485   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6486     // Check for return type matching.
6487     ReturnType = Type->getReturnType();
6488     QualType ExpectedReturnType =
6489         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6490     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6491       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6492         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6493       HadError = true;
6494     }
6495 
6496     // A defaulted special member cannot have cv-qualifiers.
6497     if (Type->getTypeQuals()) {
6498       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6499         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6500       HadError = true;
6501     }
6502   }
6503 
6504   // Check for parameter type matching.
6505   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6506   bool HasConstParam = false;
6507   if (ExpectedParams && ArgType->isReferenceType()) {
6508     // Argument must be reference to possibly-const T.
6509     QualType ReferentType = ArgType->getPointeeType();
6510     HasConstParam = ReferentType.isConstQualified();
6511 
6512     if (ReferentType.isVolatileQualified()) {
6513       Diag(MD->getLocation(),
6514            diag::err_defaulted_special_member_volatile_param) << CSM;
6515       HadError = true;
6516     }
6517 
6518     if (HasConstParam && !CanHaveConstParam) {
6519       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6520         Diag(MD->getLocation(),
6521              diag::err_defaulted_special_member_copy_const_param)
6522           << (CSM == CXXCopyAssignment);
6523         // FIXME: Explain why this special member can't be const.
6524       } else {
6525         Diag(MD->getLocation(),
6526              diag::err_defaulted_special_member_move_const_param)
6527           << (CSM == CXXMoveAssignment);
6528       }
6529       HadError = true;
6530     }
6531   } else if (ExpectedParams) {
6532     // A copy assignment operator can take its argument by value, but a
6533     // defaulted one cannot.
6534     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6535     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6536     HadError = true;
6537   }
6538 
6539   // C++11 [dcl.fct.def.default]p2:
6540   //   An explicitly-defaulted function may be declared constexpr only if it
6541   //   would have been implicitly declared as constexpr,
6542   // Do not apply this rule to members of class templates, since core issue 1358
6543   // makes such functions always instantiate to constexpr functions. For
6544   // functions which cannot be constexpr (for non-constructors in C++11 and for
6545   // destructors in C++1y), this is checked elsewhere.
6546   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6547                                                      HasConstParam);
6548   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6549                                  : isa<CXXConstructorDecl>(MD)) &&
6550       MD->isConstexpr() && !Constexpr &&
6551       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6552     Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6553     // FIXME: Explain why the special member can't be constexpr.
6554     HadError = true;
6555   }
6556 
6557   //   and may have an explicit exception-specification only if it is compatible
6558   //   with the exception-specification on the implicit declaration.
6559   if (Type->hasExceptionSpec()) {
6560     // Delay the check if this is the first declaration of the special member,
6561     // since we may not have parsed some necessary in-class initializers yet.
6562     if (First) {
6563       // If the exception specification needs to be instantiated, do so now,
6564       // before we clobber it with an EST_Unevaluated specification below.
6565       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6566         InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6567         Type = MD->getType()->getAs<FunctionProtoType>();
6568       }
6569       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6570     } else
6571       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6572   }
6573 
6574   //   If a function is explicitly defaulted on its first declaration,
6575   if (First) {
6576     //  -- it is implicitly considered to be constexpr if the implicit
6577     //     definition would be,
6578     MD->setConstexpr(Constexpr);
6579 
6580     //  -- it is implicitly considered to have the same exception-specification
6581     //     as if it had been implicitly declared,
6582     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6583     EPI.ExceptionSpec.Type = EST_Unevaluated;
6584     EPI.ExceptionSpec.SourceDecl = MD;
6585     MD->setType(Context.getFunctionType(ReturnType,
6586                                         llvm::makeArrayRef(&ArgType,
6587                                                            ExpectedParams),
6588                                         EPI));
6589   }
6590 
6591   if (ShouldDeleteSpecialMember(MD, CSM)) {
6592     if (First) {
6593       SetDeclDeleted(MD, MD->getLocation());
6594     } else {
6595       // C++11 [dcl.fct.def.default]p4:
6596       //   [For a] user-provided explicitly-defaulted function [...] if such a
6597       //   function is implicitly defined as deleted, the program is ill-formed.
6598       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6599       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6600       HadError = true;
6601     }
6602   }
6603 
6604   if (HadError)
6605     MD->setInvalidDecl();
6606 }
6607 
6608 /// Check whether the exception specification provided for an
6609 /// explicitly-defaulted special member matches the exception specification
6610 /// that would have been generated for an implicit special member, per
6611 /// C++11 [dcl.fct.def.default]p2.
6612 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6613     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6614   // If the exception specification was explicitly specified but hadn't been
6615   // parsed when the method was defaulted, grab it now.
6616   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6617     SpecifiedType =
6618         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6619 
6620   // Compute the implicit exception specification.
6621   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6622                                                        /*IsCXXMethod=*/true);
6623   FunctionProtoType::ExtProtoInfo EPI(CC);
6624   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6625   EPI.ExceptionSpec = IES.getExceptionSpec();
6626   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6627     Context.getFunctionType(Context.VoidTy, None, EPI));
6628 
6629   // Ensure that it matches.
6630   CheckEquivalentExceptionSpec(
6631     PDiag(diag::err_incorrect_defaulted_exception_spec)
6632       << getSpecialMember(MD), PDiag(),
6633     ImplicitType, SourceLocation(),
6634     SpecifiedType, MD->getLocation());
6635 }
6636 
6637 void Sema::CheckDelayedMemberExceptionSpecs() {
6638   decltype(DelayedExceptionSpecChecks) Checks;
6639   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6640 
6641   std::swap(Checks, DelayedExceptionSpecChecks);
6642   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6643 
6644   // Perform any deferred checking of exception specifications for virtual
6645   // destructors.
6646   for (auto &Check : Checks)
6647     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6648 
6649   // Check that any explicitly-defaulted methods have exception specifications
6650   // compatible with their implicit exception specifications.
6651   for (auto &Spec : Specs)
6652     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6653 }
6654 
6655 namespace {
6656 /// CRTP base class for visiting operations performed by a special member
6657 /// function (or inherited constructor).
6658 template<typename Derived>
6659 struct SpecialMemberVisitor {
6660   Sema &S;
6661   CXXMethodDecl *MD;
6662   Sema::CXXSpecialMember CSM;
6663   Sema::InheritedConstructorInfo *ICI;
6664 
6665   // Properties of the special member, computed for convenience.
6666   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6667 
6668   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6669                        Sema::InheritedConstructorInfo *ICI)
6670       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6671     switch (CSM) {
6672     case Sema::CXXDefaultConstructor:
6673     case Sema::CXXCopyConstructor:
6674     case Sema::CXXMoveConstructor:
6675       IsConstructor = true;
6676       break;
6677     case Sema::CXXCopyAssignment:
6678     case Sema::CXXMoveAssignment:
6679       IsAssignment = true;
6680       break;
6681     case Sema::CXXDestructor:
6682       break;
6683     case Sema::CXXInvalid:
6684       llvm_unreachable("invalid special member kind");
6685     }
6686 
6687     if (MD->getNumParams()) {
6688       if (const ReferenceType *RT =
6689               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6690         ConstArg = RT->getPointeeType().isConstQualified();
6691     }
6692   }
6693 
6694   Derived &getDerived() { return static_cast<Derived&>(*this); }
6695 
6696   /// Is this a "move" special member?
6697   bool isMove() const {
6698     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6699   }
6700 
6701   /// Look up the corresponding special member in the given class.
6702   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6703                                              unsigned Quals, bool IsMutable) {
6704     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6705                                        ConstArg && !IsMutable);
6706   }
6707 
6708   /// Look up the constructor for the specified base class to see if it's
6709   /// overridden due to this being an inherited constructor.
6710   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6711     if (!ICI)
6712       return {};
6713     assert(CSM == Sema::CXXDefaultConstructor);
6714     auto *BaseCtor =
6715       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6716     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6717       return MD;
6718     return {};
6719   }
6720 
6721   /// A base or member subobject.
6722   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6723 
6724   /// Get the location to use for a subobject in diagnostics.
6725   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6726     // FIXME: For an indirect virtual base, the direct base leading to
6727     // the indirect virtual base would be a more useful choice.
6728     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6729       return B->getBaseTypeLoc();
6730     else
6731       return Subobj.get<FieldDecl*>()->getLocation();
6732   }
6733 
6734   enum BasesToVisit {
6735     /// Visit all non-virtual (direct) bases.
6736     VisitNonVirtualBases,
6737     /// Visit all direct bases, virtual or not.
6738     VisitDirectBases,
6739     /// Visit all non-virtual bases, and all virtual bases if the class
6740     /// is not abstract.
6741     VisitPotentiallyConstructedBases,
6742     /// Visit all direct or virtual bases.
6743     VisitAllBases
6744   };
6745 
6746   // Visit the bases and members of the class.
6747   bool visit(BasesToVisit Bases) {
6748     CXXRecordDecl *RD = MD->getParent();
6749 
6750     if (Bases == VisitPotentiallyConstructedBases)
6751       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6752 
6753     for (auto &B : RD->bases())
6754       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6755           getDerived().visitBase(&B))
6756         return true;
6757 
6758     if (Bases == VisitAllBases)
6759       for (auto &B : RD->vbases())
6760         if (getDerived().visitBase(&B))
6761           return true;
6762 
6763     for (auto *F : RD->fields())
6764       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6765           getDerived().visitField(F))
6766         return true;
6767 
6768     return false;
6769   }
6770 };
6771 }
6772 
6773 namespace {
6774 struct SpecialMemberDeletionInfo
6775     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6776   bool Diagnose;
6777 
6778   SourceLocation Loc;
6779 
6780   bool AllFieldsAreConst;
6781 
6782   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6783                             Sema::CXXSpecialMember CSM,
6784                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6785       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6786         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6787 
6788   bool inUnion() const { return MD->getParent()->isUnion(); }
6789 
6790   Sema::CXXSpecialMember getEffectiveCSM() {
6791     return ICI ? Sema::CXXInvalid : CSM;
6792   }
6793 
6794   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6795   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6796 
6797   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6798   bool shouldDeleteForField(FieldDecl *FD);
6799   bool shouldDeleteForAllConstMembers();
6800 
6801   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6802                                      unsigned Quals);
6803   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6804                                     Sema::SpecialMemberOverloadResult SMOR,
6805                                     bool IsDtorCallInCtor);
6806 
6807   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6808 };
6809 }
6810 
6811 /// Is the given special member inaccessible when used on the given
6812 /// sub-object.
6813 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6814                                              CXXMethodDecl *target) {
6815   /// If we're operating on a base class, the object type is the
6816   /// type of this special member.
6817   QualType objectTy;
6818   AccessSpecifier access = target->getAccess();
6819   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6820     objectTy = S.Context.getTypeDeclType(MD->getParent());
6821     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6822 
6823   // If we're operating on a field, the object type is the type of the field.
6824   } else {
6825     objectTy = S.Context.getTypeDeclType(target->getParent());
6826   }
6827 
6828   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6829 }
6830 
6831 /// Check whether we should delete a special member due to the implicit
6832 /// definition containing a call to a special member of a subobject.
6833 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6834     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6835     bool IsDtorCallInCtor) {
6836   CXXMethodDecl *Decl = SMOR.getMethod();
6837   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6838 
6839   int DiagKind = -1;
6840 
6841   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6842     DiagKind = !Decl ? 0 : 1;
6843   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6844     DiagKind = 2;
6845   else if (!isAccessible(Subobj, Decl))
6846     DiagKind = 3;
6847   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6848            !Decl->isTrivial()) {
6849     // A member of a union must have a trivial corresponding special member.
6850     // As a weird special case, a destructor call from a union's constructor
6851     // must be accessible and non-deleted, but need not be trivial. Such a
6852     // destructor is never actually called, but is semantically checked as
6853     // if it were.
6854     DiagKind = 4;
6855   }
6856 
6857   if (DiagKind == -1)
6858     return false;
6859 
6860   if (Diagnose) {
6861     if (Field) {
6862       S.Diag(Field->getLocation(),
6863              diag::note_deleted_special_member_class_subobject)
6864         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6865         << Field << DiagKind << IsDtorCallInCtor;
6866     } else {
6867       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6868       S.Diag(Base->getBeginLoc(),
6869              diag::note_deleted_special_member_class_subobject)
6870           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6871           << Base->getType() << DiagKind << IsDtorCallInCtor;
6872     }
6873 
6874     if (DiagKind == 1)
6875       S.NoteDeletedFunction(Decl);
6876     // FIXME: Explain inaccessibility if DiagKind == 3.
6877   }
6878 
6879   return true;
6880 }
6881 
6882 /// Check whether we should delete a special member function due to having a
6883 /// direct or virtual base class or non-static data member of class type M.
6884 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6885     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6886   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6887   bool IsMutable = Field && Field->isMutable();
6888 
6889   // C++11 [class.ctor]p5:
6890   // -- any direct or virtual base class, or non-static data member with no
6891   //    brace-or-equal-initializer, has class type M (or array thereof) and
6892   //    either M has no default constructor or overload resolution as applied
6893   //    to M's default constructor results in an ambiguity or in a function
6894   //    that is deleted or inaccessible
6895   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6896   // -- a direct or virtual base class B that cannot be copied/moved because
6897   //    overload resolution, as applied to B's corresponding special member,
6898   //    results in an ambiguity or a function that is deleted or inaccessible
6899   //    from the defaulted special member
6900   // C++11 [class.dtor]p5:
6901   // -- any direct or virtual base class [...] has a type with a destructor
6902   //    that is deleted or inaccessible
6903   if (!(CSM == Sema::CXXDefaultConstructor &&
6904         Field && Field->hasInClassInitializer()) &&
6905       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6906                                    false))
6907     return true;
6908 
6909   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6910   // -- any direct or virtual base class or non-static data member has a
6911   //    type with a destructor that is deleted or inaccessible
6912   if (IsConstructor) {
6913     Sema::SpecialMemberOverloadResult SMOR =
6914         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6915                               false, false, false, false, false);
6916     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6917       return true;
6918   }
6919 
6920   return false;
6921 }
6922 
6923 /// Check whether we should delete a special member function due to the class
6924 /// having a particular direct or virtual base class.
6925 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6926   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6927   // If program is correct, BaseClass cannot be null, but if it is, the error
6928   // must be reported elsewhere.
6929   if (!BaseClass)
6930     return false;
6931   // If we have an inheriting constructor, check whether we're calling an
6932   // inherited constructor instead of a default constructor.
6933   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6934   if (auto *BaseCtor = SMOR.getMethod()) {
6935     // Note that we do not check access along this path; other than that,
6936     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6937     // FIXME: Check that the base has a usable destructor! Sink this into
6938     // shouldDeleteForClassSubobject.
6939     if (BaseCtor->isDeleted() && Diagnose) {
6940       S.Diag(Base->getBeginLoc(),
6941              diag::note_deleted_special_member_class_subobject)
6942           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6943           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
6944       S.NoteDeletedFunction(BaseCtor);
6945     }
6946     return BaseCtor->isDeleted();
6947   }
6948   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6949 }
6950 
6951 /// Check whether we should delete a special member function due to the class
6952 /// having a particular non-static data member.
6953 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6954   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6955   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6956 
6957   if (CSM == Sema::CXXDefaultConstructor) {
6958     // For a default constructor, all references must be initialized in-class
6959     // and, if a union, it must have a non-const member.
6960     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6961       if (Diagnose)
6962         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6963           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6964       return true;
6965     }
6966     // C++11 [class.ctor]p5: any non-variant non-static data member of
6967     // const-qualified type (or array thereof) with no
6968     // brace-or-equal-initializer does not have a user-provided default
6969     // constructor.
6970     if (!inUnion() && FieldType.isConstQualified() &&
6971         !FD->hasInClassInitializer() &&
6972         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6973       if (Diagnose)
6974         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6975           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6976       return true;
6977     }
6978 
6979     if (inUnion() && !FieldType.isConstQualified())
6980       AllFieldsAreConst = false;
6981   } else if (CSM == Sema::CXXCopyConstructor) {
6982     // For a copy constructor, data members must not be of rvalue reference
6983     // type.
6984     if (FieldType->isRValueReferenceType()) {
6985       if (Diagnose)
6986         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6987           << MD->getParent() << FD << FieldType;
6988       return true;
6989     }
6990   } else if (IsAssignment) {
6991     // For an assignment operator, data members must not be of reference type.
6992     if (FieldType->isReferenceType()) {
6993       if (Diagnose)
6994         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6995           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6996       return true;
6997     }
6998     if (!FieldRecord && FieldType.isConstQualified()) {
6999       // C++11 [class.copy]p23:
7000       // -- a non-static data member of const non-class type (or array thereof)
7001       if (Diagnose)
7002         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7003           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7004       return true;
7005     }
7006   }
7007 
7008   if (FieldRecord) {
7009     // Some additional restrictions exist on the variant members.
7010     if (!inUnion() && FieldRecord->isUnion() &&
7011         FieldRecord->isAnonymousStructOrUnion()) {
7012       bool AllVariantFieldsAreConst = true;
7013 
7014       // FIXME: Handle anonymous unions declared within anonymous unions.
7015       for (auto *UI : FieldRecord->fields()) {
7016         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7017 
7018         if (!UnionFieldType.isConstQualified())
7019           AllVariantFieldsAreConst = false;
7020 
7021         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7022         if (UnionFieldRecord &&
7023             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7024                                           UnionFieldType.getCVRQualifiers()))
7025           return true;
7026       }
7027 
7028       // At least one member in each anonymous union must be non-const
7029       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7030           !FieldRecord->field_empty()) {
7031         if (Diagnose)
7032           S.Diag(FieldRecord->getLocation(),
7033                  diag::note_deleted_default_ctor_all_const)
7034             << !!ICI << MD->getParent() << /*anonymous union*/1;
7035         return true;
7036       }
7037 
7038       // Don't check the implicit member of the anonymous union type.
7039       // This is technically non-conformant, but sanity demands it.
7040       return false;
7041     }
7042 
7043     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7044                                       FieldType.getCVRQualifiers()))
7045       return true;
7046   }
7047 
7048   return false;
7049 }
7050 
7051 /// C++11 [class.ctor] p5:
7052 ///   A defaulted default constructor for a class X is defined as deleted if
7053 /// X is a union and all of its variant members are of const-qualified type.
7054 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7055   // This is a silly definition, because it gives an empty union a deleted
7056   // default constructor. Don't do that.
7057   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7058     bool AnyFields = false;
7059     for (auto *F : MD->getParent()->fields())
7060       if ((AnyFields = !F->isUnnamedBitfield()))
7061         break;
7062     if (!AnyFields)
7063       return false;
7064     if (Diagnose)
7065       S.Diag(MD->getParent()->getLocation(),
7066              diag::note_deleted_default_ctor_all_const)
7067         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7068     return true;
7069   }
7070   return false;
7071 }
7072 
7073 /// Determine whether a defaulted special member function should be defined as
7074 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7075 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7076 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7077                                      InheritedConstructorInfo *ICI,
7078                                      bool Diagnose) {
7079   if (MD->isInvalidDecl())
7080     return false;
7081   CXXRecordDecl *RD = MD->getParent();
7082   assert(!RD->isDependentType() && "do deletion after instantiation");
7083   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7084     return false;
7085 
7086   // C++11 [expr.lambda.prim]p19:
7087   //   The closure type associated with a lambda-expression has a
7088   //   deleted (8.4.3) default constructor and a deleted copy
7089   //   assignment operator.
7090   if (RD->isLambda() &&
7091       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7092     if (Diagnose)
7093       Diag(RD->getLocation(), diag::note_lambda_decl);
7094     return true;
7095   }
7096 
7097   // For an anonymous struct or union, the copy and assignment special members
7098   // will never be used, so skip the check. For an anonymous union declared at
7099   // namespace scope, the constructor and destructor are used.
7100   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7101       RD->isAnonymousStructOrUnion())
7102     return false;
7103 
7104   // C++11 [class.copy]p7, p18:
7105   //   If the class definition declares a move constructor or move assignment
7106   //   operator, an implicitly declared copy constructor or copy assignment
7107   //   operator is defined as deleted.
7108   if (MD->isImplicit() &&
7109       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7110     CXXMethodDecl *UserDeclaredMove = nullptr;
7111 
7112     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7113     // deletion of the corresponding copy operation, not both copy operations.
7114     // MSVC 2015 has adopted the standards conforming behavior.
7115     bool DeletesOnlyMatchingCopy =
7116         getLangOpts().MSVCCompat &&
7117         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7118 
7119     if (RD->hasUserDeclaredMoveConstructor() &&
7120         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7121       if (!Diagnose) return true;
7122 
7123       // Find any user-declared move constructor.
7124       for (auto *I : RD->ctors()) {
7125         if (I->isMoveConstructor()) {
7126           UserDeclaredMove = I;
7127           break;
7128         }
7129       }
7130       assert(UserDeclaredMove);
7131     } else if (RD->hasUserDeclaredMoveAssignment() &&
7132                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7133       if (!Diagnose) return true;
7134 
7135       // Find any user-declared move assignment operator.
7136       for (auto *I : RD->methods()) {
7137         if (I->isMoveAssignmentOperator()) {
7138           UserDeclaredMove = I;
7139           break;
7140         }
7141       }
7142       assert(UserDeclaredMove);
7143     }
7144 
7145     if (UserDeclaredMove) {
7146       Diag(UserDeclaredMove->getLocation(),
7147            diag::note_deleted_copy_user_declared_move)
7148         << (CSM == CXXCopyAssignment) << RD
7149         << UserDeclaredMove->isMoveAssignmentOperator();
7150       return true;
7151     }
7152   }
7153 
7154   // Do access control from the special member function
7155   ContextRAII MethodContext(*this, MD);
7156 
7157   // C++11 [class.dtor]p5:
7158   // -- for a virtual destructor, lookup of the non-array deallocation function
7159   //    results in an ambiguity or in a function that is deleted or inaccessible
7160   if (CSM == CXXDestructor && MD->isVirtual()) {
7161     FunctionDecl *OperatorDelete = nullptr;
7162     DeclarationName Name =
7163       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7164     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7165                                  OperatorDelete, /*Diagnose*/false)) {
7166       if (Diagnose)
7167         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7168       return true;
7169     }
7170   }
7171 
7172   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7173 
7174   // Per DR1611, do not consider virtual bases of constructors of abstract
7175   // classes, since we are not going to construct them.
7176   // Per DR1658, do not consider virtual bases of destructors of abstract
7177   // classes either.
7178   // Per DR2180, for assignment operators we only assign (and thus only
7179   // consider) direct bases.
7180   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7181                                  : SMI.VisitPotentiallyConstructedBases))
7182     return true;
7183 
7184   if (SMI.shouldDeleteForAllConstMembers())
7185     return true;
7186 
7187   if (getLangOpts().CUDA) {
7188     // We should delete the special member in CUDA mode if target inference
7189     // failed.
7190     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7191                                                    Diagnose);
7192   }
7193 
7194   return false;
7195 }
7196 
7197 /// Perform lookup for a special member of the specified kind, and determine
7198 /// whether it is trivial. If the triviality can be determined without the
7199 /// lookup, skip it. This is intended for use when determining whether a
7200 /// special member of a containing object is trivial, and thus does not ever
7201 /// perform overload resolution for default constructors.
7202 ///
7203 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7204 /// member that was most likely to be intended to be trivial, if any.
7205 ///
7206 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7207 /// determine whether the special member is trivial.
7208 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7209                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7210                                      bool ConstRHS,
7211                                      Sema::TrivialABIHandling TAH,
7212                                      CXXMethodDecl **Selected) {
7213   if (Selected)
7214     *Selected = nullptr;
7215 
7216   switch (CSM) {
7217   case Sema::CXXInvalid:
7218     llvm_unreachable("not a special member");
7219 
7220   case Sema::CXXDefaultConstructor:
7221     // C++11 [class.ctor]p5:
7222     //   A default constructor is trivial if:
7223     //    - all the [direct subobjects] have trivial default constructors
7224     //
7225     // Note, no overload resolution is performed in this case.
7226     if (RD->hasTrivialDefaultConstructor())
7227       return true;
7228 
7229     if (Selected) {
7230       // If there's a default constructor which could have been trivial, dig it
7231       // out. Otherwise, if there's any user-provided default constructor, point
7232       // to that as an example of why there's not a trivial one.
7233       CXXConstructorDecl *DefCtor = nullptr;
7234       if (RD->needsImplicitDefaultConstructor())
7235         S.DeclareImplicitDefaultConstructor(RD);
7236       for (auto *CI : RD->ctors()) {
7237         if (!CI->isDefaultConstructor())
7238           continue;
7239         DefCtor = CI;
7240         if (!DefCtor->isUserProvided())
7241           break;
7242       }
7243 
7244       *Selected = DefCtor;
7245     }
7246 
7247     return false;
7248 
7249   case Sema::CXXDestructor:
7250     // C++11 [class.dtor]p5:
7251     //   A destructor is trivial if:
7252     //    - all the direct [subobjects] have trivial destructors
7253     if (RD->hasTrivialDestructor() ||
7254         (TAH == Sema::TAH_ConsiderTrivialABI &&
7255          RD->hasTrivialDestructorForCall()))
7256       return true;
7257 
7258     if (Selected) {
7259       if (RD->needsImplicitDestructor())
7260         S.DeclareImplicitDestructor(RD);
7261       *Selected = RD->getDestructor();
7262     }
7263 
7264     return false;
7265 
7266   case Sema::CXXCopyConstructor:
7267     // C++11 [class.copy]p12:
7268     //   A copy constructor is trivial if:
7269     //    - the constructor selected to copy each direct [subobject] is trivial
7270     if (RD->hasTrivialCopyConstructor() ||
7271         (TAH == Sema::TAH_ConsiderTrivialABI &&
7272          RD->hasTrivialCopyConstructorForCall())) {
7273       if (Quals == Qualifiers::Const)
7274         // We must either select the trivial copy constructor or reach an
7275         // ambiguity; no need to actually perform overload resolution.
7276         return true;
7277     } else if (!Selected) {
7278       return false;
7279     }
7280     // In C++98, we are not supposed to perform overload resolution here, but we
7281     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7282     // cases like B as having a non-trivial copy constructor:
7283     //   struct A { template<typename T> A(T&); };
7284     //   struct B { mutable A a; };
7285     goto NeedOverloadResolution;
7286 
7287   case Sema::CXXCopyAssignment:
7288     // C++11 [class.copy]p25:
7289     //   A copy assignment operator is trivial if:
7290     //    - the assignment operator selected to copy each direct [subobject] is
7291     //      trivial
7292     if (RD->hasTrivialCopyAssignment()) {
7293       if (Quals == Qualifiers::Const)
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.
7300     goto NeedOverloadResolution;
7301 
7302   case Sema::CXXMoveConstructor:
7303   case Sema::CXXMoveAssignment:
7304   NeedOverloadResolution:
7305     Sema::SpecialMemberOverloadResult SMOR =
7306         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7307 
7308     // The standard doesn't describe how to behave if the lookup is ambiguous.
7309     // We treat it as not making the member non-trivial, just like the standard
7310     // mandates for the default constructor. This should rarely matter, because
7311     // the member will also be deleted.
7312     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7313       return true;
7314 
7315     if (!SMOR.getMethod()) {
7316       assert(SMOR.getKind() ==
7317              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7318       return false;
7319     }
7320 
7321     // We deliberately don't check if we found a deleted special member. We're
7322     // not supposed to!
7323     if (Selected)
7324       *Selected = SMOR.getMethod();
7325 
7326     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7327         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7328       return SMOR.getMethod()->isTrivialForCall();
7329     return SMOR.getMethod()->isTrivial();
7330   }
7331 
7332   llvm_unreachable("unknown special method kind");
7333 }
7334 
7335 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7336   for (auto *CI : RD->ctors())
7337     if (!CI->isImplicit())
7338       return CI;
7339 
7340   // Look for constructor templates.
7341   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7342   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7343     if (CXXConstructorDecl *CD =
7344           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7345       return CD;
7346   }
7347 
7348   return nullptr;
7349 }
7350 
7351 /// The kind of subobject we are checking for triviality. The values of this
7352 /// enumeration are used in diagnostics.
7353 enum TrivialSubobjectKind {
7354   /// The subobject is a base class.
7355   TSK_BaseClass,
7356   /// The subobject is a non-static data member.
7357   TSK_Field,
7358   /// The object is actually the complete object.
7359   TSK_CompleteObject
7360 };
7361 
7362 /// Check whether the special member selected for a given type would be trivial.
7363 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7364                                       QualType SubType, bool ConstRHS,
7365                                       Sema::CXXSpecialMember CSM,
7366                                       TrivialSubobjectKind Kind,
7367                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7368   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7369   if (!SubRD)
7370     return true;
7371 
7372   CXXMethodDecl *Selected;
7373   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7374                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7375     return true;
7376 
7377   if (Diagnose) {
7378     if (ConstRHS)
7379       SubType.addConst();
7380 
7381     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7382       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7383         << Kind << SubType.getUnqualifiedType();
7384       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7385         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7386     } else if (!Selected)
7387       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7388         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7389     else if (Selected->isUserProvided()) {
7390       if (Kind == TSK_CompleteObject)
7391         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7392           << Kind << SubType.getUnqualifiedType() << CSM;
7393       else {
7394         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7395           << Kind << SubType.getUnqualifiedType() << CSM;
7396         S.Diag(Selected->getLocation(), diag::note_declared_at);
7397       }
7398     } else {
7399       if (Kind != TSK_CompleteObject)
7400         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7401           << Kind << SubType.getUnqualifiedType() << CSM;
7402 
7403       // Explain why the defaulted or deleted special member isn't trivial.
7404       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7405                                Diagnose);
7406     }
7407   }
7408 
7409   return false;
7410 }
7411 
7412 /// Check whether the members of a class type allow a special member to be
7413 /// trivial.
7414 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7415                                      Sema::CXXSpecialMember CSM,
7416                                      bool ConstArg,
7417                                      Sema::TrivialABIHandling TAH,
7418                                      bool Diagnose) {
7419   for (const auto *FI : RD->fields()) {
7420     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7421       continue;
7422 
7423     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7424 
7425     // Pretend anonymous struct or union members are members of this class.
7426     if (FI->isAnonymousStructOrUnion()) {
7427       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7428                                     CSM, ConstArg, TAH, Diagnose))
7429         return false;
7430       continue;
7431     }
7432 
7433     // C++11 [class.ctor]p5:
7434     //   A default constructor is trivial if [...]
7435     //    -- no non-static data member of its class has a
7436     //       brace-or-equal-initializer
7437     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7438       if (Diagnose)
7439         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7440       return false;
7441     }
7442 
7443     // Objective C ARC 4.3.5:
7444     //   [...] nontrivally ownership-qualified types are [...] not trivially
7445     //   default constructible, copy constructible, move constructible, copy
7446     //   assignable, move assignable, or destructible [...]
7447     if (FieldType.hasNonTrivialObjCLifetime()) {
7448       if (Diagnose)
7449         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7450           << RD << FieldType.getObjCLifetime();
7451       return false;
7452     }
7453 
7454     bool ConstRHS = ConstArg && !FI->isMutable();
7455     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7456                                    CSM, TSK_Field, TAH, Diagnose))
7457       return false;
7458   }
7459 
7460   return true;
7461 }
7462 
7463 /// Diagnose why the specified class does not have a trivial special member of
7464 /// the given kind.
7465 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7466   QualType Ty = Context.getRecordType(RD);
7467 
7468   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7469   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7470                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7471                             /*Diagnose*/true);
7472 }
7473 
7474 /// Determine whether a defaulted or deleted special member function is trivial,
7475 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7476 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7477 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7478                                   TrivialABIHandling TAH, bool Diagnose) {
7479   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7480 
7481   CXXRecordDecl *RD = MD->getParent();
7482 
7483   bool ConstArg = false;
7484 
7485   // C++11 [class.copy]p12, p25: [DR1593]
7486   //   A [special member] is trivial if [...] its parameter-type-list is
7487   //   equivalent to the parameter-type-list of an implicit declaration [...]
7488   switch (CSM) {
7489   case CXXDefaultConstructor:
7490   case CXXDestructor:
7491     // Trivial default constructors and destructors cannot have parameters.
7492     break;
7493 
7494   case CXXCopyConstructor:
7495   case CXXCopyAssignment: {
7496     // Trivial copy operations always have const, non-volatile parameter types.
7497     ConstArg = true;
7498     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7499     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7500     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7501       if (Diagnose)
7502         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7503           << Param0->getSourceRange() << Param0->getType()
7504           << Context.getLValueReferenceType(
7505                Context.getRecordType(RD).withConst());
7506       return false;
7507     }
7508     break;
7509   }
7510 
7511   case CXXMoveConstructor:
7512   case CXXMoveAssignment: {
7513     // Trivial move operations always have non-cv-qualified parameters.
7514     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7515     const RValueReferenceType *RT =
7516       Param0->getType()->getAs<RValueReferenceType>();
7517     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7518       if (Diagnose)
7519         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7520           << Param0->getSourceRange() << Param0->getType()
7521           << Context.getRValueReferenceType(Context.getRecordType(RD));
7522       return false;
7523     }
7524     break;
7525   }
7526 
7527   case CXXInvalid:
7528     llvm_unreachable("not a special member");
7529   }
7530 
7531   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7532     if (Diagnose)
7533       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7534            diag::note_nontrivial_default_arg)
7535         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7536     return false;
7537   }
7538   if (MD->isVariadic()) {
7539     if (Diagnose)
7540       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7541     return false;
7542   }
7543 
7544   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7545   //   A copy/move [constructor or assignment operator] is trivial if
7546   //    -- the [member] selected to copy/move each direct base class subobject
7547   //       is trivial
7548   //
7549   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7550   //   A [default constructor or destructor] is trivial if
7551   //    -- all the direct base classes have trivial [default constructors or
7552   //       destructors]
7553   for (const auto &BI : RD->bases())
7554     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7555                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7556       return false;
7557 
7558   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7559   //   A copy/move [constructor or assignment operator] for a class X is
7560   //   trivial if
7561   //    -- for each non-static data member of X that is of class type (or array
7562   //       thereof), the constructor selected to copy/move that member is
7563   //       trivial
7564   //
7565   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7566   //   A [default constructor or destructor] is trivial if
7567   //    -- for all of the non-static data members of its class that are of class
7568   //       type (or array thereof), each such class has a trivial [default
7569   //       constructor or destructor]
7570   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7571     return false;
7572 
7573   // C++11 [class.dtor]p5:
7574   //   A destructor is trivial if [...]
7575   //    -- the destructor is not virtual
7576   if (CSM == CXXDestructor && MD->isVirtual()) {
7577     if (Diagnose)
7578       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7579     return false;
7580   }
7581 
7582   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7583   //   A [special member] for class X is trivial if [...]
7584   //    -- class X has no virtual functions and no virtual base classes
7585   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7586     if (!Diagnose)
7587       return false;
7588 
7589     if (RD->getNumVBases()) {
7590       // Check for virtual bases. We already know that the corresponding
7591       // member in all bases is trivial, so vbases must all be direct.
7592       CXXBaseSpecifier &BS = *RD->vbases_begin();
7593       assert(BS.isVirtual());
7594       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7595       return false;
7596     }
7597 
7598     // Must have a virtual method.
7599     for (const auto *MI : RD->methods()) {
7600       if (MI->isVirtual()) {
7601         SourceLocation MLoc = MI->getBeginLoc();
7602         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7603         return false;
7604       }
7605     }
7606 
7607     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7608   }
7609 
7610   // Looks like it's trivial!
7611   return true;
7612 }
7613 
7614 namespace {
7615 struct FindHiddenVirtualMethod {
7616   Sema *S;
7617   CXXMethodDecl *Method;
7618   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7619   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7620 
7621 private:
7622   /// Check whether any most overriden method from MD in Methods
7623   static bool CheckMostOverridenMethods(
7624       const CXXMethodDecl *MD,
7625       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7626     if (MD->size_overridden_methods() == 0)
7627       return Methods.count(MD->getCanonicalDecl());
7628     for (const CXXMethodDecl *O : MD->overridden_methods())
7629       if (CheckMostOverridenMethods(O, Methods))
7630         return true;
7631     return false;
7632   }
7633 
7634 public:
7635   /// Member lookup function that determines whether a given C++
7636   /// method overloads virtual methods in a base class without overriding any,
7637   /// to be used with CXXRecordDecl::lookupInBases().
7638   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7639     RecordDecl *BaseRecord =
7640         Specifier->getType()->getAs<RecordType>()->getDecl();
7641 
7642     DeclarationName Name = Method->getDeclName();
7643     assert(Name.getNameKind() == DeclarationName::Identifier);
7644 
7645     bool foundSameNameMethod = false;
7646     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7647     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7648          Path.Decls = Path.Decls.slice(1)) {
7649       NamedDecl *D = Path.Decls.front();
7650       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7651         MD = MD->getCanonicalDecl();
7652         foundSameNameMethod = true;
7653         // Interested only in hidden virtual methods.
7654         if (!MD->isVirtual())
7655           continue;
7656         // If the method we are checking overrides a method from its base
7657         // don't warn about the other overloaded methods. Clang deviates from
7658         // GCC by only diagnosing overloads of inherited virtual functions that
7659         // do not override any other virtual functions in the base. GCC's
7660         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7661         // function from a base class. These cases may be better served by a
7662         // warning (not specific to virtual functions) on call sites when the
7663         // call would select a different function from the base class, were it
7664         // visible.
7665         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7666         if (!S->IsOverload(Method, MD, false))
7667           return true;
7668         // Collect the overload only if its hidden.
7669         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7670           overloadedMethods.push_back(MD);
7671       }
7672     }
7673 
7674     if (foundSameNameMethod)
7675       OverloadedMethods.append(overloadedMethods.begin(),
7676                                overloadedMethods.end());
7677     return foundSameNameMethod;
7678   }
7679 };
7680 } // end anonymous namespace
7681 
7682 /// Add the most overriden methods from MD to Methods
7683 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7684                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7685   if (MD->size_overridden_methods() == 0)
7686     Methods.insert(MD->getCanonicalDecl());
7687   else
7688     for (const CXXMethodDecl *O : MD->overridden_methods())
7689       AddMostOverridenMethods(O, Methods);
7690 }
7691 
7692 /// Check if a method overloads virtual methods in a base class without
7693 /// overriding any.
7694 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7695                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7696   if (!MD->getDeclName().isIdentifier())
7697     return;
7698 
7699   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7700                      /*bool RecordPaths=*/false,
7701                      /*bool DetectVirtual=*/false);
7702   FindHiddenVirtualMethod FHVM;
7703   FHVM.Method = MD;
7704   FHVM.S = this;
7705 
7706   // Keep the base methods that were overriden or introduced in the subclass
7707   // by 'using' in a set. A base method not in this set is hidden.
7708   CXXRecordDecl *DC = MD->getParent();
7709   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7710   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7711     NamedDecl *ND = *I;
7712     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7713       ND = shad->getTargetDecl();
7714     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7715       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7716   }
7717 
7718   if (DC->lookupInBases(FHVM, Paths))
7719     OverloadedMethods = FHVM.OverloadedMethods;
7720 }
7721 
7722 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7723                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7724   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7725     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7726     PartialDiagnostic PD = PDiag(
7727          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7728     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7729     Diag(overloadedMD->getLocation(), PD);
7730   }
7731 }
7732 
7733 /// Diagnose methods which overload virtual methods in a base class
7734 /// without overriding any.
7735 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7736   if (MD->isInvalidDecl())
7737     return;
7738 
7739   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7740     return;
7741 
7742   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7743   FindHiddenVirtualMethods(MD, OverloadedMethods);
7744   if (!OverloadedMethods.empty()) {
7745     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7746       << MD << (OverloadedMethods.size() > 1);
7747 
7748     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7749   }
7750 }
7751 
7752 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7753   auto PrintDiagAndRemoveAttr = [&]() {
7754     // No diagnostics if this is a template instantiation.
7755     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7756       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7757            diag::ext_cannot_use_trivial_abi) << &RD;
7758     RD.dropAttr<TrivialABIAttr>();
7759   };
7760 
7761   // Ill-formed if the struct has virtual functions.
7762   if (RD.isPolymorphic()) {
7763     PrintDiagAndRemoveAttr();
7764     return;
7765   }
7766 
7767   for (const auto &B : RD.bases()) {
7768     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7769     // virtual base.
7770     if ((!B.getType()->isDependentType() &&
7771          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7772         B.isVirtual()) {
7773       PrintDiagAndRemoveAttr();
7774       return;
7775     }
7776   }
7777 
7778   for (const auto *FD : RD.fields()) {
7779     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7780     // non-trivial for the purpose of calls.
7781     QualType FT = FD->getType();
7782     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7783       PrintDiagAndRemoveAttr();
7784       return;
7785     }
7786 
7787     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7788       if (!RT->isDependentType() &&
7789           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7790         PrintDiagAndRemoveAttr();
7791         return;
7792       }
7793   }
7794 }
7795 
7796 void Sema::ActOnFinishCXXMemberSpecification(
7797     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7798     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7799   if (!TagDecl)
7800     return;
7801 
7802   AdjustDeclIfTemplate(TagDecl);
7803 
7804   for (const ParsedAttr &AL : AttrList) {
7805     if (AL.getKind() != ParsedAttr::AT_Visibility)
7806       continue;
7807     AL.setInvalid();
7808     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7809         << AL.getName();
7810   }
7811 
7812   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7813               // strict aliasing violation!
7814               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7815               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7816 
7817   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7818 }
7819 
7820 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7821 /// special functions, such as the default constructor, copy
7822 /// constructor, or destructor, to the given C++ class (C++
7823 /// [special]p1).  This routine can only be executed just before the
7824 /// definition of the class is complete.
7825 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7826   if (ClassDecl->needsImplicitDefaultConstructor()) {
7827     ++ASTContext::NumImplicitDefaultConstructors;
7828 
7829     if (ClassDecl->hasInheritedConstructor())
7830       DeclareImplicitDefaultConstructor(ClassDecl);
7831   }
7832 
7833   if (ClassDecl->needsImplicitCopyConstructor()) {
7834     ++ASTContext::NumImplicitCopyConstructors;
7835 
7836     // If the properties or semantics of the copy constructor couldn't be
7837     // determined while the class was being declared, force a declaration
7838     // of it now.
7839     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7840         ClassDecl->hasInheritedConstructor())
7841       DeclareImplicitCopyConstructor(ClassDecl);
7842     // For the MS ABI we need to know whether the copy ctor is deleted. A
7843     // prerequisite for deleting the implicit copy ctor is that the class has a
7844     // move ctor or move assignment that is either user-declared or whose
7845     // semantics are inherited from a subobject. FIXME: We should provide a more
7846     // direct way for CodeGen to ask whether the constructor was deleted.
7847     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7848              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7849               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7850               ClassDecl->hasUserDeclaredMoveAssignment() ||
7851               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7852       DeclareImplicitCopyConstructor(ClassDecl);
7853   }
7854 
7855   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7856     ++ASTContext::NumImplicitMoveConstructors;
7857 
7858     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7859         ClassDecl->hasInheritedConstructor())
7860       DeclareImplicitMoveConstructor(ClassDecl);
7861   }
7862 
7863   if (ClassDecl->needsImplicitCopyAssignment()) {
7864     ++ASTContext::NumImplicitCopyAssignmentOperators;
7865 
7866     // If we have a dynamic class, then the copy assignment operator may be
7867     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7868     // it shows up in the right place in the vtable and that we diagnose
7869     // problems with the implicit exception specification.
7870     if (ClassDecl->isDynamicClass() ||
7871         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7872         ClassDecl->hasInheritedAssignment())
7873       DeclareImplicitCopyAssignment(ClassDecl);
7874   }
7875 
7876   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7877     ++ASTContext::NumImplicitMoveAssignmentOperators;
7878 
7879     // Likewise for the move assignment operator.
7880     if (ClassDecl->isDynamicClass() ||
7881         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7882         ClassDecl->hasInheritedAssignment())
7883       DeclareImplicitMoveAssignment(ClassDecl);
7884   }
7885 
7886   if (ClassDecl->needsImplicitDestructor()) {
7887     ++ASTContext::NumImplicitDestructors;
7888 
7889     // If we have a dynamic class, then the destructor may be virtual, so we
7890     // have to declare the destructor immediately. This ensures that, e.g., it
7891     // shows up in the right place in the vtable and that we diagnose problems
7892     // with the implicit exception specification.
7893     if (ClassDecl->isDynamicClass() ||
7894         ClassDecl->needsOverloadResolutionForDestructor())
7895       DeclareImplicitDestructor(ClassDecl);
7896   }
7897 }
7898 
7899 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7900   if (!D)
7901     return 0;
7902 
7903   // The order of template parameters is not important here. All names
7904   // get added to the same scope.
7905   SmallVector<TemplateParameterList *, 4> ParameterLists;
7906 
7907   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7908     D = TD->getTemplatedDecl();
7909 
7910   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7911     ParameterLists.push_back(PSD->getTemplateParameters());
7912 
7913   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7914     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7915       ParameterLists.push_back(DD->getTemplateParameterList(i));
7916 
7917     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7918       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7919         ParameterLists.push_back(FTD->getTemplateParameters());
7920     }
7921   }
7922 
7923   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7924     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7925       ParameterLists.push_back(TD->getTemplateParameterList(i));
7926 
7927     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7928       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7929         ParameterLists.push_back(CTD->getTemplateParameters());
7930     }
7931   }
7932 
7933   unsigned Count = 0;
7934   for (TemplateParameterList *Params : ParameterLists) {
7935     if (Params->size() > 0)
7936       // Ignore explicit specializations; they don't contribute to the template
7937       // depth.
7938       ++Count;
7939     for (NamedDecl *Param : *Params) {
7940       if (Param->getDeclName()) {
7941         S->AddDecl(Param);
7942         IdResolver.AddDecl(Param);
7943       }
7944     }
7945   }
7946 
7947   return Count;
7948 }
7949 
7950 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7951   if (!RecordD) return;
7952   AdjustDeclIfTemplate(RecordD);
7953   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7954   PushDeclContext(S, Record);
7955 }
7956 
7957 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7958   if (!RecordD) return;
7959   PopDeclContext();
7960 }
7961 
7962 /// This is used to implement the constant expression evaluation part of the
7963 /// attribute enable_if extension. There is nothing in standard C++ which would
7964 /// require reentering parameters.
7965 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7966   if (!Param)
7967     return;
7968 
7969   S->AddDecl(Param);
7970   if (Param->getDeclName())
7971     IdResolver.AddDecl(Param);
7972 }
7973 
7974 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7975 /// parsing a top-level (non-nested) C++ class, and we are now
7976 /// parsing those parts of the given Method declaration that could
7977 /// not be parsed earlier (C++ [class.mem]p2), such as default
7978 /// arguments. This action should enter the scope of the given
7979 /// Method declaration as if we had just parsed the qualified method
7980 /// name. However, it should not bring the parameters into scope;
7981 /// that will be performed by ActOnDelayedCXXMethodParameter.
7982 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7983 }
7984 
7985 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7986 /// C++ method declaration. We're (re-)introducing the given
7987 /// function parameter into scope for use in parsing later parts of
7988 /// the method declaration. For example, we could see an
7989 /// ActOnParamDefaultArgument event for this parameter.
7990 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7991   if (!ParamD)
7992     return;
7993 
7994   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7995 
7996   // If this parameter has an unparsed default argument, clear it out
7997   // to make way for the parsed default argument.
7998   if (Param->hasUnparsedDefaultArg())
7999     Param->setDefaultArg(nullptr);
8000 
8001   S->AddDecl(Param);
8002   if (Param->getDeclName())
8003     IdResolver.AddDecl(Param);
8004 }
8005 
8006 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8007 /// processing the delayed method declaration for Method. The method
8008 /// declaration is now considered finished. There may be a separate
8009 /// ActOnStartOfFunctionDef action later (not necessarily
8010 /// immediately!) for this method, if it was also defined inside the
8011 /// class body.
8012 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8013   if (!MethodD)
8014     return;
8015 
8016   AdjustDeclIfTemplate(MethodD);
8017 
8018   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8019 
8020   // Now that we have our default arguments, check the constructor
8021   // again. It could produce additional diagnostics or affect whether
8022   // the class has implicitly-declared destructors, among other
8023   // things.
8024   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8025     CheckConstructor(Constructor);
8026 
8027   // Check the default arguments, which we may have added.
8028   if (!Method->isInvalidDecl())
8029     CheckCXXDefaultArguments(Method);
8030 }
8031 
8032 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8033 /// the well-formedness of the constructor declarator @p D with type @p
8034 /// R. If there are any errors in the declarator, this routine will
8035 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8036 /// will be updated to reflect a well-formed type for the constructor and
8037 /// returned.
8038 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8039                                           StorageClass &SC) {
8040   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8041 
8042   // C++ [class.ctor]p3:
8043   //   A constructor shall not be virtual (10.3) or static (9.4). A
8044   //   constructor can be invoked for a const, volatile or const
8045   //   volatile object. A constructor shall not be declared const,
8046   //   volatile, or const volatile (9.3.2).
8047   if (isVirtual) {
8048     if (!D.isInvalidType())
8049       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8050         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8051         << SourceRange(D.getIdentifierLoc());
8052     D.setInvalidType();
8053   }
8054   if (SC == SC_Static) {
8055     if (!D.isInvalidType())
8056       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8057         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8058         << SourceRange(D.getIdentifierLoc());
8059     D.setInvalidType();
8060     SC = SC_None;
8061   }
8062 
8063   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8064     diagnoseIgnoredQualifiers(
8065         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8066         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8067         D.getDeclSpec().getRestrictSpecLoc(),
8068         D.getDeclSpec().getAtomicSpecLoc());
8069     D.setInvalidType();
8070   }
8071 
8072   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8073   if (FTI.TypeQuals != 0) {
8074     if (FTI.TypeQuals & Qualifiers::Const)
8075       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8076         << "const" << SourceRange(D.getIdentifierLoc());
8077     if (FTI.TypeQuals & Qualifiers::Volatile)
8078       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8079         << "volatile" << SourceRange(D.getIdentifierLoc());
8080     if (FTI.TypeQuals & Qualifiers::Restrict)
8081       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8082         << "restrict" << SourceRange(D.getIdentifierLoc());
8083     D.setInvalidType();
8084   }
8085 
8086   // C++0x [class.ctor]p4:
8087   //   A constructor shall not be declared with a ref-qualifier.
8088   if (FTI.hasRefQualifier()) {
8089     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8090       << FTI.RefQualifierIsLValueRef
8091       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8092     D.setInvalidType();
8093   }
8094 
8095   // Rebuild the function type "R" without any type qualifiers (in
8096   // case any of the errors above fired) and with "void" as the
8097   // return type, since constructors don't have return types.
8098   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8099   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8100     return R;
8101 
8102   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8103   EPI.TypeQuals = 0;
8104   EPI.RefQualifier = RQ_None;
8105 
8106   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8107 }
8108 
8109 /// CheckConstructor - Checks a fully-formed constructor for
8110 /// well-formedness, issuing any diagnostics required. Returns true if
8111 /// the constructor declarator is invalid.
8112 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8113   CXXRecordDecl *ClassDecl
8114     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8115   if (!ClassDecl)
8116     return Constructor->setInvalidDecl();
8117 
8118   // C++ [class.copy]p3:
8119   //   A declaration of a constructor for a class X is ill-formed if
8120   //   its first parameter is of type (optionally cv-qualified) X and
8121   //   either there are no other parameters or else all other
8122   //   parameters have default arguments.
8123   if (!Constructor->isInvalidDecl() &&
8124       ((Constructor->getNumParams() == 1) ||
8125        (Constructor->getNumParams() > 1 &&
8126         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8127       Constructor->getTemplateSpecializationKind()
8128                                               != TSK_ImplicitInstantiation) {
8129     QualType ParamType = Constructor->getParamDecl(0)->getType();
8130     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8131     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8132       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8133       const char *ConstRef
8134         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8135                                                         : " const &";
8136       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8137         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8138 
8139       // FIXME: Rather that making the constructor invalid, we should endeavor
8140       // to fix the type.
8141       Constructor->setInvalidDecl();
8142     }
8143   }
8144 }
8145 
8146 /// CheckDestructor - Checks a fully-formed destructor definition for
8147 /// well-formedness, issuing any diagnostics required.  Returns true
8148 /// on error.
8149 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8150   CXXRecordDecl *RD = Destructor->getParent();
8151 
8152   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8153     SourceLocation Loc;
8154 
8155     if (!Destructor->isImplicit())
8156       Loc = Destructor->getLocation();
8157     else
8158       Loc = RD->getLocation();
8159 
8160     // If we have a virtual destructor, look up the deallocation function
8161     if (FunctionDecl *OperatorDelete =
8162             FindDeallocationFunctionForDestructor(Loc, RD)) {
8163       Expr *ThisArg = nullptr;
8164 
8165       // If the notional 'delete this' expression requires a non-trivial
8166       // conversion from 'this' to the type of a destroying operator delete's
8167       // first parameter, perform that conversion now.
8168       if (OperatorDelete->isDestroyingOperatorDelete()) {
8169         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8170         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8171           // C++ [class.dtor]p13:
8172           //   ... as if for the expression 'delete this' appearing in a
8173           //   non-virtual destructor of the destructor's class.
8174           ContextRAII SwitchContext(*this, Destructor);
8175           ExprResult This =
8176               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8177           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8178           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8179           if (This.isInvalid()) {
8180             // FIXME: Register this as a context note so that it comes out
8181             // in the right order.
8182             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8183             return true;
8184           }
8185           ThisArg = This.get();
8186         }
8187       }
8188 
8189       MarkFunctionReferenced(Loc, OperatorDelete);
8190       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8191     }
8192   }
8193 
8194   return false;
8195 }
8196 
8197 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8198 /// the well-formednes of the destructor declarator @p D with type @p
8199 /// R. If there are any errors in the declarator, this routine will
8200 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8201 /// will be updated to reflect a well-formed type for the destructor and
8202 /// returned.
8203 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8204                                          StorageClass& SC) {
8205   // C++ [class.dtor]p1:
8206   //   [...] A typedef-name that names a class is a class-name
8207   //   (7.1.3); however, a typedef-name that names a class shall not
8208   //   be used as the identifier in the declarator for a destructor
8209   //   declaration.
8210   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8211   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8212     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8213       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8214   else if (const TemplateSpecializationType *TST =
8215              DeclaratorType->getAs<TemplateSpecializationType>())
8216     if (TST->isTypeAlias())
8217       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8218         << DeclaratorType << 1;
8219 
8220   // C++ [class.dtor]p2:
8221   //   A destructor is used to destroy objects of its class type. A
8222   //   destructor takes no parameters, and no return type can be
8223   //   specified for it (not even void). The address of a destructor
8224   //   shall not be taken. A destructor shall not be static. A
8225   //   destructor can be invoked for a const, volatile or const
8226   //   volatile object. A destructor shall not be declared const,
8227   //   volatile or const volatile (9.3.2).
8228   if (SC == SC_Static) {
8229     if (!D.isInvalidType())
8230       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8231         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8232         << SourceRange(D.getIdentifierLoc())
8233         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8234 
8235     SC = SC_None;
8236   }
8237   if (!D.isInvalidType()) {
8238     // Destructors don't have return types, but the parser will
8239     // happily parse something like:
8240     //
8241     //   class X {
8242     //     float ~X();
8243     //   };
8244     //
8245     // The return type will be eliminated later.
8246     if (D.getDeclSpec().hasTypeSpecifier())
8247       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8248         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8249         << SourceRange(D.getIdentifierLoc());
8250     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8251       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8252                                 SourceLocation(),
8253                                 D.getDeclSpec().getConstSpecLoc(),
8254                                 D.getDeclSpec().getVolatileSpecLoc(),
8255                                 D.getDeclSpec().getRestrictSpecLoc(),
8256                                 D.getDeclSpec().getAtomicSpecLoc());
8257       D.setInvalidType();
8258     }
8259   }
8260 
8261   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8262   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8263     if (FTI.TypeQuals & Qualifiers::Const)
8264       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8265         << "const" << SourceRange(D.getIdentifierLoc());
8266     if (FTI.TypeQuals & Qualifiers::Volatile)
8267       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8268         << "volatile" << SourceRange(D.getIdentifierLoc());
8269     if (FTI.TypeQuals & Qualifiers::Restrict)
8270       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8271         << "restrict" << SourceRange(D.getIdentifierLoc());
8272     D.setInvalidType();
8273   }
8274 
8275   // C++0x [class.dtor]p2:
8276   //   A destructor shall not be declared with a ref-qualifier.
8277   if (FTI.hasRefQualifier()) {
8278     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8279       << FTI.RefQualifierIsLValueRef
8280       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8281     D.setInvalidType();
8282   }
8283 
8284   // Make sure we don't have any parameters.
8285   if (FTIHasNonVoidParameters(FTI)) {
8286     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8287 
8288     // Delete the parameters.
8289     FTI.freeParams();
8290     D.setInvalidType();
8291   }
8292 
8293   // Make sure the destructor isn't variadic.
8294   if (FTI.isVariadic) {
8295     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8296     D.setInvalidType();
8297   }
8298 
8299   // Rebuild the function type "R" without any type qualifiers or
8300   // parameters (in case any of the errors above fired) and with
8301   // "void" as the return type, since destructors don't have return
8302   // types.
8303   if (!D.isInvalidType())
8304     return R;
8305 
8306   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8307   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8308   EPI.Variadic = false;
8309   EPI.TypeQuals = 0;
8310   EPI.RefQualifier = RQ_None;
8311   return Context.getFunctionType(Context.VoidTy, None, EPI);
8312 }
8313 
8314 static void extendLeft(SourceRange &R, SourceRange Before) {
8315   if (Before.isInvalid())
8316     return;
8317   R.setBegin(Before.getBegin());
8318   if (R.getEnd().isInvalid())
8319     R.setEnd(Before.getEnd());
8320 }
8321 
8322 static void extendRight(SourceRange &R, SourceRange After) {
8323   if (After.isInvalid())
8324     return;
8325   if (R.getBegin().isInvalid())
8326     R.setBegin(After.getBegin());
8327   R.setEnd(After.getEnd());
8328 }
8329 
8330 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8331 /// well-formednes of the conversion function declarator @p D with
8332 /// type @p R. If there are any errors in the declarator, this routine
8333 /// will emit diagnostics and return true. Otherwise, it will return
8334 /// false. Either way, the type @p R will be updated to reflect a
8335 /// well-formed type for the conversion operator.
8336 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8337                                      StorageClass& SC) {
8338   // C++ [class.conv.fct]p1:
8339   //   Neither parameter types nor return type can be specified. The
8340   //   type of a conversion function (8.3.5) is "function taking no
8341   //   parameter returning conversion-type-id."
8342   if (SC == SC_Static) {
8343     if (!D.isInvalidType())
8344       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8345         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8346         << D.getName().getSourceRange();
8347     D.setInvalidType();
8348     SC = SC_None;
8349   }
8350 
8351   TypeSourceInfo *ConvTSI = nullptr;
8352   QualType ConvType =
8353       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8354 
8355   const DeclSpec &DS = D.getDeclSpec();
8356   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8357     // Conversion functions don't have return types, but the parser will
8358     // happily parse something like:
8359     //
8360     //   class X {
8361     //     float operator bool();
8362     //   };
8363     //
8364     // The return type will be changed later anyway.
8365     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8366       << SourceRange(DS.getTypeSpecTypeLoc())
8367       << SourceRange(D.getIdentifierLoc());
8368     D.setInvalidType();
8369   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8370     // It's also plausible that the user writes type qualifiers in the wrong
8371     // place, such as:
8372     //   struct S { const operator int(); };
8373     // FIXME: we could provide a fixit to move the qualifiers onto the
8374     // conversion type.
8375     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8376         << SourceRange(D.getIdentifierLoc()) << 0;
8377     D.setInvalidType();
8378   }
8379 
8380   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8381 
8382   // Make sure we don't have any parameters.
8383   if (Proto->getNumParams() > 0) {
8384     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8385 
8386     // Delete the parameters.
8387     D.getFunctionTypeInfo().freeParams();
8388     D.setInvalidType();
8389   } else if (Proto->isVariadic()) {
8390     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8391     D.setInvalidType();
8392   }
8393 
8394   // Diagnose "&operator bool()" and other such nonsense.  This
8395   // is actually a gcc extension which we don't support.
8396   if (Proto->getReturnType() != ConvType) {
8397     bool NeedsTypedef = false;
8398     SourceRange Before, After;
8399 
8400     // Walk the chunks and extract information on them for our diagnostic.
8401     bool PastFunctionChunk = false;
8402     for (auto &Chunk : D.type_objects()) {
8403       switch (Chunk.Kind) {
8404       case DeclaratorChunk::Function:
8405         if (!PastFunctionChunk) {
8406           if (Chunk.Fun.HasTrailingReturnType) {
8407             TypeSourceInfo *TRT = nullptr;
8408             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8409             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8410           }
8411           PastFunctionChunk = true;
8412           break;
8413         }
8414         LLVM_FALLTHROUGH;
8415       case DeclaratorChunk::Array:
8416         NeedsTypedef = true;
8417         extendRight(After, Chunk.getSourceRange());
8418         break;
8419 
8420       case DeclaratorChunk::Pointer:
8421       case DeclaratorChunk::BlockPointer:
8422       case DeclaratorChunk::Reference:
8423       case DeclaratorChunk::MemberPointer:
8424       case DeclaratorChunk::Pipe:
8425         extendLeft(Before, Chunk.getSourceRange());
8426         break;
8427 
8428       case DeclaratorChunk::Paren:
8429         extendLeft(Before, Chunk.Loc);
8430         extendRight(After, Chunk.EndLoc);
8431         break;
8432       }
8433     }
8434 
8435     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8436                          After.isValid()  ? After.getBegin() :
8437                                             D.getIdentifierLoc();
8438     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8439     DB << Before << After;
8440 
8441     if (!NeedsTypedef) {
8442       DB << /*don't need a typedef*/0;
8443 
8444       // If we can provide a correct fix-it hint, do so.
8445       if (After.isInvalid() && ConvTSI) {
8446         SourceLocation InsertLoc =
8447             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8448         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8449            << FixItHint::CreateInsertionFromRange(
8450                   InsertLoc, CharSourceRange::getTokenRange(Before))
8451            << FixItHint::CreateRemoval(Before);
8452       }
8453     } else if (!Proto->getReturnType()->isDependentType()) {
8454       DB << /*typedef*/1 << Proto->getReturnType();
8455     } else if (getLangOpts().CPlusPlus11) {
8456       DB << /*alias template*/2 << Proto->getReturnType();
8457     } else {
8458       DB << /*might not be fixable*/3;
8459     }
8460 
8461     // Recover by incorporating the other type chunks into the result type.
8462     // Note, this does *not* change the name of the function. This is compatible
8463     // with the GCC extension:
8464     //   struct S { &operator int(); } s;
8465     //   int &r = s.operator int(); // ok in GCC
8466     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8467     ConvType = Proto->getReturnType();
8468   }
8469 
8470   // C++ [class.conv.fct]p4:
8471   //   The conversion-type-id shall not represent a function type nor
8472   //   an array type.
8473   if (ConvType->isArrayType()) {
8474     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8475     ConvType = Context.getPointerType(ConvType);
8476     D.setInvalidType();
8477   } else if (ConvType->isFunctionType()) {
8478     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8479     ConvType = Context.getPointerType(ConvType);
8480     D.setInvalidType();
8481   }
8482 
8483   // Rebuild the function type "R" without any parameters (in case any
8484   // of the errors above fired) and with the conversion type as the
8485   // return type.
8486   if (D.isInvalidType())
8487     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8488 
8489   // C++0x explicit conversion operators.
8490   if (DS.isExplicitSpecified())
8491     Diag(DS.getExplicitSpecLoc(),
8492          getLangOpts().CPlusPlus11
8493              ? diag::warn_cxx98_compat_explicit_conversion_functions
8494              : diag::ext_explicit_conversion_functions)
8495         << SourceRange(DS.getExplicitSpecLoc());
8496 }
8497 
8498 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8499 /// the declaration of the given C++ conversion function. This routine
8500 /// is responsible for recording the conversion function in the C++
8501 /// class, if possible.
8502 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8503   assert(Conversion && "Expected to receive a conversion function declaration");
8504 
8505   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8506 
8507   // Make sure we aren't redeclaring the conversion function.
8508   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8509 
8510   // C++ [class.conv.fct]p1:
8511   //   [...] A conversion function is never used to convert a
8512   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8513   //   same object type (or a reference to it), to a (possibly
8514   //   cv-qualified) base class of that type (or a reference to it),
8515   //   or to (possibly cv-qualified) void.
8516   // FIXME: Suppress this warning if the conversion function ends up being a
8517   // virtual function that overrides a virtual function in a base class.
8518   QualType ClassType
8519     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8520   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8521     ConvType = ConvTypeRef->getPointeeType();
8522   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8523       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8524     /* Suppress diagnostics for instantiations. */;
8525   else if (ConvType->isRecordType()) {
8526     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8527     if (ConvType == ClassType)
8528       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8529         << ClassType;
8530     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8531       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8532         <<  ClassType << ConvType;
8533   } else if (ConvType->isVoidType()) {
8534     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8535       << ClassType << ConvType;
8536   }
8537 
8538   if (FunctionTemplateDecl *ConversionTemplate
8539                                 = Conversion->getDescribedFunctionTemplate())
8540     return ConversionTemplate;
8541 
8542   return Conversion;
8543 }
8544 
8545 namespace {
8546 /// Utility class to accumulate and print a diagnostic listing the invalid
8547 /// specifier(s) on a declaration.
8548 struct BadSpecifierDiagnoser {
8549   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8550       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8551   ~BadSpecifierDiagnoser() {
8552     Diagnostic << Specifiers;
8553   }
8554 
8555   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8556     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8557   }
8558   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8559     return check(SpecLoc,
8560                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8561   }
8562   void check(SourceLocation SpecLoc, const char *Spec) {
8563     if (SpecLoc.isInvalid()) return;
8564     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8565     if (!Specifiers.empty()) Specifiers += " ";
8566     Specifiers += Spec;
8567   }
8568 
8569   Sema &S;
8570   Sema::SemaDiagnosticBuilder Diagnostic;
8571   std::string Specifiers;
8572 };
8573 }
8574 
8575 /// Check the validity of a declarator that we parsed for a deduction-guide.
8576 /// These aren't actually declarators in the grammar, so we need to check that
8577 /// the user didn't specify any pieces that are not part of the deduction-guide
8578 /// grammar.
8579 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8580                                          StorageClass &SC) {
8581   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8582   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8583   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8584 
8585   // C++ [temp.deduct.guide]p3:
8586   //   A deduction-gide shall be declared in the same scope as the
8587   //   corresponding class template.
8588   if (!CurContext->getRedeclContext()->Equals(
8589           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8590     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8591       << GuidedTemplateDecl;
8592     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8593   }
8594 
8595   auto &DS = D.getMutableDeclSpec();
8596   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8597   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8598       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8599       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8600     BadSpecifierDiagnoser Diagnoser(
8601         *this, D.getIdentifierLoc(),
8602         diag::err_deduction_guide_invalid_specifier);
8603 
8604     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8605     DS.ClearStorageClassSpecs();
8606     SC = SC_None;
8607 
8608     // 'explicit' is permitted.
8609     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8610     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8611     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8612     DS.ClearConstexprSpec();
8613 
8614     Diagnoser.check(DS.getConstSpecLoc(), "const");
8615     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8616     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8617     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8618     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8619     DS.ClearTypeQualifiers();
8620 
8621     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8622     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8623     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8624     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8625     DS.ClearTypeSpecType();
8626   }
8627 
8628   if (D.isInvalidType())
8629     return;
8630 
8631   // Check the declarator is simple enough.
8632   bool FoundFunction = false;
8633   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8634     if (Chunk.Kind == DeclaratorChunk::Paren)
8635       continue;
8636     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8637       Diag(D.getDeclSpec().getBeginLoc(),
8638            diag::err_deduction_guide_with_complex_decl)
8639           << D.getSourceRange();
8640       break;
8641     }
8642     if (!Chunk.Fun.hasTrailingReturnType()) {
8643       Diag(D.getName().getBeginLoc(),
8644            diag::err_deduction_guide_no_trailing_return_type);
8645       break;
8646     }
8647 
8648     // Check that the return type is written as a specialization of
8649     // the template specified as the deduction-guide's name.
8650     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8651     TypeSourceInfo *TSI = nullptr;
8652     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8653     assert(TSI && "deduction guide has valid type but invalid return type?");
8654     bool AcceptableReturnType = false;
8655     bool MightInstantiateToSpecialization = false;
8656     if (auto RetTST =
8657             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8658       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8659       bool TemplateMatches =
8660           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8661       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8662         AcceptableReturnType = true;
8663       else {
8664         // This could still instantiate to the right type, unless we know it
8665         // names the wrong class template.
8666         auto *TD = SpecifiedName.getAsTemplateDecl();
8667         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8668                                              !TemplateMatches);
8669       }
8670     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8671       MightInstantiateToSpecialization = true;
8672     }
8673 
8674     if (!AcceptableReturnType) {
8675       Diag(TSI->getTypeLoc().getBeginLoc(),
8676            diag::err_deduction_guide_bad_trailing_return_type)
8677           << GuidedTemplate << TSI->getType()
8678           << MightInstantiateToSpecialization
8679           << TSI->getTypeLoc().getSourceRange();
8680     }
8681 
8682     // Keep going to check that we don't have any inner declarator pieces (we
8683     // could still have a function returning a pointer to a function).
8684     FoundFunction = true;
8685   }
8686 
8687   if (D.isFunctionDefinition())
8688     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8689 }
8690 
8691 //===----------------------------------------------------------------------===//
8692 // Namespace Handling
8693 //===----------------------------------------------------------------------===//
8694 
8695 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8696 /// reopened.
8697 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8698                                             SourceLocation Loc,
8699                                             IdentifierInfo *II, bool *IsInline,
8700                                             NamespaceDecl *PrevNS) {
8701   assert(*IsInline != PrevNS->isInline());
8702 
8703   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8704   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8705   // inline namespaces, with the intention of bringing names into namespace std.
8706   //
8707   // We support this just well enough to get that case working; this is not
8708   // sufficient to support reopening namespaces as inline in general.
8709   if (*IsInline && II && II->getName().startswith("__atomic") &&
8710       S.getSourceManager().isInSystemHeader(Loc)) {
8711     // Mark all prior declarations of the namespace as inline.
8712     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8713          NS = NS->getPreviousDecl())
8714       NS->setInline(*IsInline);
8715     // Patch up the lookup table for the containing namespace. This isn't really
8716     // correct, but it's good enough for this particular case.
8717     for (auto *I : PrevNS->decls())
8718       if (auto *ND = dyn_cast<NamedDecl>(I))
8719         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8720     return;
8721   }
8722 
8723   if (PrevNS->isInline())
8724     // The user probably just forgot the 'inline', so suggest that it
8725     // be added back.
8726     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8727       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8728   else
8729     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8730 
8731   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8732   *IsInline = PrevNS->isInline();
8733 }
8734 
8735 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8736 /// definition.
8737 Decl *Sema::ActOnStartNamespaceDef(
8738     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8739     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8740     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8741   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8742   // For anonymous namespace, take the location of the left brace.
8743   SourceLocation Loc = II ? IdentLoc : LBrace;
8744   bool IsInline = InlineLoc.isValid();
8745   bool IsInvalid = false;
8746   bool IsStd = false;
8747   bool AddToKnown = false;
8748   Scope *DeclRegionScope = NamespcScope->getParent();
8749 
8750   NamespaceDecl *PrevNS = nullptr;
8751   if (II) {
8752     // C++ [namespace.def]p2:
8753     //   The identifier in an original-namespace-definition shall not
8754     //   have been previously defined in the declarative region in
8755     //   which the original-namespace-definition appears. The
8756     //   identifier in an original-namespace-definition is the name of
8757     //   the namespace. Subsequently in that declarative region, it is
8758     //   treated as an original-namespace-name.
8759     //
8760     // Since namespace names are unique in their scope, and we don't
8761     // look through using directives, just look for any ordinary names
8762     // as if by qualified name lookup.
8763     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8764                    ForExternalRedeclaration);
8765     LookupQualifiedName(R, CurContext->getRedeclContext());
8766     NamedDecl *PrevDecl =
8767         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8768     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8769 
8770     if (PrevNS) {
8771       // This is an extended namespace definition.
8772       if (IsInline != PrevNS->isInline())
8773         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8774                                         &IsInline, PrevNS);
8775     } else if (PrevDecl) {
8776       // This is an invalid name redefinition.
8777       Diag(Loc, diag::err_redefinition_different_kind)
8778         << II;
8779       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8780       IsInvalid = true;
8781       // Continue on to push Namespc as current DeclContext and return it.
8782     } else if (II->isStr("std") &&
8783                CurContext->getRedeclContext()->isTranslationUnit()) {
8784       // This is the first "real" definition of the namespace "std", so update
8785       // our cache of the "std" namespace to point at this definition.
8786       PrevNS = getStdNamespace();
8787       IsStd = true;
8788       AddToKnown = !IsInline;
8789     } else {
8790       // We've seen this namespace for the first time.
8791       AddToKnown = !IsInline;
8792     }
8793   } else {
8794     // Anonymous namespaces.
8795 
8796     // Determine whether the parent already has an anonymous namespace.
8797     DeclContext *Parent = CurContext->getRedeclContext();
8798     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8799       PrevNS = TU->getAnonymousNamespace();
8800     } else {
8801       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8802       PrevNS = ND->getAnonymousNamespace();
8803     }
8804 
8805     if (PrevNS && IsInline != PrevNS->isInline())
8806       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8807                                       &IsInline, PrevNS);
8808   }
8809 
8810   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8811                                                  StartLoc, Loc, II, PrevNS);
8812   if (IsInvalid)
8813     Namespc->setInvalidDecl();
8814 
8815   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8816   AddPragmaAttributes(DeclRegionScope, Namespc);
8817 
8818   // FIXME: Should we be merging attributes?
8819   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8820     PushNamespaceVisibilityAttr(Attr, Loc);
8821 
8822   if (IsStd)
8823     StdNamespace = Namespc;
8824   if (AddToKnown)
8825     KnownNamespaces[Namespc] = false;
8826 
8827   if (II) {
8828     PushOnScopeChains(Namespc, DeclRegionScope);
8829   } else {
8830     // Link the anonymous namespace into its parent.
8831     DeclContext *Parent = CurContext->getRedeclContext();
8832     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8833       TU->setAnonymousNamespace(Namespc);
8834     } else {
8835       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8836     }
8837 
8838     CurContext->addDecl(Namespc);
8839 
8840     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8841     //   behaves as if it were replaced by
8842     //     namespace unique { /* empty body */ }
8843     //     using namespace unique;
8844     //     namespace unique { namespace-body }
8845     //   where all occurrences of 'unique' in a translation unit are
8846     //   replaced by the same identifier and this identifier differs
8847     //   from all other identifiers in the entire program.
8848 
8849     // We just create the namespace with an empty name and then add an
8850     // implicit using declaration, just like the standard suggests.
8851     //
8852     // CodeGen enforces the "universally unique" aspect by giving all
8853     // declarations semantically contained within an anonymous
8854     // namespace internal linkage.
8855 
8856     if (!PrevNS) {
8857       UD = UsingDirectiveDecl::Create(Context, Parent,
8858                                       /* 'using' */ LBrace,
8859                                       /* 'namespace' */ SourceLocation(),
8860                                       /* qualifier */ NestedNameSpecifierLoc(),
8861                                       /* identifier */ SourceLocation(),
8862                                       Namespc,
8863                                       /* Ancestor */ Parent);
8864       UD->setImplicit();
8865       Parent->addDecl(UD);
8866     }
8867   }
8868 
8869   ActOnDocumentableDecl(Namespc);
8870 
8871   // Although we could have an invalid decl (i.e. the namespace name is a
8872   // redefinition), push it as current DeclContext and try to continue parsing.
8873   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8874   // for the namespace has the declarations that showed up in that particular
8875   // namespace definition.
8876   PushDeclContext(NamespcScope, Namespc);
8877   return Namespc;
8878 }
8879 
8880 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8881 /// is a namespace alias, returns the namespace it points to.
8882 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8883   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8884     return AD->getNamespace();
8885   return dyn_cast_or_null<NamespaceDecl>(D);
8886 }
8887 
8888 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8889 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8890 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8891   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8892   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8893   Namespc->setRBraceLoc(RBrace);
8894   PopDeclContext();
8895   if (Namespc->hasAttr<VisibilityAttr>())
8896     PopPragmaVisibility(true, RBrace);
8897 }
8898 
8899 CXXRecordDecl *Sema::getStdBadAlloc() const {
8900   return cast_or_null<CXXRecordDecl>(
8901                                   StdBadAlloc.get(Context.getExternalSource()));
8902 }
8903 
8904 EnumDecl *Sema::getStdAlignValT() const {
8905   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8906 }
8907 
8908 NamespaceDecl *Sema::getStdNamespace() const {
8909   return cast_or_null<NamespaceDecl>(
8910                                  StdNamespace.get(Context.getExternalSource()));
8911 }
8912 
8913 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8914   if (!StdExperimentalNamespaceCache) {
8915     if (auto Std = getStdNamespace()) {
8916       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8917                           SourceLocation(), LookupNamespaceName);
8918       if (!LookupQualifiedName(Result, Std) ||
8919           !(StdExperimentalNamespaceCache =
8920                 Result.getAsSingle<NamespaceDecl>()))
8921         Result.suppressDiagnostics();
8922     }
8923   }
8924   return StdExperimentalNamespaceCache;
8925 }
8926 
8927 namespace {
8928 
8929 enum UnsupportedSTLSelect {
8930   USS_InvalidMember,
8931   USS_MissingMember,
8932   USS_NonTrivial,
8933   USS_Other
8934 };
8935 
8936 struct InvalidSTLDiagnoser {
8937   Sema &S;
8938   SourceLocation Loc;
8939   QualType TyForDiags;
8940 
8941   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
8942                       const VarDecl *VD = nullptr) {
8943     {
8944       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
8945                << TyForDiags << ((int)Sel);
8946       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
8947         assert(!Name.empty());
8948         D << Name;
8949       }
8950     }
8951     if (Sel == USS_InvalidMember) {
8952       S.Diag(VD->getLocation(), diag::note_var_declared_here)
8953           << VD << VD->getSourceRange();
8954     }
8955     return QualType();
8956   }
8957 };
8958 } // namespace
8959 
8960 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
8961                                            SourceLocation Loc) {
8962   assert(getLangOpts().CPlusPlus &&
8963          "Looking for comparison category type outside of C++.");
8964 
8965   // Check if we've already successfully checked the comparison category type
8966   // before. If so, skip checking it again.
8967   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
8968   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
8969     return Info->getType();
8970 
8971   // If lookup failed
8972   if (!Info) {
8973     std::string NameForDiags = "std::";
8974     NameForDiags += ComparisonCategories::getCategoryString(Kind);
8975     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
8976         << NameForDiags;
8977     return QualType();
8978   }
8979 
8980   assert(Info->Kind == Kind);
8981   assert(Info->Record);
8982 
8983   // Update the Record decl in case we encountered a forward declaration on our
8984   // first pass. FIXME: This is a bit of a hack.
8985   if (Info->Record->hasDefinition())
8986     Info->Record = Info->Record->getDefinition();
8987 
8988   // Use an elaborated type for diagnostics which has a name containing the
8989   // prepended 'std' namespace but not any inline namespace names.
8990   QualType TyForDiags = [&]() {
8991     auto *NNS =
8992         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
8993     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
8994   }();
8995 
8996   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
8997     return QualType();
8998 
8999   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9000 
9001   if (!Info->Record->isTriviallyCopyable())
9002     return UnsupportedSTLError(USS_NonTrivial);
9003 
9004   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9005     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9006     // Tolerate empty base classes.
9007     if (Base->isEmpty())
9008       continue;
9009     // Reject STL implementations which have at least one non-empty base.
9010     return UnsupportedSTLError();
9011   }
9012 
9013   // Check that the STL has implemented the types using a single integer field.
9014   // This expectation allows better codegen for builtin operators. We require:
9015   //   (1) The class has exactly one field.
9016   //   (2) The field is an integral or enumeration type.
9017   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9018   if (std::distance(FIt, FEnd) != 1 ||
9019       !FIt->getType()->isIntegralOrEnumerationType()) {
9020     return UnsupportedSTLError();
9021   }
9022 
9023   // Build each of the require values and store them in Info.
9024   for (ComparisonCategoryResult CCR :
9025        ComparisonCategories::getPossibleResultsForType(Kind)) {
9026     StringRef MemName = ComparisonCategories::getResultString(CCR);
9027     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9028 
9029     if (!ValInfo)
9030       return UnsupportedSTLError(USS_MissingMember, MemName);
9031 
9032     VarDecl *VD = ValInfo->VD;
9033     assert(VD && "should not be null!");
9034 
9035     // Attempt to diagnose reasons why the STL definition of this type
9036     // might be foobar, including it failing to be a constant expression.
9037     // TODO Handle more ways the lookup or result can be invalid.
9038     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9039         !VD->checkInitIsICE())
9040       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9041 
9042     // Attempt to evaluate the var decl as a constant expression and extract
9043     // the value of its first field as a ICE. If this fails, the STL
9044     // implementation is not supported.
9045     if (!ValInfo->hasValidIntValue())
9046       return UnsupportedSTLError();
9047 
9048     MarkVariableReferenced(Loc, VD);
9049   }
9050 
9051   // We've successfully built the required types and expressions. Update
9052   // the cache and return the newly cached value.
9053   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9054   return Info->getType();
9055 }
9056 
9057 /// Retrieve the special "std" namespace, which may require us to
9058 /// implicitly define the namespace.
9059 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9060   if (!StdNamespace) {
9061     // The "std" namespace has not yet been defined, so build one implicitly.
9062     StdNamespace = NamespaceDecl::Create(Context,
9063                                          Context.getTranslationUnitDecl(),
9064                                          /*Inline=*/false,
9065                                          SourceLocation(), SourceLocation(),
9066                                          &PP.getIdentifierTable().get("std"),
9067                                          /*PrevDecl=*/nullptr);
9068     getStdNamespace()->setImplicit(true);
9069   }
9070 
9071   return getStdNamespace();
9072 }
9073 
9074 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9075   assert(getLangOpts().CPlusPlus &&
9076          "Looking for std::initializer_list outside of C++.");
9077 
9078   // We're looking for implicit instantiations of
9079   // template <typename E> class std::initializer_list.
9080 
9081   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9082     return false;
9083 
9084   ClassTemplateDecl *Template = nullptr;
9085   const TemplateArgument *Arguments = nullptr;
9086 
9087   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9088 
9089     ClassTemplateSpecializationDecl *Specialization =
9090         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9091     if (!Specialization)
9092       return false;
9093 
9094     Template = Specialization->getSpecializedTemplate();
9095     Arguments = Specialization->getTemplateArgs().data();
9096   } else if (const TemplateSpecializationType *TST =
9097                  Ty->getAs<TemplateSpecializationType>()) {
9098     Template = dyn_cast_or_null<ClassTemplateDecl>(
9099         TST->getTemplateName().getAsTemplateDecl());
9100     Arguments = TST->getArgs();
9101   }
9102   if (!Template)
9103     return false;
9104 
9105   if (!StdInitializerList) {
9106     // Haven't recognized std::initializer_list yet, maybe this is it.
9107     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9108     if (TemplateClass->getIdentifier() !=
9109             &PP.getIdentifierTable().get("initializer_list") ||
9110         !getStdNamespace()->InEnclosingNamespaceSetOf(
9111             TemplateClass->getDeclContext()))
9112       return false;
9113     // This is a template called std::initializer_list, but is it the right
9114     // template?
9115     TemplateParameterList *Params = Template->getTemplateParameters();
9116     if (Params->getMinRequiredArguments() != 1)
9117       return false;
9118     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9119       return false;
9120 
9121     // It's the right template.
9122     StdInitializerList = Template;
9123   }
9124 
9125   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9126     return false;
9127 
9128   // This is an instance of std::initializer_list. Find the argument type.
9129   if (Element)
9130     *Element = Arguments[0].getAsType();
9131   return true;
9132 }
9133 
9134 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9135   NamespaceDecl *Std = S.getStdNamespace();
9136   if (!Std) {
9137     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9138     return nullptr;
9139   }
9140 
9141   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9142                       Loc, Sema::LookupOrdinaryName);
9143   if (!S.LookupQualifiedName(Result, Std)) {
9144     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9145     return nullptr;
9146   }
9147   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9148   if (!Template) {
9149     Result.suppressDiagnostics();
9150     // We found something weird. Complain about the first thing we found.
9151     NamedDecl *Found = *Result.begin();
9152     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9153     return nullptr;
9154   }
9155 
9156   // We found some template called std::initializer_list. Now verify that it's
9157   // correct.
9158   TemplateParameterList *Params = Template->getTemplateParameters();
9159   if (Params->getMinRequiredArguments() != 1 ||
9160       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9161     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9162     return nullptr;
9163   }
9164 
9165   return Template;
9166 }
9167 
9168 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9169   if (!StdInitializerList) {
9170     StdInitializerList = LookupStdInitializerList(*this, Loc);
9171     if (!StdInitializerList)
9172       return QualType();
9173   }
9174 
9175   TemplateArgumentListInfo Args(Loc, Loc);
9176   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9177                                        Context.getTrivialTypeSourceInfo(Element,
9178                                                                         Loc)));
9179   return Context.getCanonicalType(
9180       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9181 }
9182 
9183 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9184   // C++ [dcl.init.list]p2:
9185   //   A constructor is an initializer-list constructor if its first parameter
9186   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9187   //   std::initializer_list<E> for some type E, and either there are no other
9188   //   parameters or else all other parameters have default arguments.
9189   if (Ctor->getNumParams() < 1 ||
9190       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9191     return false;
9192 
9193   QualType ArgType = Ctor->getParamDecl(0)->getType();
9194   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9195     ArgType = RT->getPointeeType().getUnqualifiedType();
9196 
9197   return isStdInitializerList(ArgType, nullptr);
9198 }
9199 
9200 /// Determine whether a using statement is in a context where it will be
9201 /// apply in all contexts.
9202 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9203   switch (CurContext->getDeclKind()) {
9204     case Decl::TranslationUnit:
9205       return true;
9206     case Decl::LinkageSpec:
9207       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9208     default:
9209       return false;
9210   }
9211 }
9212 
9213 namespace {
9214 
9215 // Callback to only accept typo corrections that are namespaces.
9216 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9217 public:
9218   bool ValidateCandidate(const TypoCorrection &candidate) override {
9219     if (NamedDecl *ND = candidate.getCorrectionDecl())
9220       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9221     return false;
9222   }
9223 };
9224 
9225 }
9226 
9227 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9228                                        CXXScopeSpec &SS,
9229                                        SourceLocation IdentLoc,
9230                                        IdentifierInfo *Ident) {
9231   R.clear();
9232   if (TypoCorrection Corrected =
9233           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9234                         llvm::make_unique<NamespaceValidatorCCC>(),
9235                         Sema::CTK_ErrorRecovery)) {
9236     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9237       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9238       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9239                               Ident->getName().equals(CorrectedStr);
9240       S.diagnoseTypo(Corrected,
9241                      S.PDiag(diag::err_using_directive_member_suggest)
9242                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9243                      S.PDiag(diag::note_namespace_defined_here));
9244     } else {
9245       S.diagnoseTypo(Corrected,
9246                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9247                      S.PDiag(diag::note_namespace_defined_here));
9248     }
9249     R.addDecl(Corrected.getFoundDecl());
9250     return true;
9251   }
9252   return false;
9253 }
9254 
9255 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9256                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9257                                 SourceLocation IdentLoc,
9258                                 IdentifierInfo *NamespcName,
9259                                 const ParsedAttributesView &AttrList) {
9260   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9261   assert(NamespcName && "Invalid NamespcName.");
9262   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9263 
9264   // This can only happen along a recovery path.
9265   while (S->isTemplateParamScope())
9266     S = S->getParent();
9267   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9268 
9269   UsingDirectiveDecl *UDir = nullptr;
9270   NestedNameSpecifier *Qualifier = nullptr;
9271   if (SS.isSet())
9272     Qualifier = SS.getScopeRep();
9273 
9274   // Lookup namespace name.
9275   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9276   LookupParsedName(R, S, &SS);
9277   if (R.isAmbiguous())
9278     return nullptr;
9279 
9280   if (R.empty()) {
9281     R.clear();
9282     // Allow "using namespace std;" or "using namespace ::std;" even if
9283     // "std" hasn't been defined yet, for GCC compatibility.
9284     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9285         NamespcName->isStr("std")) {
9286       Diag(IdentLoc, diag::ext_using_undefined_std);
9287       R.addDecl(getOrCreateStdNamespace());
9288       R.resolveKind();
9289     }
9290     // Otherwise, attempt typo correction.
9291     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9292   }
9293 
9294   if (!R.empty()) {
9295     NamedDecl *Named = R.getRepresentativeDecl();
9296     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9297     assert(NS && "expected namespace decl");
9298 
9299     // The use of a nested name specifier may trigger deprecation warnings.
9300     DiagnoseUseOfDecl(Named, IdentLoc);
9301 
9302     // C++ [namespace.udir]p1:
9303     //   A using-directive specifies that the names in the nominated
9304     //   namespace can be used in the scope in which the
9305     //   using-directive appears after the using-directive. During
9306     //   unqualified name lookup (3.4.1), the names appear as if they
9307     //   were declared in the nearest enclosing namespace which
9308     //   contains both the using-directive and the nominated
9309     //   namespace. [Note: in this context, "contains" means "contains
9310     //   directly or indirectly". ]
9311 
9312     // Find enclosing context containing both using-directive and
9313     // nominated namespace.
9314     DeclContext *CommonAncestor = NS;
9315     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9316       CommonAncestor = CommonAncestor->getParent();
9317 
9318     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9319                                       SS.getWithLocInContext(Context),
9320                                       IdentLoc, Named, CommonAncestor);
9321 
9322     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9323         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9324       Diag(IdentLoc, diag::warn_using_directive_in_header);
9325     }
9326 
9327     PushUsingDirective(S, UDir);
9328   } else {
9329     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9330   }
9331 
9332   if (UDir)
9333     ProcessDeclAttributeList(S, UDir, AttrList);
9334 
9335   return UDir;
9336 }
9337 
9338 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9339   // If the scope has an associated entity and the using directive is at
9340   // namespace or translation unit scope, add the UsingDirectiveDecl into
9341   // its lookup structure so qualified name lookup can find it.
9342   DeclContext *Ctx = S->getEntity();
9343   if (Ctx && !Ctx->isFunctionOrMethod())
9344     Ctx->addDecl(UDir);
9345   else
9346     // Otherwise, it is at block scope. The using-directives will affect lookup
9347     // only to the end of the scope.
9348     S->PushUsingDirective(UDir);
9349 }
9350 
9351 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9352                                   SourceLocation UsingLoc,
9353                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9354                                   UnqualifiedId &Name,
9355                                   SourceLocation EllipsisLoc,
9356                                   const ParsedAttributesView &AttrList) {
9357   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9358 
9359   if (SS.isEmpty()) {
9360     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9361     return nullptr;
9362   }
9363 
9364   switch (Name.getKind()) {
9365   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9366   case UnqualifiedIdKind::IK_Identifier:
9367   case UnqualifiedIdKind::IK_OperatorFunctionId:
9368   case UnqualifiedIdKind::IK_LiteralOperatorId:
9369   case UnqualifiedIdKind::IK_ConversionFunctionId:
9370     break;
9371 
9372   case UnqualifiedIdKind::IK_ConstructorName:
9373   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9374     // C++11 inheriting constructors.
9375     Diag(Name.getBeginLoc(),
9376          getLangOpts().CPlusPlus11
9377              ? diag::warn_cxx98_compat_using_decl_constructor
9378              : diag::err_using_decl_constructor)
9379         << SS.getRange();
9380 
9381     if (getLangOpts().CPlusPlus11) break;
9382 
9383     return nullptr;
9384 
9385   case UnqualifiedIdKind::IK_DestructorName:
9386     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9387     return nullptr;
9388 
9389   case UnqualifiedIdKind::IK_TemplateId:
9390     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9391         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9392     return nullptr;
9393 
9394   case UnqualifiedIdKind::IK_DeductionGuideName:
9395     llvm_unreachable("cannot parse qualified deduction guide name");
9396   }
9397 
9398   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9399   DeclarationName TargetName = TargetNameInfo.getName();
9400   if (!TargetName)
9401     return nullptr;
9402 
9403   // Warn about access declarations.
9404   if (UsingLoc.isInvalid()) {
9405     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9406                                  ? diag::err_access_decl
9407                                  : diag::warn_access_decl_deprecated)
9408         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9409   }
9410 
9411   if (EllipsisLoc.isInvalid()) {
9412     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9413         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9414       return nullptr;
9415   } else {
9416     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9417         !TargetNameInfo.containsUnexpandedParameterPack()) {
9418       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9419         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9420       EllipsisLoc = SourceLocation();
9421     }
9422   }
9423 
9424   NamedDecl *UD =
9425       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9426                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9427                             /*IsInstantiation*/false);
9428   if (UD)
9429     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9430 
9431   return UD;
9432 }
9433 
9434 /// Determine whether a using declaration considers the given
9435 /// declarations as "equivalent", e.g., if they are redeclarations of
9436 /// the same entity or are both typedefs of the same type.
9437 static bool
9438 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9439   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9440     return true;
9441 
9442   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9443     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9444       return Context.hasSameType(TD1->getUnderlyingType(),
9445                                  TD2->getUnderlyingType());
9446 
9447   return false;
9448 }
9449 
9450 
9451 /// Determines whether to create a using shadow decl for a particular
9452 /// decl, given the set of decls existing prior to this using lookup.
9453 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9454                                 const LookupResult &Previous,
9455                                 UsingShadowDecl *&PrevShadow) {
9456   // Diagnose finding a decl which is not from a base class of the
9457   // current class.  We do this now because there are cases where this
9458   // function will silently decide not to build a shadow decl, which
9459   // will pre-empt further diagnostics.
9460   //
9461   // We don't need to do this in C++11 because we do the check once on
9462   // the qualifier.
9463   //
9464   // FIXME: diagnose the following if we care enough:
9465   //   struct A { int foo; };
9466   //   struct B : A { using A::foo; };
9467   //   template <class T> struct C : A {};
9468   //   template <class T> struct D : C<T> { using B::foo; } // <---
9469   // This is invalid (during instantiation) in C++03 because B::foo
9470   // resolves to the using decl in B, which is not a base class of D<T>.
9471   // We can't diagnose it immediately because C<T> is an unknown
9472   // specialization.  The UsingShadowDecl in D<T> then points directly
9473   // to A::foo, which will look well-formed when we instantiate.
9474   // The right solution is to not collapse the shadow-decl chain.
9475   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9476     DeclContext *OrigDC = Orig->getDeclContext();
9477 
9478     // Handle enums and anonymous structs.
9479     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9480     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9481     while (OrigRec->isAnonymousStructOrUnion())
9482       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9483 
9484     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9485       if (OrigDC == CurContext) {
9486         Diag(Using->getLocation(),
9487              diag::err_using_decl_nested_name_specifier_is_current_class)
9488           << Using->getQualifierLoc().getSourceRange();
9489         Diag(Orig->getLocation(), diag::note_using_decl_target);
9490         Using->setInvalidDecl();
9491         return true;
9492       }
9493 
9494       Diag(Using->getQualifierLoc().getBeginLoc(),
9495            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9496         << Using->getQualifier()
9497         << cast<CXXRecordDecl>(CurContext)
9498         << Using->getQualifierLoc().getSourceRange();
9499       Diag(Orig->getLocation(), diag::note_using_decl_target);
9500       Using->setInvalidDecl();
9501       return true;
9502     }
9503   }
9504 
9505   if (Previous.empty()) return false;
9506 
9507   NamedDecl *Target = Orig;
9508   if (isa<UsingShadowDecl>(Target))
9509     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9510 
9511   // If the target happens to be one of the previous declarations, we
9512   // don't have a conflict.
9513   //
9514   // FIXME: but we might be increasing its access, in which case we
9515   // should redeclare it.
9516   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9517   bool FoundEquivalentDecl = false;
9518   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9519          I != E; ++I) {
9520     NamedDecl *D = (*I)->getUnderlyingDecl();
9521     // We can have UsingDecls in our Previous results because we use the same
9522     // LookupResult for checking whether the UsingDecl itself is a valid
9523     // redeclaration.
9524     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9525       continue;
9526 
9527     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9528       // C++ [class.mem]p19:
9529       //   If T is the name of a class, then [every named member other than
9530       //   a non-static data member] shall have a name different from T
9531       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9532           !isa<IndirectFieldDecl>(Target) &&
9533           !isa<UnresolvedUsingValueDecl>(Target) &&
9534           DiagnoseClassNameShadow(
9535               CurContext,
9536               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9537         return true;
9538     }
9539 
9540     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9541       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9542         PrevShadow = Shadow;
9543       FoundEquivalentDecl = true;
9544     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9545       // We don't conflict with an existing using shadow decl of an equivalent
9546       // declaration, but we're not a redeclaration of it.
9547       FoundEquivalentDecl = true;
9548     }
9549 
9550     if (isVisible(D))
9551       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9552   }
9553 
9554   if (FoundEquivalentDecl)
9555     return false;
9556 
9557   if (FunctionDecl *FD = Target->getAsFunction()) {
9558     NamedDecl *OldDecl = nullptr;
9559     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9560                           /*IsForUsingDecl*/ true)) {
9561     case Ovl_Overload:
9562       return false;
9563 
9564     case Ovl_NonFunction:
9565       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9566       break;
9567 
9568     // We found a decl with the exact signature.
9569     case Ovl_Match:
9570       // If we're in a record, we want to hide the target, so we
9571       // return true (without a diagnostic) to tell the caller not to
9572       // build a shadow decl.
9573       if (CurContext->isRecord())
9574         return true;
9575 
9576       // If we're not in a record, this is an error.
9577       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9578       break;
9579     }
9580 
9581     Diag(Target->getLocation(), diag::note_using_decl_target);
9582     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9583     Using->setInvalidDecl();
9584     return true;
9585   }
9586 
9587   // Target is not a function.
9588 
9589   if (isa<TagDecl>(Target)) {
9590     // No conflict between a tag and a non-tag.
9591     if (!Tag) return false;
9592 
9593     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9594     Diag(Target->getLocation(), diag::note_using_decl_target);
9595     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9596     Using->setInvalidDecl();
9597     return true;
9598   }
9599 
9600   // No conflict between a tag and a non-tag.
9601   if (!NonTag) return false;
9602 
9603   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9604   Diag(Target->getLocation(), diag::note_using_decl_target);
9605   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9606   Using->setInvalidDecl();
9607   return true;
9608 }
9609 
9610 /// Determine whether a direct base class is a virtual base class.
9611 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9612   if (!Derived->getNumVBases())
9613     return false;
9614   for (auto &B : Derived->bases())
9615     if (B.getType()->getAsCXXRecordDecl() == Base)
9616       return B.isVirtual();
9617   llvm_unreachable("not a direct base class");
9618 }
9619 
9620 /// Builds a shadow declaration corresponding to a 'using' declaration.
9621 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9622                                             UsingDecl *UD,
9623                                             NamedDecl *Orig,
9624                                             UsingShadowDecl *PrevDecl) {
9625   // If we resolved to another shadow declaration, just coalesce them.
9626   NamedDecl *Target = Orig;
9627   if (isa<UsingShadowDecl>(Target)) {
9628     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9629     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9630   }
9631 
9632   NamedDecl *NonTemplateTarget = Target;
9633   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9634     NonTemplateTarget = TargetTD->getTemplatedDecl();
9635 
9636   UsingShadowDecl *Shadow;
9637   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9638     bool IsVirtualBase =
9639         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9640                             UD->getQualifier()->getAsRecordDecl());
9641     Shadow = ConstructorUsingShadowDecl::Create(
9642         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9643   } else {
9644     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9645                                      Target);
9646   }
9647   UD->addShadowDecl(Shadow);
9648 
9649   Shadow->setAccess(UD->getAccess());
9650   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9651     Shadow->setInvalidDecl();
9652 
9653   Shadow->setPreviousDecl(PrevDecl);
9654 
9655   if (S)
9656     PushOnScopeChains(Shadow, S);
9657   else
9658     CurContext->addDecl(Shadow);
9659 
9660 
9661   return Shadow;
9662 }
9663 
9664 /// Hides a using shadow declaration.  This is required by the current
9665 /// using-decl implementation when a resolvable using declaration in a
9666 /// class is followed by a declaration which would hide or override
9667 /// one or more of the using decl's targets; for example:
9668 ///
9669 ///   struct Base { void foo(int); };
9670 ///   struct Derived : Base {
9671 ///     using Base::foo;
9672 ///     void foo(int);
9673 ///   };
9674 ///
9675 /// The governing language is C++03 [namespace.udecl]p12:
9676 ///
9677 ///   When a using-declaration brings names from a base class into a
9678 ///   derived class scope, member functions in the derived class
9679 ///   override and/or hide member functions with the same name and
9680 ///   parameter types in a base class (rather than conflicting).
9681 ///
9682 /// There are two ways to implement this:
9683 ///   (1) optimistically create shadow decls when they're not hidden
9684 ///       by existing declarations, or
9685 ///   (2) don't create any shadow decls (or at least don't make them
9686 ///       visible) until we've fully parsed/instantiated the class.
9687 /// The problem with (1) is that we might have to retroactively remove
9688 /// a shadow decl, which requires several O(n) operations because the
9689 /// decl structures are (very reasonably) not designed for removal.
9690 /// (2) avoids this but is very fiddly and phase-dependent.
9691 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9692   if (Shadow->getDeclName().getNameKind() ==
9693         DeclarationName::CXXConversionFunctionName)
9694     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9695 
9696   // Remove it from the DeclContext...
9697   Shadow->getDeclContext()->removeDecl(Shadow);
9698 
9699   // ...and the scope, if applicable...
9700   if (S) {
9701     S->RemoveDecl(Shadow);
9702     IdResolver.RemoveDecl(Shadow);
9703   }
9704 
9705   // ...and the using decl.
9706   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9707 
9708   // TODO: complain somehow if Shadow was used.  It shouldn't
9709   // be possible for this to happen, because...?
9710 }
9711 
9712 /// Find the base specifier for a base class with the given type.
9713 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9714                                                 QualType DesiredBase,
9715                                                 bool &AnyDependentBases) {
9716   // Check whether the named type is a direct base class.
9717   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9718   for (auto &Base : Derived->bases()) {
9719     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9720     if (CanonicalDesiredBase == BaseType)
9721       return &Base;
9722     if (BaseType->isDependentType())
9723       AnyDependentBases = true;
9724   }
9725   return nullptr;
9726 }
9727 
9728 namespace {
9729 class UsingValidatorCCC : public CorrectionCandidateCallback {
9730 public:
9731   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9732                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9733       : HasTypenameKeyword(HasTypenameKeyword),
9734         IsInstantiation(IsInstantiation), OldNNS(NNS),
9735         RequireMemberOf(RequireMemberOf) {}
9736 
9737   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9738     NamedDecl *ND = Candidate.getCorrectionDecl();
9739 
9740     // Keywords are not valid here.
9741     if (!ND || isa<NamespaceDecl>(ND))
9742       return false;
9743 
9744     // Completely unqualified names are invalid for a 'using' declaration.
9745     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9746       return false;
9747 
9748     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9749     // reject.
9750 
9751     if (RequireMemberOf) {
9752       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9753       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9754         // No-one ever wants a using-declaration to name an injected-class-name
9755         // of a base class, unless they're declaring an inheriting constructor.
9756         ASTContext &Ctx = ND->getASTContext();
9757         if (!Ctx.getLangOpts().CPlusPlus11)
9758           return false;
9759         QualType FoundType = Ctx.getRecordType(FoundRecord);
9760 
9761         // Check that the injected-class-name is named as a member of its own
9762         // type; we don't want to suggest 'using Derived::Base;', since that
9763         // means something else.
9764         NestedNameSpecifier *Specifier =
9765             Candidate.WillReplaceSpecifier()
9766                 ? Candidate.getCorrectionSpecifier()
9767                 : OldNNS;
9768         if (!Specifier->getAsType() ||
9769             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9770           return false;
9771 
9772         // Check that this inheriting constructor declaration actually names a
9773         // direct base class of the current class.
9774         bool AnyDependentBases = false;
9775         if (!findDirectBaseWithType(RequireMemberOf,
9776                                     Ctx.getRecordType(FoundRecord),
9777                                     AnyDependentBases) &&
9778             !AnyDependentBases)
9779           return false;
9780       } else {
9781         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9782         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9783           return false;
9784 
9785         // FIXME: Check that the base class member is accessible?
9786       }
9787     } else {
9788       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9789       if (FoundRecord && FoundRecord->isInjectedClassName())
9790         return false;
9791     }
9792 
9793     if (isa<TypeDecl>(ND))
9794       return HasTypenameKeyword || !IsInstantiation;
9795 
9796     return !HasTypenameKeyword;
9797   }
9798 
9799 private:
9800   bool HasTypenameKeyword;
9801   bool IsInstantiation;
9802   NestedNameSpecifier *OldNNS;
9803   CXXRecordDecl *RequireMemberOf;
9804 };
9805 } // end anonymous namespace
9806 
9807 /// Builds a using declaration.
9808 ///
9809 /// \param IsInstantiation - Whether this call arises from an
9810 ///   instantiation of an unresolved using declaration.  We treat
9811 ///   the lookup differently for these declarations.
9812 NamedDecl *Sema::BuildUsingDeclaration(
9813     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9814     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9815     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9816     const ParsedAttributesView &AttrList, bool IsInstantiation) {
9817   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9818   SourceLocation IdentLoc = NameInfo.getLoc();
9819   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9820 
9821   // FIXME: We ignore attributes for now.
9822 
9823   // For an inheriting constructor declaration, the name of the using
9824   // declaration is the name of a constructor in this class, not in the
9825   // base class.
9826   DeclarationNameInfo UsingName = NameInfo;
9827   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9828     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9829       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9830           Context.getCanonicalType(Context.getRecordType(RD))));
9831 
9832   // Do the redeclaration lookup in the current scope.
9833   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9834                         ForVisibleRedeclaration);
9835   Previous.setHideTags(false);
9836   if (S) {
9837     LookupName(Previous, S);
9838 
9839     // It is really dumb that we have to do this.
9840     LookupResult::Filter F = Previous.makeFilter();
9841     while (F.hasNext()) {
9842       NamedDecl *D = F.next();
9843       if (!isDeclInScope(D, CurContext, S))
9844         F.erase();
9845       // If we found a local extern declaration that's not ordinarily visible,
9846       // and this declaration is being added to a non-block scope, ignore it.
9847       // We're only checking for scope conflicts here, not also for violations
9848       // of the linkage rules.
9849       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9850                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9851         F.erase();
9852     }
9853     F.done();
9854   } else {
9855     assert(IsInstantiation && "no scope in non-instantiation");
9856     if (CurContext->isRecord())
9857       LookupQualifiedName(Previous, CurContext);
9858     else {
9859       // No redeclaration check is needed here; in non-member contexts we
9860       // diagnosed all possible conflicts with other using-declarations when
9861       // building the template:
9862       //
9863       // For a dependent non-type using declaration, the only valid case is
9864       // if we instantiate to a single enumerator. We check for conflicts
9865       // between shadow declarations we introduce, and we check in the template
9866       // definition for conflicts between a non-type using declaration and any
9867       // other declaration, which together covers all cases.
9868       //
9869       // A dependent typename using declaration will never successfully
9870       // instantiate, since it will always name a class member, so we reject
9871       // that in the template definition.
9872     }
9873   }
9874 
9875   // Check for invalid redeclarations.
9876   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9877                                   SS, IdentLoc, Previous))
9878     return nullptr;
9879 
9880   // Check for bad qualifiers.
9881   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9882                               IdentLoc))
9883     return nullptr;
9884 
9885   DeclContext *LookupContext = computeDeclContext(SS);
9886   NamedDecl *D;
9887   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9888   if (!LookupContext || EllipsisLoc.isValid()) {
9889     if (HasTypenameKeyword) {
9890       // FIXME: not all declaration name kinds are legal here
9891       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9892                                               UsingLoc, TypenameLoc,
9893                                               QualifierLoc,
9894                                               IdentLoc, NameInfo.getName(),
9895                                               EllipsisLoc);
9896     } else {
9897       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9898                                            QualifierLoc, NameInfo, EllipsisLoc);
9899     }
9900     D->setAccess(AS);
9901     CurContext->addDecl(D);
9902     return D;
9903   }
9904 
9905   auto Build = [&](bool Invalid) {
9906     UsingDecl *UD =
9907         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9908                           UsingName, HasTypenameKeyword);
9909     UD->setAccess(AS);
9910     CurContext->addDecl(UD);
9911     UD->setInvalidDecl(Invalid);
9912     return UD;
9913   };
9914   auto BuildInvalid = [&]{ return Build(true); };
9915   auto BuildValid = [&]{ return Build(false); };
9916 
9917   if (RequireCompleteDeclContext(SS, LookupContext))
9918     return BuildInvalid();
9919 
9920   // Look up the target name.
9921   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9922 
9923   // Unlike most lookups, we don't always want to hide tag
9924   // declarations: tag names are visible through the using declaration
9925   // even if hidden by ordinary names, *except* in a dependent context
9926   // where it's important for the sanity of two-phase lookup.
9927   if (!IsInstantiation)
9928     R.setHideTags(false);
9929 
9930   // For the purposes of this lookup, we have a base object type
9931   // equal to that of the current context.
9932   if (CurContext->isRecord()) {
9933     R.setBaseObjectType(
9934                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9935   }
9936 
9937   LookupQualifiedName(R, LookupContext);
9938 
9939   // Try to correct typos if possible. If constructor name lookup finds no
9940   // results, that means the named class has no explicit constructors, and we
9941   // suppressed declaring implicit ones (probably because it's dependent or
9942   // invalid).
9943   if (R.empty() &&
9944       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9945     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9946     // it will believe that glibc provides a ::gets in cases where it does not,
9947     // and will try to pull it into namespace std with a using-declaration.
9948     // Just ignore the using-declaration in that case.
9949     auto *II = NameInfo.getName().getAsIdentifierInfo();
9950     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9951         CurContext->isStdNamespace() &&
9952         isa<TranslationUnitDecl>(LookupContext) &&
9953         getSourceManager().isInSystemHeader(UsingLoc))
9954       return nullptr;
9955     if (TypoCorrection Corrected = CorrectTypo(
9956             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9957             llvm::make_unique<UsingValidatorCCC>(
9958                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9959                 dyn_cast<CXXRecordDecl>(CurContext)),
9960             CTK_ErrorRecovery)) {
9961       // We reject candidates where DroppedSpecifier == true, hence the
9962       // literal '0' below.
9963       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9964                                 << NameInfo.getName() << LookupContext << 0
9965                                 << SS.getRange());
9966 
9967       // If we picked a correction with no attached Decl we can't do anything
9968       // useful with it, bail out.
9969       NamedDecl *ND = Corrected.getCorrectionDecl();
9970       if (!ND)
9971         return BuildInvalid();
9972 
9973       // If we corrected to an inheriting constructor, handle it as one.
9974       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9975       if (RD && RD->isInjectedClassName()) {
9976         // The parent of the injected class name is the class itself.
9977         RD = cast<CXXRecordDecl>(RD->getParent());
9978 
9979         // Fix up the information we'll use to build the using declaration.
9980         if (Corrected.WillReplaceSpecifier()) {
9981           NestedNameSpecifierLocBuilder Builder;
9982           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9983                               QualifierLoc.getSourceRange());
9984           QualifierLoc = Builder.getWithLocInContext(Context);
9985         }
9986 
9987         // In this case, the name we introduce is the name of a derived class
9988         // constructor.
9989         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9990         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9991             Context.getCanonicalType(Context.getRecordType(CurClass))));
9992         UsingName.setNamedTypeInfo(nullptr);
9993         for (auto *Ctor : LookupConstructors(RD))
9994           R.addDecl(Ctor);
9995         R.resolveKind();
9996       } else {
9997         // FIXME: Pick up all the declarations if we found an overloaded
9998         // function.
9999         UsingName.setName(ND->getDeclName());
10000         R.addDecl(ND);
10001       }
10002     } else {
10003       Diag(IdentLoc, diag::err_no_member)
10004         << NameInfo.getName() << LookupContext << SS.getRange();
10005       return BuildInvalid();
10006     }
10007   }
10008 
10009   if (R.isAmbiguous())
10010     return BuildInvalid();
10011 
10012   if (HasTypenameKeyword) {
10013     // If we asked for a typename and got a non-type decl, error out.
10014     if (!R.getAsSingle<TypeDecl>()) {
10015       Diag(IdentLoc, diag::err_using_typename_non_type);
10016       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10017         Diag((*I)->getUnderlyingDecl()->getLocation(),
10018              diag::note_using_decl_target);
10019       return BuildInvalid();
10020     }
10021   } else {
10022     // If we asked for a non-typename and we got a type, error out,
10023     // but only if this is an instantiation of an unresolved using
10024     // decl.  Otherwise just silently find the type name.
10025     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10026       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10027       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10028       return BuildInvalid();
10029     }
10030   }
10031 
10032   // C++14 [namespace.udecl]p6:
10033   // A using-declaration shall not name a namespace.
10034   if (R.getAsSingle<NamespaceDecl>()) {
10035     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10036       << SS.getRange();
10037     return BuildInvalid();
10038   }
10039 
10040   // C++14 [namespace.udecl]p7:
10041   // A using-declaration shall not name a scoped enumerator.
10042   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10043     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10044       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10045         << SS.getRange();
10046       return BuildInvalid();
10047     }
10048   }
10049 
10050   UsingDecl *UD = BuildValid();
10051 
10052   // Some additional rules apply to inheriting constructors.
10053   if (UsingName.getName().getNameKind() ==
10054         DeclarationName::CXXConstructorName) {
10055     // Suppress access diagnostics; the access check is instead performed at the
10056     // point of use for an inheriting constructor.
10057     R.suppressDiagnostics();
10058     if (CheckInheritingConstructorUsingDecl(UD))
10059       return UD;
10060   }
10061 
10062   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10063     UsingShadowDecl *PrevDecl = nullptr;
10064     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10065       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10066   }
10067 
10068   return UD;
10069 }
10070 
10071 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10072                                     ArrayRef<NamedDecl *> Expansions) {
10073   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10074          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10075          isa<UsingPackDecl>(InstantiatedFrom));
10076 
10077   auto *UPD =
10078       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10079   UPD->setAccess(InstantiatedFrom->getAccess());
10080   CurContext->addDecl(UPD);
10081   return UPD;
10082 }
10083 
10084 /// Additional checks for a using declaration referring to a constructor name.
10085 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10086   assert(!UD->hasTypename() && "expecting a constructor name");
10087 
10088   const Type *SourceType = UD->getQualifier()->getAsType();
10089   assert(SourceType &&
10090          "Using decl naming constructor doesn't have type in scope spec.");
10091   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10092 
10093   // Check whether the named type is a direct base class.
10094   bool AnyDependentBases = false;
10095   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10096                                       AnyDependentBases);
10097   if (!Base && !AnyDependentBases) {
10098     Diag(UD->getUsingLoc(),
10099          diag::err_using_decl_constructor_not_in_direct_base)
10100       << UD->getNameInfo().getSourceRange()
10101       << QualType(SourceType, 0) << TargetClass;
10102     UD->setInvalidDecl();
10103     return true;
10104   }
10105 
10106   if (Base)
10107     Base->setInheritConstructors();
10108 
10109   return false;
10110 }
10111 
10112 /// Checks that the given using declaration is not an invalid
10113 /// redeclaration.  Note that this is checking only for the using decl
10114 /// itself, not for any ill-formedness among the UsingShadowDecls.
10115 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10116                                        bool HasTypenameKeyword,
10117                                        const CXXScopeSpec &SS,
10118                                        SourceLocation NameLoc,
10119                                        const LookupResult &Prev) {
10120   NestedNameSpecifier *Qual = SS.getScopeRep();
10121 
10122   // C++03 [namespace.udecl]p8:
10123   // C++0x [namespace.udecl]p10:
10124   //   A using-declaration is a declaration and can therefore be used
10125   //   repeatedly where (and only where) multiple declarations are
10126   //   allowed.
10127   //
10128   // That's in non-member contexts.
10129   if (!CurContext->getRedeclContext()->isRecord()) {
10130     // A dependent qualifier outside a class can only ever resolve to an
10131     // enumeration type. Therefore it conflicts with any other non-type
10132     // declaration in the same scope.
10133     // FIXME: How should we check for dependent type-type conflicts at block
10134     // scope?
10135     if (Qual->isDependent() && !HasTypenameKeyword) {
10136       for (auto *D : Prev) {
10137         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10138           bool OldCouldBeEnumerator =
10139               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10140           Diag(NameLoc,
10141                OldCouldBeEnumerator ? diag::err_redefinition
10142                                     : diag::err_redefinition_different_kind)
10143               << Prev.getLookupName();
10144           Diag(D->getLocation(), diag::note_previous_definition);
10145           return true;
10146         }
10147       }
10148     }
10149     return false;
10150   }
10151 
10152   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10153     NamedDecl *D = *I;
10154 
10155     bool DTypename;
10156     NestedNameSpecifier *DQual;
10157     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10158       DTypename = UD->hasTypename();
10159       DQual = UD->getQualifier();
10160     } else if (UnresolvedUsingValueDecl *UD
10161                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10162       DTypename = false;
10163       DQual = UD->getQualifier();
10164     } else if (UnresolvedUsingTypenameDecl *UD
10165                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10166       DTypename = true;
10167       DQual = UD->getQualifier();
10168     } else continue;
10169 
10170     // using decls differ if one says 'typename' and the other doesn't.
10171     // FIXME: non-dependent using decls?
10172     if (HasTypenameKeyword != DTypename) continue;
10173 
10174     // using decls differ if they name different scopes (but note that
10175     // template instantiation can cause this check to trigger when it
10176     // didn't before instantiation).
10177     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10178         Context.getCanonicalNestedNameSpecifier(DQual))
10179       continue;
10180 
10181     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10182     Diag(D->getLocation(), diag::note_using_decl) << 1;
10183     return true;
10184   }
10185 
10186   return false;
10187 }
10188 
10189 
10190 /// Checks that the given nested-name qualifier used in a using decl
10191 /// in the current context is appropriately related to the current
10192 /// scope.  If an error is found, diagnoses it and returns true.
10193 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10194                                    bool HasTypename,
10195                                    const CXXScopeSpec &SS,
10196                                    const DeclarationNameInfo &NameInfo,
10197                                    SourceLocation NameLoc) {
10198   DeclContext *NamedContext = computeDeclContext(SS);
10199 
10200   if (!CurContext->isRecord()) {
10201     // C++03 [namespace.udecl]p3:
10202     // C++0x [namespace.udecl]p8:
10203     //   A using-declaration for a class member shall be a member-declaration.
10204 
10205     // If we weren't able to compute a valid scope, it might validly be a
10206     // dependent class scope or a dependent enumeration unscoped scope. If
10207     // we have a 'typename' keyword, the scope must resolve to a class type.
10208     if ((HasTypename && !NamedContext) ||
10209         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10210       auto *RD = NamedContext
10211                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10212                      : nullptr;
10213       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10214         RD = nullptr;
10215 
10216       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10217         << SS.getRange();
10218 
10219       // If we have a complete, non-dependent source type, try to suggest a
10220       // way to get the same effect.
10221       if (!RD)
10222         return true;
10223 
10224       // Find what this using-declaration was referring to.
10225       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10226       R.setHideTags(false);
10227       R.suppressDiagnostics();
10228       LookupQualifiedName(R, RD);
10229 
10230       if (R.getAsSingle<TypeDecl>()) {
10231         if (getLangOpts().CPlusPlus11) {
10232           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10233           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10234             << 0 // alias declaration
10235             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10236                                           NameInfo.getName().getAsString() +
10237                                               " = ");
10238         } else {
10239           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10240           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10241           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10242             << 1 // typedef declaration
10243             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10244             << FixItHint::CreateInsertion(
10245                    InsertLoc, " " + NameInfo.getName().getAsString());
10246         }
10247       } else if (R.getAsSingle<VarDecl>()) {
10248         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10249         // repeating the type of the static data member here.
10250         FixItHint FixIt;
10251         if (getLangOpts().CPlusPlus11) {
10252           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10253           FixIt = FixItHint::CreateReplacement(
10254               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10255         }
10256 
10257         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10258           << 2 // reference declaration
10259           << FixIt;
10260       } else if (R.getAsSingle<EnumConstantDecl>()) {
10261         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10262         // repeating the type of the enumeration here, and we can't do so if
10263         // the type is anonymous.
10264         FixItHint FixIt;
10265         if (getLangOpts().CPlusPlus11) {
10266           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10267           FixIt = FixItHint::CreateReplacement(
10268               UsingLoc,
10269               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10270         }
10271 
10272         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10273           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10274           << FixIt;
10275       }
10276       return true;
10277     }
10278 
10279     // Otherwise, this might be valid.
10280     return false;
10281   }
10282 
10283   // The current scope is a record.
10284 
10285   // If the named context is dependent, we can't decide much.
10286   if (!NamedContext) {
10287     // FIXME: in C++0x, we can diagnose if we can prove that the
10288     // nested-name-specifier does not refer to a base class, which is
10289     // still possible in some cases.
10290 
10291     // Otherwise we have to conservatively report that things might be
10292     // okay.
10293     return false;
10294   }
10295 
10296   if (!NamedContext->isRecord()) {
10297     // Ideally this would point at the last name in the specifier,
10298     // but we don't have that level of source info.
10299     Diag(SS.getRange().getBegin(),
10300          diag::err_using_decl_nested_name_specifier_is_not_class)
10301       << SS.getScopeRep() << SS.getRange();
10302     return true;
10303   }
10304 
10305   if (!NamedContext->isDependentContext() &&
10306       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10307     return true;
10308 
10309   if (getLangOpts().CPlusPlus11) {
10310     // C++11 [namespace.udecl]p3:
10311     //   In a using-declaration used as a member-declaration, the
10312     //   nested-name-specifier shall name a base class of the class
10313     //   being defined.
10314 
10315     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10316                                  cast<CXXRecordDecl>(NamedContext))) {
10317       if (CurContext == NamedContext) {
10318         Diag(NameLoc,
10319              diag::err_using_decl_nested_name_specifier_is_current_class)
10320           << SS.getRange();
10321         return true;
10322       }
10323 
10324       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10325         Diag(SS.getRange().getBegin(),
10326              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10327           << SS.getScopeRep()
10328           << cast<CXXRecordDecl>(CurContext)
10329           << SS.getRange();
10330       }
10331       return true;
10332     }
10333 
10334     return false;
10335   }
10336 
10337   // C++03 [namespace.udecl]p4:
10338   //   A using-declaration used as a member-declaration shall refer
10339   //   to a member of a base class of the class being defined [etc.].
10340 
10341   // Salient point: SS doesn't have to name a base class as long as
10342   // lookup only finds members from base classes.  Therefore we can
10343   // diagnose here only if we can prove that that can't happen,
10344   // i.e. if the class hierarchies provably don't intersect.
10345 
10346   // TODO: it would be nice if "definitely valid" results were cached
10347   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10348   // need to be repeated.
10349 
10350   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10351   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10352     Bases.insert(Base);
10353     return true;
10354   };
10355 
10356   // Collect all bases. Return false if we find a dependent base.
10357   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10358     return false;
10359 
10360   // Returns true if the base is dependent or is one of the accumulated base
10361   // classes.
10362   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10363     return !Bases.count(Base);
10364   };
10365 
10366   // Return false if the class has a dependent base or if it or one
10367   // of its bases is present in the base set of the current context.
10368   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10369       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10370     return false;
10371 
10372   Diag(SS.getRange().getBegin(),
10373        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10374     << SS.getScopeRep()
10375     << cast<CXXRecordDecl>(CurContext)
10376     << SS.getRange();
10377 
10378   return true;
10379 }
10380 
10381 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10382                                   MultiTemplateParamsArg TemplateParamLists,
10383                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10384                                   const ParsedAttributesView &AttrList,
10385                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10386   // Skip up to the relevant declaration scope.
10387   while (S->isTemplateParamScope())
10388     S = S->getParent();
10389   assert((S->getFlags() & Scope::DeclScope) &&
10390          "got alias-declaration outside of declaration scope");
10391 
10392   if (Type.isInvalid())
10393     return nullptr;
10394 
10395   bool Invalid = false;
10396   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10397   TypeSourceInfo *TInfo = nullptr;
10398   GetTypeFromParser(Type.get(), &TInfo);
10399 
10400   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10401     return nullptr;
10402 
10403   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10404                                       UPPC_DeclarationType)) {
10405     Invalid = true;
10406     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10407                                              TInfo->getTypeLoc().getBeginLoc());
10408   }
10409 
10410   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10411                         TemplateParamLists.size()
10412                             ? forRedeclarationInCurContext()
10413                             : ForVisibleRedeclaration);
10414   LookupName(Previous, S);
10415 
10416   // Warn about shadowing the name of a template parameter.
10417   if (Previous.isSingleResult() &&
10418       Previous.getFoundDecl()->isTemplateParameter()) {
10419     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10420     Previous.clear();
10421   }
10422 
10423   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10424          "name in alias declaration must be an identifier");
10425   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10426                                                Name.StartLocation,
10427                                                Name.Identifier, TInfo);
10428 
10429   NewTD->setAccess(AS);
10430 
10431   if (Invalid)
10432     NewTD->setInvalidDecl();
10433 
10434   ProcessDeclAttributeList(S, NewTD, AttrList);
10435   AddPragmaAttributes(S, NewTD);
10436 
10437   CheckTypedefForVariablyModifiedType(S, NewTD);
10438   Invalid |= NewTD->isInvalidDecl();
10439 
10440   bool Redeclaration = false;
10441 
10442   NamedDecl *NewND;
10443   if (TemplateParamLists.size()) {
10444     TypeAliasTemplateDecl *OldDecl = nullptr;
10445     TemplateParameterList *OldTemplateParams = nullptr;
10446 
10447     if (TemplateParamLists.size() != 1) {
10448       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10449         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10450          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10451     }
10452     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10453 
10454     // Check that we can declare a template here.
10455     if (CheckTemplateDeclScope(S, TemplateParams))
10456       return nullptr;
10457 
10458     // Only consider previous declarations in the same scope.
10459     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10460                          /*ExplicitInstantiationOrSpecialization*/false);
10461     if (!Previous.empty()) {
10462       Redeclaration = true;
10463 
10464       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10465       if (!OldDecl && !Invalid) {
10466         Diag(UsingLoc, diag::err_redefinition_different_kind)
10467           << Name.Identifier;
10468 
10469         NamedDecl *OldD = Previous.getRepresentativeDecl();
10470         if (OldD->getLocation().isValid())
10471           Diag(OldD->getLocation(), diag::note_previous_definition);
10472 
10473         Invalid = true;
10474       }
10475 
10476       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10477         if (TemplateParameterListsAreEqual(TemplateParams,
10478                                            OldDecl->getTemplateParameters(),
10479                                            /*Complain=*/true,
10480                                            TPL_TemplateMatch))
10481           OldTemplateParams = OldDecl->getTemplateParameters();
10482         else
10483           Invalid = true;
10484 
10485         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10486         if (!Invalid &&
10487             !Context.hasSameType(OldTD->getUnderlyingType(),
10488                                  NewTD->getUnderlyingType())) {
10489           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10490           // but we can't reasonably accept it.
10491           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10492             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10493           if (OldTD->getLocation().isValid())
10494             Diag(OldTD->getLocation(), diag::note_previous_definition);
10495           Invalid = true;
10496         }
10497       }
10498     }
10499 
10500     // Merge any previous default template arguments into our parameters,
10501     // and check the parameter list.
10502     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10503                                    TPC_TypeAliasTemplate))
10504       return nullptr;
10505 
10506     TypeAliasTemplateDecl *NewDecl =
10507       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10508                                     Name.Identifier, TemplateParams,
10509                                     NewTD);
10510     NewTD->setDescribedAliasTemplate(NewDecl);
10511 
10512     NewDecl->setAccess(AS);
10513 
10514     if (Invalid)
10515       NewDecl->setInvalidDecl();
10516     else if (OldDecl) {
10517       NewDecl->setPreviousDecl(OldDecl);
10518       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10519     }
10520 
10521     NewND = NewDecl;
10522   } else {
10523     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10524       setTagNameForLinkagePurposes(TD, NewTD);
10525       handleTagNumbering(TD, S);
10526     }
10527     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10528     NewND = NewTD;
10529   }
10530 
10531   PushOnScopeChains(NewND, S);
10532   ActOnDocumentableDecl(NewND);
10533   return NewND;
10534 }
10535 
10536 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10537                                    SourceLocation AliasLoc,
10538                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10539                                    SourceLocation IdentLoc,
10540                                    IdentifierInfo *Ident) {
10541 
10542   // Lookup the namespace name.
10543   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10544   LookupParsedName(R, S, &SS);
10545 
10546   if (R.isAmbiguous())
10547     return nullptr;
10548 
10549   if (R.empty()) {
10550     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10551       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10552       return nullptr;
10553     }
10554   }
10555   assert(!R.isAmbiguous() && !R.empty());
10556   NamedDecl *ND = R.getRepresentativeDecl();
10557 
10558   // Check if we have a previous declaration with the same name.
10559   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10560                      ForVisibleRedeclaration);
10561   LookupName(PrevR, S);
10562 
10563   // Check we're not shadowing a template parameter.
10564   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10565     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10566     PrevR.clear();
10567   }
10568 
10569   // Filter out any other lookup result from an enclosing scope.
10570   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10571                        /*AllowInlineNamespace*/false);
10572 
10573   // Find the previous declaration and check that we can redeclare it.
10574   NamespaceAliasDecl *Prev = nullptr;
10575   if (PrevR.isSingleResult()) {
10576     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10577     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10578       // We already have an alias with the same name that points to the same
10579       // namespace; check that it matches.
10580       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10581         Prev = AD;
10582       } else if (isVisible(PrevDecl)) {
10583         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10584           << Alias;
10585         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10586           << AD->getNamespace();
10587         return nullptr;
10588       }
10589     } else if (isVisible(PrevDecl)) {
10590       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10591                             ? diag::err_redefinition
10592                             : diag::err_redefinition_different_kind;
10593       Diag(AliasLoc, DiagID) << Alias;
10594       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10595       return nullptr;
10596     }
10597   }
10598 
10599   // The use of a nested name specifier may trigger deprecation warnings.
10600   DiagnoseUseOfDecl(ND, IdentLoc);
10601 
10602   NamespaceAliasDecl *AliasDecl =
10603     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10604                                Alias, SS.getWithLocInContext(Context),
10605                                IdentLoc, ND);
10606   if (Prev)
10607     AliasDecl->setPreviousDecl(Prev);
10608 
10609   PushOnScopeChains(AliasDecl, S);
10610   return AliasDecl;
10611 }
10612 
10613 namespace {
10614 struct SpecialMemberExceptionSpecInfo
10615     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10616   SourceLocation Loc;
10617   Sema::ImplicitExceptionSpecification ExceptSpec;
10618 
10619   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10620                                  Sema::CXXSpecialMember CSM,
10621                                  Sema::InheritedConstructorInfo *ICI,
10622                                  SourceLocation Loc)
10623       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10624 
10625   bool visitBase(CXXBaseSpecifier *Base);
10626   bool visitField(FieldDecl *FD);
10627 
10628   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10629                            unsigned Quals);
10630 
10631   void visitSubobjectCall(Subobject Subobj,
10632                           Sema::SpecialMemberOverloadResult SMOR);
10633 };
10634 }
10635 
10636 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10637   auto *RT = Base->getType()->getAs<RecordType>();
10638   if (!RT)
10639     return false;
10640 
10641   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10642   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10643   if (auto *BaseCtor = SMOR.getMethod()) {
10644     visitSubobjectCall(Base, BaseCtor);
10645     return false;
10646   }
10647 
10648   visitClassSubobject(BaseClass, Base, 0);
10649   return false;
10650 }
10651 
10652 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10653   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10654     Expr *E = FD->getInClassInitializer();
10655     if (!E)
10656       // FIXME: It's a little wasteful to build and throw away a
10657       // CXXDefaultInitExpr here.
10658       // FIXME: We should have a single context note pointing at Loc, and
10659       // this location should be MD->getLocation() instead, since that's
10660       // the location where we actually use the default init expression.
10661       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10662     if (E)
10663       ExceptSpec.CalledExpr(E);
10664   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10665                             ->getAs<RecordType>()) {
10666     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10667                         FD->getType().getCVRQualifiers());
10668   }
10669   return false;
10670 }
10671 
10672 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10673                                                          Subobject Subobj,
10674                                                          unsigned Quals) {
10675   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10676   bool IsMutable = Field && Field->isMutable();
10677   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10678 }
10679 
10680 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10681     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10682   // Note, if lookup fails, it doesn't matter what exception specification we
10683   // choose because the special member will be deleted.
10684   if (CXXMethodDecl *MD = SMOR.getMethod())
10685     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10686 }
10687 
10688 static Sema::ImplicitExceptionSpecification
10689 ComputeDefaultedSpecialMemberExceptionSpec(
10690     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10691     Sema::InheritedConstructorInfo *ICI) {
10692   CXXRecordDecl *ClassDecl = MD->getParent();
10693 
10694   // C++ [except.spec]p14:
10695   //   An implicitly declared special member function (Clause 12) shall have an
10696   //   exception-specification. [...]
10697   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10698   if (ClassDecl->isInvalidDecl())
10699     return Info.ExceptSpec;
10700 
10701   // C++1z [except.spec]p7:
10702   //   [Look for exceptions thrown by] a constructor selected [...] to
10703   //   initialize a potentially constructed subobject,
10704   // C++1z [except.spec]p8:
10705   //   The exception specification for an implicitly-declared destructor, or a
10706   //   destructor without a noexcept-specifier, is potentially-throwing if and
10707   //   only if any of the destructors for any of its potentially constructed
10708   //   subojects is potentially throwing.
10709   // FIXME: We respect the first rule but ignore the "potentially constructed"
10710   // in the second rule to resolve a core issue (no number yet) that would have
10711   // us reject:
10712   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10713   //   struct B : A {};
10714   //   struct C : B { void f(); };
10715   // ... due to giving B::~B() a non-throwing exception specification.
10716   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10717                                 : Info.VisitAllBases);
10718 
10719   return Info.ExceptSpec;
10720 }
10721 
10722 namespace {
10723 /// RAII object to register a special member as being currently declared.
10724 struct DeclaringSpecialMember {
10725   Sema &S;
10726   Sema::SpecialMemberDecl D;
10727   Sema::ContextRAII SavedContext;
10728   bool WasAlreadyBeingDeclared;
10729 
10730   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10731       : S(S), D(RD, CSM), SavedContext(S, RD) {
10732     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10733     if (WasAlreadyBeingDeclared)
10734       // This almost never happens, but if it does, ensure that our cache
10735       // doesn't contain a stale result.
10736       S.SpecialMemberCache.clear();
10737     else {
10738       // Register a note to be produced if we encounter an error while
10739       // declaring the special member.
10740       Sema::CodeSynthesisContext Ctx;
10741       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10742       // FIXME: We don't have a location to use here. Using the class's
10743       // location maintains the fiction that we declare all special members
10744       // with the class, but (1) it's not clear that lying about that helps our
10745       // users understand what's going on, and (2) there may be outer contexts
10746       // on the stack (some of which are relevant) and printing them exposes
10747       // our lies.
10748       Ctx.PointOfInstantiation = RD->getLocation();
10749       Ctx.Entity = RD;
10750       Ctx.SpecialMember = CSM;
10751       S.pushCodeSynthesisContext(Ctx);
10752     }
10753   }
10754   ~DeclaringSpecialMember() {
10755     if (!WasAlreadyBeingDeclared) {
10756       S.SpecialMembersBeingDeclared.erase(D);
10757       S.popCodeSynthesisContext();
10758     }
10759   }
10760 
10761   /// Are we already trying to declare this special member?
10762   bool isAlreadyBeingDeclared() const {
10763     return WasAlreadyBeingDeclared;
10764   }
10765 };
10766 }
10767 
10768 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10769   // Look up any existing declarations, but don't trigger declaration of all
10770   // implicit special members with this name.
10771   DeclarationName Name = FD->getDeclName();
10772   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10773                  ForExternalRedeclaration);
10774   for (auto *D : FD->getParent()->lookup(Name))
10775     if (auto *Acceptable = R.getAcceptableDecl(D))
10776       R.addDecl(Acceptable);
10777   R.resolveKind();
10778   R.suppressDiagnostics();
10779 
10780   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10781 }
10782 
10783 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10784                                                      CXXRecordDecl *ClassDecl) {
10785   // C++ [class.ctor]p5:
10786   //   A default constructor for a class X is a constructor of class X
10787   //   that can be called without an argument. If there is no
10788   //   user-declared constructor for class X, a default constructor is
10789   //   implicitly declared. An implicitly-declared default constructor
10790   //   is an inline public member of its class.
10791   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10792          "Should not build implicit default constructor!");
10793 
10794   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10795   if (DSM.isAlreadyBeingDeclared())
10796     return nullptr;
10797 
10798   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10799                                                      CXXDefaultConstructor,
10800                                                      false);
10801 
10802   // Create the actual constructor declaration.
10803   CanQualType ClassType
10804     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10805   SourceLocation ClassLoc = ClassDecl->getLocation();
10806   DeclarationName Name
10807     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10808   DeclarationNameInfo NameInfo(Name, ClassLoc);
10809   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10810       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10811       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10812       /*isImplicitlyDeclared=*/true, Constexpr);
10813   DefaultCon->setAccess(AS_public);
10814   DefaultCon->setDefaulted();
10815 
10816   if (getLangOpts().CUDA) {
10817     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10818                                             DefaultCon,
10819                                             /* ConstRHS */ false,
10820                                             /* Diagnose */ false);
10821   }
10822 
10823   // Build an exception specification pointing back at this constructor.
10824   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10825   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10826 
10827   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10828   // constructors is easy to compute.
10829   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10830 
10831   // Note that we have declared this constructor.
10832   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10833 
10834   Scope *S = getScopeForContext(ClassDecl);
10835   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10836 
10837   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10838     SetDeclDeleted(DefaultCon, ClassLoc);
10839 
10840   if (S)
10841     PushOnScopeChains(DefaultCon, S, false);
10842   ClassDecl->addDecl(DefaultCon);
10843 
10844   return DefaultCon;
10845 }
10846 
10847 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10848                                             CXXConstructorDecl *Constructor) {
10849   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10850           !Constructor->doesThisDeclarationHaveABody() &&
10851           !Constructor->isDeleted()) &&
10852     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10853   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10854     return;
10855 
10856   CXXRecordDecl *ClassDecl = Constructor->getParent();
10857   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10858 
10859   SynthesizedFunctionScope Scope(*this, Constructor);
10860 
10861   // The exception specification is needed because we are defining the
10862   // function.
10863   ResolveExceptionSpec(CurrentLocation,
10864                        Constructor->getType()->castAs<FunctionProtoType>());
10865   MarkVTableUsed(CurrentLocation, ClassDecl);
10866 
10867   // Add a context note for diagnostics produced after this point.
10868   Scope.addContextNote(CurrentLocation);
10869 
10870   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10871     Constructor->setInvalidDecl();
10872     return;
10873   }
10874 
10875   SourceLocation Loc = Constructor->getEndLoc().isValid()
10876                            ? Constructor->getEndLoc()
10877                            : Constructor->getLocation();
10878   Constructor->setBody(new (Context) CompoundStmt(Loc));
10879   Constructor->markUsed(Context);
10880 
10881   if (ASTMutationListener *L = getASTMutationListener()) {
10882     L->CompletedImplicitDefinition(Constructor);
10883   }
10884 
10885   DiagnoseUninitializedFields(*this, Constructor);
10886 }
10887 
10888 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10889   // Perform any delayed checks on exception specifications.
10890   CheckDelayedMemberExceptionSpecs();
10891 }
10892 
10893 /// Find or create the fake constructor we synthesize to model constructing an
10894 /// object of a derived class via a constructor of a base class.
10895 CXXConstructorDecl *
10896 Sema::findInheritingConstructor(SourceLocation Loc,
10897                                 CXXConstructorDecl *BaseCtor,
10898                                 ConstructorUsingShadowDecl *Shadow) {
10899   CXXRecordDecl *Derived = Shadow->getParent();
10900   SourceLocation UsingLoc = Shadow->getLocation();
10901 
10902   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10903   // For now we use the name of the base class constructor as a member of the
10904   // derived class to indicate a (fake) inherited constructor name.
10905   DeclarationName Name = BaseCtor->getDeclName();
10906 
10907   // Check to see if we already have a fake constructor for this inherited
10908   // constructor call.
10909   for (NamedDecl *Ctor : Derived->lookup(Name))
10910     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10911                                ->getInheritedConstructor()
10912                                .getConstructor(),
10913                            BaseCtor))
10914       return cast<CXXConstructorDecl>(Ctor);
10915 
10916   DeclarationNameInfo NameInfo(Name, UsingLoc);
10917   TypeSourceInfo *TInfo =
10918       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10919   FunctionProtoTypeLoc ProtoLoc =
10920       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10921 
10922   // Check the inherited constructor is valid and find the list of base classes
10923   // from which it was inherited.
10924   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10925 
10926   bool Constexpr =
10927       BaseCtor->isConstexpr() &&
10928       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10929                                         false, BaseCtor, &ICI);
10930 
10931   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10932       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10933       BaseCtor->isExplicit(), /*Inline=*/true,
10934       /*ImplicitlyDeclared=*/true, Constexpr,
10935       InheritedConstructor(Shadow, BaseCtor));
10936   if (Shadow->isInvalidDecl())
10937     DerivedCtor->setInvalidDecl();
10938 
10939   // Build an unevaluated exception specification for this fake constructor.
10940   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10941   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10942   EPI.ExceptionSpec.Type = EST_Unevaluated;
10943   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10944   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10945                                                FPT->getParamTypes(), EPI));
10946 
10947   // Build the parameter declarations.
10948   SmallVector<ParmVarDecl *, 16> ParamDecls;
10949   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10950     TypeSourceInfo *TInfo =
10951         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10952     ParmVarDecl *PD = ParmVarDecl::Create(
10953         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10954         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10955     PD->setScopeInfo(0, I);
10956     PD->setImplicit();
10957     // Ensure attributes are propagated onto parameters (this matters for
10958     // format, pass_object_size, ...).
10959     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10960     ParamDecls.push_back(PD);
10961     ProtoLoc.setParam(I, PD);
10962   }
10963 
10964   // Set up the new constructor.
10965   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10966   DerivedCtor->setAccess(BaseCtor->getAccess());
10967   DerivedCtor->setParams(ParamDecls);
10968   Derived->addDecl(DerivedCtor);
10969 
10970   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10971     SetDeclDeleted(DerivedCtor, UsingLoc);
10972 
10973   return DerivedCtor;
10974 }
10975 
10976 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10977   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10978                                Ctor->getInheritedConstructor().getShadowDecl());
10979   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10980                             /*Diagnose*/true);
10981 }
10982 
10983 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10984                                        CXXConstructorDecl *Constructor) {
10985   CXXRecordDecl *ClassDecl = Constructor->getParent();
10986   assert(Constructor->getInheritedConstructor() &&
10987          !Constructor->doesThisDeclarationHaveABody() &&
10988          !Constructor->isDeleted());
10989   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10990     return;
10991 
10992   // Initializations are performed "as if by a defaulted default constructor",
10993   // so enter the appropriate scope.
10994   SynthesizedFunctionScope Scope(*this, Constructor);
10995 
10996   // The exception specification is needed because we are defining the
10997   // function.
10998   ResolveExceptionSpec(CurrentLocation,
10999                        Constructor->getType()->castAs<FunctionProtoType>());
11000   MarkVTableUsed(CurrentLocation, ClassDecl);
11001 
11002   // Add a context note for diagnostics produced after this point.
11003   Scope.addContextNote(CurrentLocation);
11004 
11005   ConstructorUsingShadowDecl *Shadow =
11006       Constructor->getInheritedConstructor().getShadowDecl();
11007   CXXConstructorDecl *InheritedCtor =
11008       Constructor->getInheritedConstructor().getConstructor();
11009 
11010   // [class.inhctor.init]p1:
11011   //   initialization proceeds as if a defaulted default constructor is used to
11012   //   initialize the D object and each base class subobject from which the
11013   //   constructor was inherited
11014 
11015   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11016   CXXRecordDecl *RD = Shadow->getParent();
11017   SourceLocation InitLoc = Shadow->getLocation();
11018 
11019   // Build explicit initializers for all base classes from which the
11020   // constructor was inherited.
11021   SmallVector<CXXCtorInitializer*, 8> Inits;
11022   for (bool VBase : {false, true}) {
11023     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11024       if (B.isVirtual() != VBase)
11025         continue;
11026 
11027       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11028       if (!BaseRD)
11029         continue;
11030 
11031       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11032       if (!BaseCtor.first)
11033         continue;
11034 
11035       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11036       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11037           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11038 
11039       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11040       Inits.push_back(new (Context) CXXCtorInitializer(
11041           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11042           SourceLocation()));
11043     }
11044   }
11045 
11046   // We now proceed as if for a defaulted default constructor, with the relevant
11047   // initializers replaced.
11048 
11049   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11050     Constructor->setInvalidDecl();
11051     return;
11052   }
11053 
11054   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11055   Constructor->markUsed(Context);
11056 
11057   if (ASTMutationListener *L = getASTMutationListener()) {
11058     L->CompletedImplicitDefinition(Constructor);
11059   }
11060 
11061   DiagnoseUninitializedFields(*this, Constructor);
11062 }
11063 
11064 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11065   // C++ [class.dtor]p2:
11066   //   If a class has no user-declared destructor, a destructor is
11067   //   declared implicitly. An implicitly-declared destructor is an
11068   //   inline public member of its class.
11069   assert(ClassDecl->needsImplicitDestructor());
11070 
11071   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11072   if (DSM.isAlreadyBeingDeclared())
11073     return nullptr;
11074 
11075   // Create the actual destructor declaration.
11076   CanQualType ClassType
11077     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11078   SourceLocation ClassLoc = ClassDecl->getLocation();
11079   DeclarationName Name
11080     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11081   DeclarationNameInfo NameInfo(Name, ClassLoc);
11082   CXXDestructorDecl *Destructor
11083       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11084                                   QualType(), nullptr, /*isInline=*/true,
11085                                   /*isImplicitlyDeclared=*/true);
11086   Destructor->setAccess(AS_public);
11087   Destructor->setDefaulted();
11088 
11089   if (getLangOpts().CUDA) {
11090     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11091                                             Destructor,
11092                                             /* ConstRHS */ false,
11093                                             /* Diagnose */ false);
11094   }
11095 
11096   // Build an exception specification pointing back at this destructor.
11097   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11098   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11099 
11100   // We don't need to use SpecialMemberIsTrivial here; triviality for
11101   // destructors is easy to compute.
11102   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11103   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11104                                 ClassDecl->hasTrivialDestructorForCall());
11105 
11106   // Note that we have declared this destructor.
11107   ++ASTContext::NumImplicitDestructorsDeclared;
11108 
11109   Scope *S = getScopeForContext(ClassDecl);
11110   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11111 
11112   // We can't check whether an implicit destructor is deleted before we complete
11113   // the definition of the class, because its validity depends on the alignment
11114   // of the class. We'll check this from ActOnFields once the class is complete.
11115   if (ClassDecl->isCompleteDefinition() &&
11116       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11117     SetDeclDeleted(Destructor, ClassLoc);
11118 
11119   // Introduce this destructor into its scope.
11120   if (S)
11121     PushOnScopeChains(Destructor, S, false);
11122   ClassDecl->addDecl(Destructor);
11123 
11124   return Destructor;
11125 }
11126 
11127 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11128                                     CXXDestructorDecl *Destructor) {
11129   assert((Destructor->isDefaulted() &&
11130           !Destructor->doesThisDeclarationHaveABody() &&
11131           !Destructor->isDeleted()) &&
11132          "DefineImplicitDestructor - call it for implicit default dtor");
11133   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11134     return;
11135 
11136   CXXRecordDecl *ClassDecl = Destructor->getParent();
11137   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11138 
11139   SynthesizedFunctionScope Scope(*this, Destructor);
11140 
11141   // The exception specification is needed because we are defining the
11142   // function.
11143   ResolveExceptionSpec(CurrentLocation,
11144                        Destructor->getType()->castAs<FunctionProtoType>());
11145   MarkVTableUsed(CurrentLocation, ClassDecl);
11146 
11147   // Add a context note for diagnostics produced after this point.
11148   Scope.addContextNote(CurrentLocation);
11149 
11150   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11151                                          Destructor->getParent());
11152 
11153   if (CheckDestructor(Destructor)) {
11154     Destructor->setInvalidDecl();
11155     return;
11156   }
11157 
11158   SourceLocation Loc = Destructor->getEndLoc().isValid()
11159                            ? Destructor->getEndLoc()
11160                            : Destructor->getLocation();
11161   Destructor->setBody(new (Context) CompoundStmt(Loc));
11162   Destructor->markUsed(Context);
11163 
11164   if (ASTMutationListener *L = getASTMutationListener()) {
11165     L->CompletedImplicitDefinition(Destructor);
11166   }
11167 }
11168 
11169 /// Perform any semantic analysis which needs to be delayed until all
11170 /// pending class member declarations have been parsed.
11171 void Sema::ActOnFinishCXXMemberDecls() {
11172   // If the context is an invalid C++ class, just suppress these checks.
11173   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11174     if (Record->isInvalidDecl()) {
11175       DelayedDefaultedMemberExceptionSpecs.clear();
11176       DelayedExceptionSpecChecks.clear();
11177       return;
11178     }
11179     checkForMultipleExportedDefaultConstructors(*this, Record);
11180   }
11181 }
11182 
11183 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11184   referenceDLLExportedClassMethods();
11185 }
11186 
11187 void Sema::referenceDLLExportedClassMethods() {
11188   if (!DelayedDllExportClasses.empty()) {
11189     // Calling ReferenceDllExportedMembers might cause the current function to
11190     // be called again, so use a local copy of DelayedDllExportClasses.
11191     SmallVector<CXXRecordDecl *, 4> WorkList;
11192     std::swap(DelayedDllExportClasses, WorkList);
11193     for (CXXRecordDecl *Class : WorkList)
11194       ReferenceDllExportedMembers(*this, Class);
11195   }
11196 }
11197 
11198 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
11199                                          CXXDestructorDecl *Destructor) {
11200   assert(getLangOpts().CPlusPlus11 &&
11201          "adjusting dtor exception specs was introduced in c++11");
11202 
11203   // C++11 [class.dtor]p3:
11204   //   A declaration of a destructor that does not have an exception-
11205   //   specification is implicitly considered to have the same exception-
11206   //   specification as an implicit declaration.
11207   const FunctionProtoType *DtorType = Destructor->getType()->
11208                                         getAs<FunctionProtoType>();
11209   if (DtorType->hasExceptionSpec())
11210     return;
11211 
11212   // Replace the destructor's type, building off the existing one. Fortunately,
11213   // the only thing of interest in the destructor type is its extended info.
11214   // The return and arguments are fixed.
11215   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11216   EPI.ExceptionSpec.Type = EST_Unevaluated;
11217   EPI.ExceptionSpec.SourceDecl = Destructor;
11218   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11219 
11220   // FIXME: If the destructor has a body that could throw, and the newly created
11221   // spec doesn't allow exceptions, we should emit a warning, because this
11222   // change in behavior can break conforming C++03 programs at runtime.
11223   // However, we don't have a body or an exception specification yet, so it
11224   // needs to be done somewhere else.
11225 }
11226 
11227 namespace {
11228 /// An abstract base class for all helper classes used in building the
11229 //  copy/move operators. These classes serve as factory functions and help us
11230 //  avoid using the same Expr* in the AST twice.
11231 class ExprBuilder {
11232   ExprBuilder(const ExprBuilder&) = delete;
11233   ExprBuilder &operator=(const ExprBuilder&) = delete;
11234 
11235 protected:
11236   static Expr *assertNotNull(Expr *E) {
11237     assert(E && "Expression construction must not fail.");
11238     return E;
11239   }
11240 
11241 public:
11242   ExprBuilder() {}
11243   virtual ~ExprBuilder() {}
11244 
11245   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11246 };
11247 
11248 class RefBuilder: public ExprBuilder {
11249   VarDecl *Var;
11250   QualType VarType;
11251 
11252 public:
11253   Expr *build(Sema &S, SourceLocation Loc) const override {
11254     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11255   }
11256 
11257   RefBuilder(VarDecl *Var, QualType VarType)
11258       : Var(Var), VarType(VarType) {}
11259 };
11260 
11261 class ThisBuilder: public ExprBuilder {
11262 public:
11263   Expr *build(Sema &S, SourceLocation Loc) const override {
11264     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11265   }
11266 };
11267 
11268 class CastBuilder: public ExprBuilder {
11269   const ExprBuilder &Builder;
11270   QualType Type;
11271   ExprValueKind Kind;
11272   const CXXCastPath &Path;
11273 
11274 public:
11275   Expr *build(Sema &S, SourceLocation Loc) const override {
11276     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11277                                              CK_UncheckedDerivedToBase, Kind,
11278                                              &Path).get());
11279   }
11280 
11281   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11282               const CXXCastPath &Path)
11283       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11284 };
11285 
11286 class DerefBuilder: public ExprBuilder {
11287   const ExprBuilder &Builder;
11288 
11289 public:
11290   Expr *build(Sema &S, SourceLocation Loc) const override {
11291     return assertNotNull(
11292         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11293   }
11294 
11295   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11296 };
11297 
11298 class MemberBuilder: public ExprBuilder {
11299   const ExprBuilder &Builder;
11300   QualType Type;
11301   CXXScopeSpec SS;
11302   bool IsArrow;
11303   LookupResult &MemberLookup;
11304 
11305 public:
11306   Expr *build(Sema &S, SourceLocation Loc) const override {
11307     return assertNotNull(S.BuildMemberReferenceExpr(
11308         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11309         nullptr, MemberLookup, nullptr, nullptr).get());
11310   }
11311 
11312   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11313                 LookupResult &MemberLookup)
11314       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11315         MemberLookup(MemberLookup) {}
11316 };
11317 
11318 class MoveCastBuilder: public ExprBuilder {
11319   const ExprBuilder &Builder;
11320 
11321 public:
11322   Expr *build(Sema &S, SourceLocation Loc) const override {
11323     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11324   }
11325 
11326   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11327 };
11328 
11329 class LvalueConvBuilder: public ExprBuilder {
11330   const ExprBuilder &Builder;
11331 
11332 public:
11333   Expr *build(Sema &S, SourceLocation Loc) const override {
11334     return assertNotNull(
11335         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11336   }
11337 
11338   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11339 };
11340 
11341 class SubscriptBuilder: public ExprBuilder {
11342   const ExprBuilder &Base;
11343   const ExprBuilder &Index;
11344 
11345 public:
11346   Expr *build(Sema &S, SourceLocation Loc) const override {
11347     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11348         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11349   }
11350 
11351   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11352       : Base(Base), Index(Index) {}
11353 };
11354 
11355 } // end anonymous namespace
11356 
11357 /// When generating a defaulted copy or move assignment operator, if a field
11358 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11359 /// do so. This optimization only applies for arrays of scalars, and for arrays
11360 /// of class type where the selected copy/move-assignment operator is trivial.
11361 static StmtResult
11362 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11363                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11364   // Compute the size of the memory buffer to be copied.
11365   QualType SizeType = S.Context.getSizeType();
11366   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11367                    S.Context.getTypeSizeInChars(T).getQuantity());
11368 
11369   // Take the address of the field references for "from" and "to". We
11370   // directly construct UnaryOperators here because semantic analysis
11371   // does not permit us to take the address of an xvalue.
11372   Expr *From = FromB.build(S, Loc);
11373   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11374                          S.Context.getPointerType(From->getType()),
11375                          VK_RValue, OK_Ordinary, Loc, false);
11376   Expr *To = ToB.build(S, Loc);
11377   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11378                        S.Context.getPointerType(To->getType()),
11379                        VK_RValue, OK_Ordinary, Loc, false);
11380 
11381   const Type *E = T->getBaseElementTypeUnsafe();
11382   bool NeedsCollectableMemCpy =
11383     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11384 
11385   // Create a reference to the __builtin_objc_memmove_collectable function
11386   StringRef MemCpyName = NeedsCollectableMemCpy ?
11387     "__builtin_objc_memmove_collectable" :
11388     "__builtin_memcpy";
11389   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11390                  Sema::LookupOrdinaryName);
11391   S.LookupName(R, S.TUScope, true);
11392 
11393   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11394   if (!MemCpy)
11395     // Something went horribly wrong earlier, and we will have complained
11396     // about it.
11397     return StmtError();
11398 
11399   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11400                                             VK_RValue, Loc, nullptr);
11401   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11402 
11403   Expr *CallArgs[] = {
11404     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11405   };
11406   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11407                                     Loc, CallArgs, Loc);
11408 
11409   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11410   return Call.getAs<Stmt>();
11411 }
11412 
11413 /// Builds a statement that copies/moves the given entity from \p From to
11414 /// \c To.
11415 ///
11416 /// This routine is used to copy/move the members of a class with an
11417 /// implicitly-declared copy/move assignment operator. When the entities being
11418 /// copied are arrays, this routine builds for loops to copy them.
11419 ///
11420 /// \param S The Sema object used for type-checking.
11421 ///
11422 /// \param Loc The location where the implicit copy/move is being generated.
11423 ///
11424 /// \param T The type of the expressions being copied/moved. Both expressions
11425 /// must have this type.
11426 ///
11427 /// \param To The expression we are copying/moving to.
11428 ///
11429 /// \param From The expression we are copying/moving from.
11430 ///
11431 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11432 /// Otherwise, it's a non-static member subobject.
11433 ///
11434 /// \param Copying Whether we're copying or moving.
11435 ///
11436 /// \param Depth Internal parameter recording the depth of the recursion.
11437 ///
11438 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11439 /// if a memcpy should be used instead.
11440 static StmtResult
11441 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11442                                  const ExprBuilder &To, const ExprBuilder &From,
11443                                  bool CopyingBaseSubobject, bool Copying,
11444                                  unsigned Depth = 0) {
11445   // C++11 [class.copy]p28:
11446   //   Each subobject is assigned in the manner appropriate to its type:
11447   //
11448   //     - if the subobject is of class type, as if by a call to operator= with
11449   //       the subobject as the object expression and the corresponding
11450   //       subobject of x as a single function argument (as if by explicit
11451   //       qualification; that is, ignoring any possible virtual overriding
11452   //       functions in more derived classes);
11453   //
11454   // C++03 [class.copy]p13:
11455   //     - if the subobject is of class type, the copy assignment operator for
11456   //       the class is used (as if by explicit qualification; that is,
11457   //       ignoring any possible virtual overriding functions in more derived
11458   //       classes);
11459   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11460     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11461 
11462     // Look for operator=.
11463     DeclarationName Name
11464       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11465     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11466     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11467 
11468     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11469     // operator.
11470     if (!S.getLangOpts().CPlusPlus11) {
11471       LookupResult::Filter F = OpLookup.makeFilter();
11472       while (F.hasNext()) {
11473         NamedDecl *D = F.next();
11474         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11475           if (Method->isCopyAssignmentOperator() ||
11476               (!Copying && Method->isMoveAssignmentOperator()))
11477             continue;
11478 
11479         F.erase();
11480       }
11481       F.done();
11482     }
11483 
11484     // Suppress the protected check (C++ [class.protected]) for each of the
11485     // assignment operators we found. This strange dance is required when
11486     // we're assigning via a base classes's copy-assignment operator. To
11487     // ensure that we're getting the right base class subobject (without
11488     // ambiguities), we need to cast "this" to that subobject type; to
11489     // ensure that we don't go through the virtual call mechanism, we need
11490     // to qualify the operator= name with the base class (see below). However,
11491     // this means that if the base class has a protected copy assignment
11492     // operator, the protected member access check will fail. So, we
11493     // rewrite "protected" access to "public" access in this case, since we
11494     // know by construction that we're calling from a derived class.
11495     if (CopyingBaseSubobject) {
11496       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11497            L != LEnd; ++L) {
11498         if (L.getAccess() == AS_protected)
11499           L.setAccess(AS_public);
11500       }
11501     }
11502 
11503     // Create the nested-name-specifier that will be used to qualify the
11504     // reference to operator=; this is required to suppress the virtual
11505     // call mechanism.
11506     CXXScopeSpec SS;
11507     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11508     SS.MakeTrivial(S.Context,
11509                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11510                                                CanonicalT),
11511                    Loc);
11512 
11513     // Create the reference to operator=.
11514     ExprResult OpEqualRef
11515       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11516                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11517                                    /*FirstQualifierInScope=*/nullptr,
11518                                    OpLookup,
11519                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11520                                    /*SuppressQualifierCheck=*/true);
11521     if (OpEqualRef.isInvalid())
11522       return StmtError();
11523 
11524     // Build the call to the assignment operator.
11525 
11526     Expr *FromInst = From.build(S, Loc);
11527     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11528                                                   OpEqualRef.getAs<Expr>(),
11529                                                   Loc, FromInst, Loc);
11530     if (Call.isInvalid())
11531       return StmtError();
11532 
11533     // If we built a call to a trivial 'operator=' while copying an array,
11534     // bail out. We'll replace the whole shebang with a memcpy.
11535     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11536     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11537       return StmtResult((Stmt*)nullptr);
11538 
11539     // Convert to an expression-statement, and clean up any produced
11540     // temporaries.
11541     return S.ActOnExprStmt(Call);
11542   }
11543 
11544   //     - if the subobject is of scalar type, the built-in assignment
11545   //       operator is used.
11546   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11547   if (!ArrayTy) {
11548     ExprResult Assignment = S.CreateBuiltinBinOp(
11549         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11550     if (Assignment.isInvalid())
11551       return StmtError();
11552     return S.ActOnExprStmt(Assignment);
11553   }
11554 
11555   //     - if the subobject is an array, each element is assigned, in the
11556   //       manner appropriate to the element type;
11557 
11558   // Construct a loop over the array bounds, e.g.,
11559   //
11560   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11561   //
11562   // that will copy each of the array elements.
11563   QualType SizeType = S.Context.getSizeType();
11564 
11565   // Create the iteration variable.
11566   IdentifierInfo *IterationVarName = nullptr;
11567   {
11568     SmallString<8> Str;
11569     llvm::raw_svector_ostream OS(Str);
11570     OS << "__i" << Depth;
11571     IterationVarName = &S.Context.Idents.get(OS.str());
11572   }
11573   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11574                                           IterationVarName, SizeType,
11575                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11576                                           SC_None);
11577 
11578   // Initialize the iteration variable to zero.
11579   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11580   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11581 
11582   // Creates a reference to the iteration variable.
11583   RefBuilder IterationVarRef(IterationVar, SizeType);
11584   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11585 
11586   // Create the DeclStmt that holds the iteration variable.
11587   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11588 
11589   // Subscript the "from" and "to" expressions with the iteration variable.
11590   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11591   MoveCastBuilder FromIndexMove(FromIndexCopy);
11592   const ExprBuilder *FromIndex;
11593   if (Copying)
11594     FromIndex = &FromIndexCopy;
11595   else
11596     FromIndex = &FromIndexMove;
11597 
11598   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11599 
11600   // Build the copy/move for an individual element of the array.
11601   StmtResult Copy =
11602     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11603                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11604                                      Copying, Depth + 1);
11605   // Bail out if copying fails or if we determined that we should use memcpy.
11606   if (Copy.isInvalid() || !Copy.get())
11607     return Copy;
11608 
11609   // Create the comparison against the array bound.
11610   llvm::APInt Upper
11611     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11612   Expr *Comparison
11613     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11614                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11615                                      BO_NE, S.Context.BoolTy,
11616                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11617 
11618   // Create the pre-increment of the iteration variable. We can determine
11619   // whether the increment will overflow based on the value of the array
11620   // bound.
11621   Expr *Increment = new (S.Context)
11622       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11623                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11624 
11625   // Construct the loop that copies all elements of this array.
11626   return S.ActOnForStmt(
11627       Loc, Loc, InitStmt,
11628       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11629       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11630 }
11631 
11632 static StmtResult
11633 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11634                       const ExprBuilder &To, const ExprBuilder &From,
11635                       bool CopyingBaseSubobject, bool Copying) {
11636   // Maybe we should use a memcpy?
11637   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11638       T.isTriviallyCopyableType(S.Context))
11639     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11640 
11641   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11642                                                      CopyingBaseSubobject,
11643                                                      Copying, 0));
11644 
11645   // If we ended up picking a trivial assignment operator for an array of a
11646   // non-trivially-copyable class type, just emit a memcpy.
11647   if (!Result.isInvalid() && !Result.get())
11648     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11649 
11650   return Result;
11651 }
11652 
11653 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11654   // Note: The following rules are largely analoguous to the copy
11655   // constructor rules. Note that virtual bases are not taken into account
11656   // for determining the argument type of the operator. Note also that
11657   // operators taking an object instead of a reference are allowed.
11658   assert(ClassDecl->needsImplicitCopyAssignment());
11659 
11660   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11661   if (DSM.isAlreadyBeingDeclared())
11662     return nullptr;
11663 
11664   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11665   QualType RetType = Context.getLValueReferenceType(ArgType);
11666   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11667   if (Const)
11668     ArgType = ArgType.withConst();
11669   ArgType = Context.getLValueReferenceType(ArgType);
11670 
11671   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11672                                                      CXXCopyAssignment,
11673                                                      Const);
11674 
11675   //   An implicitly-declared copy assignment operator is an inline public
11676   //   member of its class.
11677   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11678   SourceLocation ClassLoc = ClassDecl->getLocation();
11679   DeclarationNameInfo NameInfo(Name, ClassLoc);
11680   CXXMethodDecl *CopyAssignment =
11681       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11682                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11683                             /*isInline=*/true, Constexpr, SourceLocation());
11684   CopyAssignment->setAccess(AS_public);
11685   CopyAssignment->setDefaulted();
11686   CopyAssignment->setImplicit();
11687 
11688   if (getLangOpts().CUDA) {
11689     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11690                                             CopyAssignment,
11691                                             /* ConstRHS */ Const,
11692                                             /* Diagnose */ false);
11693   }
11694 
11695   // Build an exception specification pointing back at this member.
11696   FunctionProtoType::ExtProtoInfo EPI =
11697       getImplicitMethodEPI(*this, CopyAssignment);
11698   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11699 
11700   // Add the parameter to the operator.
11701   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11702                                                ClassLoc, ClassLoc,
11703                                                /*Id=*/nullptr, ArgType,
11704                                                /*TInfo=*/nullptr, SC_None,
11705                                                nullptr);
11706   CopyAssignment->setParams(FromParam);
11707 
11708   CopyAssignment->setTrivial(
11709     ClassDecl->needsOverloadResolutionForCopyAssignment()
11710       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11711       : ClassDecl->hasTrivialCopyAssignment());
11712 
11713   // Note that we have added this copy-assignment operator.
11714   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11715 
11716   Scope *S = getScopeForContext(ClassDecl);
11717   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11718 
11719   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11720     SetDeclDeleted(CopyAssignment, ClassLoc);
11721 
11722   if (S)
11723     PushOnScopeChains(CopyAssignment, S, false);
11724   ClassDecl->addDecl(CopyAssignment);
11725 
11726   return CopyAssignment;
11727 }
11728 
11729 /// Diagnose an implicit copy operation for a class which is odr-used, but
11730 /// which is deprecated because the class has a user-declared copy constructor,
11731 /// copy assignment operator, or destructor.
11732 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11733   assert(CopyOp->isImplicit());
11734 
11735   CXXRecordDecl *RD = CopyOp->getParent();
11736   CXXMethodDecl *UserDeclaredOperation = nullptr;
11737 
11738   // In Microsoft mode, assignment operations don't affect constructors and
11739   // vice versa.
11740   if (RD->hasUserDeclaredDestructor()) {
11741     UserDeclaredOperation = RD->getDestructor();
11742   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11743              RD->hasUserDeclaredCopyConstructor() &&
11744              !S.getLangOpts().MSVCCompat) {
11745     // Find any user-declared copy constructor.
11746     for (auto *I : RD->ctors()) {
11747       if (I->isCopyConstructor()) {
11748         UserDeclaredOperation = I;
11749         break;
11750       }
11751     }
11752     assert(UserDeclaredOperation);
11753   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11754              RD->hasUserDeclaredCopyAssignment() &&
11755              !S.getLangOpts().MSVCCompat) {
11756     // Find any user-declared move assignment operator.
11757     for (auto *I : RD->methods()) {
11758       if (I->isCopyAssignmentOperator()) {
11759         UserDeclaredOperation = I;
11760         break;
11761       }
11762     }
11763     assert(UserDeclaredOperation);
11764   }
11765 
11766   if (UserDeclaredOperation) {
11767     S.Diag(UserDeclaredOperation->getLocation(),
11768          diag::warn_deprecated_copy_operation)
11769       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11770       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11771   }
11772 }
11773 
11774 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11775                                         CXXMethodDecl *CopyAssignOperator) {
11776   assert((CopyAssignOperator->isDefaulted() &&
11777           CopyAssignOperator->isOverloadedOperator() &&
11778           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11779           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11780           !CopyAssignOperator->isDeleted()) &&
11781          "DefineImplicitCopyAssignment called for wrong function");
11782   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11783     return;
11784 
11785   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11786   if (ClassDecl->isInvalidDecl()) {
11787     CopyAssignOperator->setInvalidDecl();
11788     return;
11789   }
11790 
11791   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11792 
11793   // The exception specification is needed because we are defining the
11794   // function.
11795   ResolveExceptionSpec(CurrentLocation,
11796                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11797 
11798   // Add a context note for diagnostics produced after this point.
11799   Scope.addContextNote(CurrentLocation);
11800 
11801   // C++11 [class.copy]p18:
11802   //   The [definition of an implicitly declared copy assignment operator] is
11803   //   deprecated if the class has a user-declared copy constructor or a
11804   //   user-declared destructor.
11805   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11806     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11807 
11808   // C++0x [class.copy]p30:
11809   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11810   //   for a non-union class X performs memberwise copy assignment of its
11811   //   subobjects. The direct base classes of X are assigned first, in the
11812   //   order of their declaration in the base-specifier-list, and then the
11813   //   immediate non-static data members of X are assigned, in the order in
11814   //   which they were declared in the class definition.
11815 
11816   // The statements that form the synthesized function body.
11817   SmallVector<Stmt*, 8> Statements;
11818 
11819   // The parameter for the "other" object, which we are copying from.
11820   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11821   Qualifiers OtherQuals = Other->getType().getQualifiers();
11822   QualType OtherRefType = Other->getType();
11823   if (const LValueReferenceType *OtherRef
11824                                 = OtherRefType->getAs<LValueReferenceType>()) {
11825     OtherRefType = OtherRef->getPointeeType();
11826     OtherQuals = OtherRefType.getQualifiers();
11827   }
11828 
11829   // Our location for everything implicitly-generated.
11830   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11831                            ? CopyAssignOperator->getEndLoc()
11832                            : CopyAssignOperator->getLocation();
11833 
11834   // Builds a DeclRefExpr for the "other" object.
11835   RefBuilder OtherRef(Other, OtherRefType);
11836 
11837   // Builds the "this" pointer.
11838   ThisBuilder This;
11839 
11840   // Assign base classes.
11841   bool Invalid = false;
11842   for (auto &Base : ClassDecl->bases()) {
11843     // Form the assignment:
11844     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11845     QualType BaseType = Base.getType().getUnqualifiedType();
11846     if (!BaseType->isRecordType()) {
11847       Invalid = true;
11848       continue;
11849     }
11850 
11851     CXXCastPath BasePath;
11852     BasePath.push_back(&Base);
11853 
11854     // Construct the "from" expression, which is an implicit cast to the
11855     // appropriately-qualified base type.
11856     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11857                      VK_LValue, BasePath);
11858 
11859     // Dereference "this".
11860     DerefBuilder DerefThis(This);
11861     CastBuilder To(DerefThis,
11862                    Context.getCVRQualifiedType(
11863                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11864                    VK_LValue, BasePath);
11865 
11866     // Build the copy.
11867     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11868                                             To, From,
11869                                             /*CopyingBaseSubobject=*/true,
11870                                             /*Copying=*/true);
11871     if (Copy.isInvalid()) {
11872       CopyAssignOperator->setInvalidDecl();
11873       return;
11874     }
11875 
11876     // Success! Record the copy.
11877     Statements.push_back(Copy.getAs<Expr>());
11878   }
11879 
11880   // Assign non-static members.
11881   for (auto *Field : ClassDecl->fields()) {
11882     // FIXME: We should form some kind of AST representation for the implied
11883     // memcpy in a union copy operation.
11884     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11885       continue;
11886 
11887     if (Field->isInvalidDecl()) {
11888       Invalid = true;
11889       continue;
11890     }
11891 
11892     // Check for members of reference type; we can't copy those.
11893     if (Field->getType()->isReferenceType()) {
11894       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11895         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11896       Diag(Field->getLocation(), diag::note_declared_at);
11897       Invalid = true;
11898       continue;
11899     }
11900 
11901     // Check for members of const-qualified, non-class type.
11902     QualType BaseType = Context.getBaseElementType(Field->getType());
11903     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11904       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11905         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11906       Diag(Field->getLocation(), diag::note_declared_at);
11907       Invalid = true;
11908       continue;
11909     }
11910 
11911     // Suppress assigning zero-width bitfields.
11912     if (Field->isZeroLengthBitField(Context))
11913       continue;
11914 
11915     QualType FieldType = Field->getType().getNonReferenceType();
11916     if (FieldType->isIncompleteArrayType()) {
11917       assert(ClassDecl->hasFlexibleArrayMember() &&
11918              "Incomplete array type is not valid");
11919       continue;
11920     }
11921 
11922     // Build references to the field in the object we're copying from and to.
11923     CXXScopeSpec SS; // Intentionally empty
11924     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11925                               LookupMemberName);
11926     MemberLookup.addDecl(Field);
11927     MemberLookup.resolveKind();
11928 
11929     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11930 
11931     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11932 
11933     // Build the copy of this field.
11934     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11935                                             To, From,
11936                                             /*CopyingBaseSubobject=*/false,
11937                                             /*Copying=*/true);
11938     if (Copy.isInvalid()) {
11939       CopyAssignOperator->setInvalidDecl();
11940       return;
11941     }
11942 
11943     // Success! Record the copy.
11944     Statements.push_back(Copy.getAs<Stmt>());
11945   }
11946 
11947   if (!Invalid) {
11948     // Add a "return *this;"
11949     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11950 
11951     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11952     if (Return.isInvalid())
11953       Invalid = true;
11954     else
11955       Statements.push_back(Return.getAs<Stmt>());
11956   }
11957 
11958   if (Invalid) {
11959     CopyAssignOperator->setInvalidDecl();
11960     return;
11961   }
11962 
11963   StmtResult Body;
11964   {
11965     CompoundScopeRAII CompoundScope(*this);
11966     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11967                              /*isStmtExpr=*/false);
11968     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11969   }
11970   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11971   CopyAssignOperator->markUsed(Context);
11972 
11973   if (ASTMutationListener *L = getASTMutationListener()) {
11974     L->CompletedImplicitDefinition(CopyAssignOperator);
11975   }
11976 }
11977 
11978 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11979   assert(ClassDecl->needsImplicitMoveAssignment());
11980 
11981   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11982   if (DSM.isAlreadyBeingDeclared())
11983     return nullptr;
11984 
11985   // Note: The following rules are largely analoguous to the move
11986   // constructor rules.
11987 
11988   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11989   QualType RetType = Context.getLValueReferenceType(ArgType);
11990   ArgType = Context.getRValueReferenceType(ArgType);
11991 
11992   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11993                                                      CXXMoveAssignment,
11994                                                      false);
11995 
11996   //   An implicitly-declared move assignment operator is an inline public
11997   //   member of its class.
11998   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11999   SourceLocation ClassLoc = ClassDecl->getLocation();
12000   DeclarationNameInfo NameInfo(Name, ClassLoc);
12001   CXXMethodDecl *MoveAssignment =
12002       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12003                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12004                             /*isInline=*/true, Constexpr, SourceLocation());
12005   MoveAssignment->setAccess(AS_public);
12006   MoveAssignment->setDefaulted();
12007   MoveAssignment->setImplicit();
12008 
12009   if (getLangOpts().CUDA) {
12010     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12011                                             MoveAssignment,
12012                                             /* ConstRHS */ false,
12013                                             /* Diagnose */ false);
12014   }
12015 
12016   // Build an exception specification pointing back at this member.
12017   FunctionProtoType::ExtProtoInfo EPI =
12018       getImplicitMethodEPI(*this, MoveAssignment);
12019   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12020 
12021   // Add the parameter to the operator.
12022   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12023                                                ClassLoc, ClassLoc,
12024                                                /*Id=*/nullptr, ArgType,
12025                                                /*TInfo=*/nullptr, SC_None,
12026                                                nullptr);
12027   MoveAssignment->setParams(FromParam);
12028 
12029   MoveAssignment->setTrivial(
12030     ClassDecl->needsOverloadResolutionForMoveAssignment()
12031       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12032       : ClassDecl->hasTrivialMoveAssignment());
12033 
12034   // Note that we have added this copy-assignment operator.
12035   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12036 
12037   Scope *S = getScopeForContext(ClassDecl);
12038   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12039 
12040   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12041     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12042     SetDeclDeleted(MoveAssignment, ClassLoc);
12043   }
12044 
12045   if (S)
12046     PushOnScopeChains(MoveAssignment, S, false);
12047   ClassDecl->addDecl(MoveAssignment);
12048 
12049   return MoveAssignment;
12050 }
12051 
12052 /// Check if we're implicitly defining a move assignment operator for a class
12053 /// with virtual bases. Such a move assignment might move-assign the virtual
12054 /// base multiple times.
12055 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12056                                                SourceLocation CurrentLocation) {
12057   assert(!Class->isDependentContext() && "should not define dependent move");
12058 
12059   // Only a virtual base could get implicitly move-assigned multiple times.
12060   // Only a non-trivial move assignment can observe this. We only want to
12061   // diagnose if we implicitly define an assignment operator that assigns
12062   // two base classes, both of which move-assign the same virtual base.
12063   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12064       Class->getNumBases() < 2)
12065     return;
12066 
12067   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12068   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12069   VBaseMap VBases;
12070 
12071   for (auto &BI : Class->bases()) {
12072     Worklist.push_back(&BI);
12073     while (!Worklist.empty()) {
12074       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12075       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12076 
12077       // If the base has no non-trivial move assignment operators,
12078       // we don't care about moves from it.
12079       if (!Base->hasNonTrivialMoveAssignment())
12080         continue;
12081 
12082       // If there's nothing virtual here, skip it.
12083       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12084         continue;
12085 
12086       // If we're not actually going to call a move assignment for this base,
12087       // or the selected move assignment is trivial, skip it.
12088       Sema::SpecialMemberOverloadResult SMOR =
12089         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12090                               /*ConstArg*/false, /*VolatileArg*/false,
12091                               /*RValueThis*/true, /*ConstThis*/false,
12092                               /*VolatileThis*/false);
12093       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12094           !SMOR.getMethod()->isMoveAssignmentOperator())
12095         continue;
12096 
12097       if (BaseSpec->isVirtual()) {
12098         // We're going to move-assign this virtual base, and its move
12099         // assignment operator is not trivial. If this can happen for
12100         // multiple distinct direct bases of Class, diagnose it. (If it
12101         // only happens in one base, we'll diagnose it when synthesizing
12102         // that base class's move assignment operator.)
12103         CXXBaseSpecifier *&Existing =
12104             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12105                 .first->second;
12106         if (Existing && Existing != &BI) {
12107           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12108             << Class << Base;
12109           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12110               << (Base->getCanonicalDecl() ==
12111                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12112               << Base << Existing->getType() << Existing->getSourceRange();
12113           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12114               << (Base->getCanonicalDecl() ==
12115                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12116               << Base << BI.getType() << BaseSpec->getSourceRange();
12117 
12118           // Only diagnose each vbase once.
12119           Existing = nullptr;
12120         }
12121       } else {
12122         // Only walk over bases that have defaulted move assignment operators.
12123         // We assume that any user-provided move assignment operator handles
12124         // the multiple-moves-of-vbase case itself somehow.
12125         if (!SMOR.getMethod()->isDefaulted())
12126           continue;
12127 
12128         // We're going to move the base classes of Base. Add them to the list.
12129         for (auto &BI : Base->bases())
12130           Worklist.push_back(&BI);
12131       }
12132     }
12133   }
12134 }
12135 
12136 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12137                                         CXXMethodDecl *MoveAssignOperator) {
12138   assert((MoveAssignOperator->isDefaulted() &&
12139           MoveAssignOperator->isOverloadedOperator() &&
12140           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12141           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12142           !MoveAssignOperator->isDeleted()) &&
12143          "DefineImplicitMoveAssignment called for wrong function");
12144   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12145     return;
12146 
12147   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12148   if (ClassDecl->isInvalidDecl()) {
12149     MoveAssignOperator->setInvalidDecl();
12150     return;
12151   }
12152 
12153   // C++0x [class.copy]p28:
12154   //   The implicitly-defined or move assignment operator for a non-union class
12155   //   X performs memberwise move assignment of its subobjects. The direct base
12156   //   classes of X are assigned first, in the order of their declaration in the
12157   //   base-specifier-list, and then the immediate non-static data members of X
12158   //   are assigned, in the order in which they were declared in the class
12159   //   definition.
12160 
12161   // Issue a warning if our implicit move assignment operator will move
12162   // from a virtual base more than once.
12163   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12164 
12165   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12166 
12167   // The exception specification is needed because we are defining the
12168   // function.
12169   ResolveExceptionSpec(CurrentLocation,
12170                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12171 
12172   // Add a context note for diagnostics produced after this point.
12173   Scope.addContextNote(CurrentLocation);
12174 
12175   // The statements that form the synthesized function body.
12176   SmallVector<Stmt*, 8> Statements;
12177 
12178   // The parameter for the "other" object, which we are move from.
12179   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12180   QualType OtherRefType = Other->getType()->
12181       getAs<RValueReferenceType>()->getPointeeType();
12182   assert(!OtherRefType.getQualifiers() &&
12183          "Bad argument type of defaulted move assignment");
12184 
12185   // Our location for everything implicitly-generated.
12186   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12187                            ? MoveAssignOperator->getEndLoc()
12188                            : MoveAssignOperator->getLocation();
12189 
12190   // Builds a reference to the "other" object.
12191   RefBuilder OtherRef(Other, OtherRefType);
12192   // Cast to rvalue.
12193   MoveCastBuilder MoveOther(OtherRef);
12194 
12195   // Builds the "this" pointer.
12196   ThisBuilder This;
12197 
12198   // Assign base classes.
12199   bool Invalid = false;
12200   for (auto &Base : ClassDecl->bases()) {
12201     // C++11 [class.copy]p28:
12202     //   It is unspecified whether subobjects representing virtual base classes
12203     //   are assigned more than once by the implicitly-defined copy assignment
12204     //   operator.
12205     // FIXME: Do not assign to a vbase that will be assigned by some other base
12206     // class. For a move-assignment, this can result in the vbase being moved
12207     // multiple times.
12208 
12209     // Form the assignment:
12210     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12211     QualType BaseType = Base.getType().getUnqualifiedType();
12212     if (!BaseType->isRecordType()) {
12213       Invalid = true;
12214       continue;
12215     }
12216 
12217     CXXCastPath BasePath;
12218     BasePath.push_back(&Base);
12219 
12220     // Construct the "from" expression, which is an implicit cast to the
12221     // appropriately-qualified base type.
12222     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12223 
12224     // Dereference "this".
12225     DerefBuilder DerefThis(This);
12226 
12227     // Implicitly cast "this" to the appropriately-qualified base type.
12228     CastBuilder To(DerefThis,
12229                    Context.getCVRQualifiedType(
12230                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12231                    VK_LValue, BasePath);
12232 
12233     // Build the move.
12234     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12235                                             To, From,
12236                                             /*CopyingBaseSubobject=*/true,
12237                                             /*Copying=*/false);
12238     if (Move.isInvalid()) {
12239       MoveAssignOperator->setInvalidDecl();
12240       return;
12241     }
12242 
12243     // Success! Record the move.
12244     Statements.push_back(Move.getAs<Expr>());
12245   }
12246 
12247   // Assign non-static members.
12248   for (auto *Field : ClassDecl->fields()) {
12249     // FIXME: We should form some kind of AST representation for the implied
12250     // memcpy in a union copy operation.
12251     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12252       continue;
12253 
12254     if (Field->isInvalidDecl()) {
12255       Invalid = true;
12256       continue;
12257     }
12258 
12259     // Check for members of reference type; we can't move those.
12260     if (Field->getType()->isReferenceType()) {
12261       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12262         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12263       Diag(Field->getLocation(), diag::note_declared_at);
12264       Invalid = true;
12265       continue;
12266     }
12267 
12268     // Check for members of const-qualified, non-class type.
12269     QualType BaseType = Context.getBaseElementType(Field->getType());
12270     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12271       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12272         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12273       Diag(Field->getLocation(), diag::note_declared_at);
12274       Invalid = true;
12275       continue;
12276     }
12277 
12278     // Suppress assigning zero-width bitfields.
12279     if (Field->isZeroLengthBitField(Context))
12280       continue;
12281 
12282     QualType FieldType = Field->getType().getNonReferenceType();
12283     if (FieldType->isIncompleteArrayType()) {
12284       assert(ClassDecl->hasFlexibleArrayMember() &&
12285              "Incomplete array type is not valid");
12286       continue;
12287     }
12288 
12289     // Build references to the field in the object we're copying from and to.
12290     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12291                               LookupMemberName);
12292     MemberLookup.addDecl(Field);
12293     MemberLookup.resolveKind();
12294     MemberBuilder From(MoveOther, OtherRefType,
12295                        /*IsArrow=*/false, MemberLookup);
12296     MemberBuilder To(This, getCurrentThisType(),
12297                      /*IsArrow=*/true, MemberLookup);
12298 
12299     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12300         "Member reference with rvalue base must be rvalue except for reference "
12301         "members, which aren't allowed for move assignment.");
12302 
12303     // Build the move of this field.
12304     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12305                                             To, From,
12306                                             /*CopyingBaseSubobject=*/false,
12307                                             /*Copying=*/false);
12308     if (Move.isInvalid()) {
12309       MoveAssignOperator->setInvalidDecl();
12310       return;
12311     }
12312 
12313     // Success! Record the copy.
12314     Statements.push_back(Move.getAs<Stmt>());
12315   }
12316 
12317   if (!Invalid) {
12318     // Add a "return *this;"
12319     ExprResult ThisObj =
12320         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12321 
12322     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12323     if (Return.isInvalid())
12324       Invalid = true;
12325     else
12326       Statements.push_back(Return.getAs<Stmt>());
12327   }
12328 
12329   if (Invalid) {
12330     MoveAssignOperator->setInvalidDecl();
12331     return;
12332   }
12333 
12334   StmtResult Body;
12335   {
12336     CompoundScopeRAII CompoundScope(*this);
12337     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12338                              /*isStmtExpr=*/false);
12339     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12340   }
12341   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12342   MoveAssignOperator->markUsed(Context);
12343 
12344   if (ASTMutationListener *L = getASTMutationListener()) {
12345     L->CompletedImplicitDefinition(MoveAssignOperator);
12346   }
12347 }
12348 
12349 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12350                                                     CXXRecordDecl *ClassDecl) {
12351   // C++ [class.copy]p4:
12352   //   If the class definition does not explicitly declare a copy
12353   //   constructor, one is declared implicitly.
12354   assert(ClassDecl->needsImplicitCopyConstructor());
12355 
12356   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12357   if (DSM.isAlreadyBeingDeclared())
12358     return nullptr;
12359 
12360   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12361   QualType ArgType = ClassType;
12362   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12363   if (Const)
12364     ArgType = ArgType.withConst();
12365   ArgType = Context.getLValueReferenceType(ArgType);
12366 
12367   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12368                                                      CXXCopyConstructor,
12369                                                      Const);
12370 
12371   DeclarationName Name
12372     = Context.DeclarationNames.getCXXConstructorName(
12373                                            Context.getCanonicalType(ClassType));
12374   SourceLocation ClassLoc = ClassDecl->getLocation();
12375   DeclarationNameInfo NameInfo(Name, ClassLoc);
12376 
12377   //   An implicitly-declared copy constructor is an inline public
12378   //   member of its class.
12379   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12380       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12381       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12382       Constexpr);
12383   CopyConstructor->setAccess(AS_public);
12384   CopyConstructor->setDefaulted();
12385 
12386   if (getLangOpts().CUDA) {
12387     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12388                                             CopyConstructor,
12389                                             /* ConstRHS */ Const,
12390                                             /* Diagnose */ false);
12391   }
12392 
12393   // Build an exception specification pointing back at this member.
12394   FunctionProtoType::ExtProtoInfo EPI =
12395       getImplicitMethodEPI(*this, CopyConstructor);
12396   CopyConstructor->setType(
12397       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12398 
12399   // Add the parameter to the constructor.
12400   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12401                                                ClassLoc, ClassLoc,
12402                                                /*IdentifierInfo=*/nullptr,
12403                                                ArgType, /*TInfo=*/nullptr,
12404                                                SC_None, nullptr);
12405   CopyConstructor->setParams(FromParam);
12406 
12407   CopyConstructor->setTrivial(
12408       ClassDecl->needsOverloadResolutionForCopyConstructor()
12409           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12410           : ClassDecl->hasTrivialCopyConstructor());
12411 
12412   CopyConstructor->setTrivialForCall(
12413       ClassDecl->hasAttr<TrivialABIAttr>() ||
12414       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12415            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12416              TAH_ConsiderTrivialABI)
12417            : ClassDecl->hasTrivialCopyConstructorForCall()));
12418 
12419   // Note that we have declared this constructor.
12420   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12421 
12422   Scope *S = getScopeForContext(ClassDecl);
12423   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12424 
12425   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12426     ClassDecl->setImplicitCopyConstructorIsDeleted();
12427     SetDeclDeleted(CopyConstructor, ClassLoc);
12428   }
12429 
12430   if (S)
12431     PushOnScopeChains(CopyConstructor, S, false);
12432   ClassDecl->addDecl(CopyConstructor);
12433 
12434   return CopyConstructor;
12435 }
12436 
12437 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12438                                          CXXConstructorDecl *CopyConstructor) {
12439   assert((CopyConstructor->isDefaulted() &&
12440           CopyConstructor->isCopyConstructor() &&
12441           !CopyConstructor->doesThisDeclarationHaveABody() &&
12442           !CopyConstructor->isDeleted()) &&
12443          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12444   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12445     return;
12446 
12447   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12448   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12449 
12450   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12451 
12452   // The exception specification is needed because we are defining the
12453   // function.
12454   ResolveExceptionSpec(CurrentLocation,
12455                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12456   MarkVTableUsed(CurrentLocation, ClassDecl);
12457 
12458   // Add a context note for diagnostics produced after this point.
12459   Scope.addContextNote(CurrentLocation);
12460 
12461   // C++11 [class.copy]p7:
12462   //   The [definition of an implicitly declared copy constructor] is
12463   //   deprecated if the class has a user-declared copy assignment operator
12464   //   or a user-declared destructor.
12465   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12466     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12467 
12468   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12469     CopyConstructor->setInvalidDecl();
12470   }  else {
12471     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12472                              ? CopyConstructor->getEndLoc()
12473                              : CopyConstructor->getLocation();
12474     Sema::CompoundScopeRAII CompoundScope(*this);
12475     CopyConstructor->setBody(
12476         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12477     CopyConstructor->markUsed(Context);
12478   }
12479 
12480   if (ASTMutationListener *L = getASTMutationListener()) {
12481     L->CompletedImplicitDefinition(CopyConstructor);
12482   }
12483 }
12484 
12485 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12486                                                     CXXRecordDecl *ClassDecl) {
12487   assert(ClassDecl->needsImplicitMoveConstructor());
12488 
12489   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12490   if (DSM.isAlreadyBeingDeclared())
12491     return nullptr;
12492 
12493   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12494   QualType ArgType = Context.getRValueReferenceType(ClassType);
12495 
12496   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12497                                                      CXXMoveConstructor,
12498                                                      false);
12499 
12500   DeclarationName Name
12501     = Context.DeclarationNames.getCXXConstructorName(
12502                                            Context.getCanonicalType(ClassType));
12503   SourceLocation ClassLoc = ClassDecl->getLocation();
12504   DeclarationNameInfo NameInfo(Name, ClassLoc);
12505 
12506   // C++11 [class.copy]p11:
12507   //   An implicitly-declared copy/move constructor is an inline public
12508   //   member of its class.
12509   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12510       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12511       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12512       Constexpr);
12513   MoveConstructor->setAccess(AS_public);
12514   MoveConstructor->setDefaulted();
12515 
12516   if (getLangOpts().CUDA) {
12517     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12518                                             MoveConstructor,
12519                                             /* ConstRHS */ false,
12520                                             /* Diagnose */ false);
12521   }
12522 
12523   // Build an exception specification pointing back at this member.
12524   FunctionProtoType::ExtProtoInfo EPI =
12525       getImplicitMethodEPI(*this, MoveConstructor);
12526   MoveConstructor->setType(
12527       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12528 
12529   // Add the parameter to the constructor.
12530   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12531                                                ClassLoc, ClassLoc,
12532                                                /*IdentifierInfo=*/nullptr,
12533                                                ArgType, /*TInfo=*/nullptr,
12534                                                SC_None, nullptr);
12535   MoveConstructor->setParams(FromParam);
12536 
12537   MoveConstructor->setTrivial(
12538       ClassDecl->needsOverloadResolutionForMoveConstructor()
12539           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12540           : ClassDecl->hasTrivialMoveConstructor());
12541 
12542   MoveConstructor->setTrivialForCall(
12543       ClassDecl->hasAttr<TrivialABIAttr>() ||
12544       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12545            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12546                                     TAH_ConsiderTrivialABI)
12547            : ClassDecl->hasTrivialMoveConstructorForCall()));
12548 
12549   // Note that we have declared this constructor.
12550   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12551 
12552   Scope *S = getScopeForContext(ClassDecl);
12553   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12554 
12555   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12556     ClassDecl->setImplicitMoveConstructorIsDeleted();
12557     SetDeclDeleted(MoveConstructor, ClassLoc);
12558   }
12559 
12560   if (S)
12561     PushOnScopeChains(MoveConstructor, S, false);
12562   ClassDecl->addDecl(MoveConstructor);
12563 
12564   return MoveConstructor;
12565 }
12566 
12567 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12568                                          CXXConstructorDecl *MoveConstructor) {
12569   assert((MoveConstructor->isDefaulted() &&
12570           MoveConstructor->isMoveConstructor() &&
12571           !MoveConstructor->doesThisDeclarationHaveABody() &&
12572           !MoveConstructor->isDeleted()) &&
12573          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12574   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12575     return;
12576 
12577   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12578   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12579 
12580   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12581 
12582   // The exception specification is needed because we are defining the
12583   // function.
12584   ResolveExceptionSpec(CurrentLocation,
12585                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12586   MarkVTableUsed(CurrentLocation, ClassDecl);
12587 
12588   // Add a context note for diagnostics produced after this point.
12589   Scope.addContextNote(CurrentLocation);
12590 
12591   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12592     MoveConstructor->setInvalidDecl();
12593   } else {
12594     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12595                              ? MoveConstructor->getEndLoc()
12596                              : MoveConstructor->getLocation();
12597     Sema::CompoundScopeRAII CompoundScope(*this);
12598     MoveConstructor->setBody(ActOnCompoundStmt(
12599         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12600     MoveConstructor->markUsed(Context);
12601   }
12602 
12603   if (ASTMutationListener *L = getASTMutationListener()) {
12604     L->CompletedImplicitDefinition(MoveConstructor);
12605   }
12606 }
12607 
12608 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12609   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12610 }
12611 
12612 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12613                             SourceLocation CurrentLocation,
12614                             CXXConversionDecl *Conv) {
12615   SynthesizedFunctionScope Scope(*this, Conv);
12616   assert(!Conv->getReturnType()->isUndeducedType());
12617 
12618   CXXRecordDecl *Lambda = Conv->getParent();
12619   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12620   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12621 
12622   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12623     CallOp = InstantiateFunctionDeclaration(
12624         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12625     if (!CallOp)
12626       return;
12627 
12628     Invoker = InstantiateFunctionDeclaration(
12629         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12630     if (!Invoker)
12631       return;
12632   }
12633 
12634   if (CallOp->isInvalidDecl())
12635     return;
12636 
12637   // Mark the call operator referenced (and add to pending instantiations
12638   // if necessary).
12639   // For both the conversion and static-invoker template specializations
12640   // we construct their body's in this function, so no need to add them
12641   // to the PendingInstantiations.
12642   MarkFunctionReferenced(CurrentLocation, CallOp);
12643 
12644   // Fill in the __invoke function with a dummy implementation. IR generation
12645   // will fill in the actual details. Update its type in case it contained
12646   // an 'auto'.
12647   Invoker->markUsed(Context);
12648   Invoker->setReferenced();
12649   Invoker->setType(Conv->getReturnType()->getPointeeType());
12650   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12651 
12652   // Construct the body of the conversion function { return __invoke; }.
12653   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12654                                        VK_LValue, Conv->getLocation()).get();
12655   assert(FunctionRef && "Can't refer to __invoke function?");
12656   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12657   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12658                                      Conv->getLocation()));
12659   Conv->markUsed(Context);
12660   Conv->setReferenced();
12661 
12662   if (ASTMutationListener *L = getASTMutationListener()) {
12663     L->CompletedImplicitDefinition(Conv);
12664     L->CompletedImplicitDefinition(Invoker);
12665   }
12666 }
12667 
12668 
12669 
12670 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12671        SourceLocation CurrentLocation,
12672        CXXConversionDecl *Conv)
12673 {
12674   assert(!Conv->getParent()->isGenericLambda());
12675 
12676   SynthesizedFunctionScope Scope(*this, Conv);
12677 
12678   // Copy-initialize the lambda object as needed to capture it.
12679   Expr *This = ActOnCXXThis(CurrentLocation).get();
12680   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12681 
12682   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12683                                                         Conv->getLocation(),
12684                                                         Conv, DerefThis);
12685 
12686   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12687   // behavior.  Note that only the general conversion function does this
12688   // (since it's unusable otherwise); in the case where we inline the
12689   // block literal, it has block literal lifetime semantics.
12690   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12691     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12692                                           CK_CopyAndAutoreleaseBlockObject,
12693                                           BuildBlock.get(), nullptr, VK_RValue);
12694 
12695   if (BuildBlock.isInvalid()) {
12696     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12697     Conv->setInvalidDecl();
12698     return;
12699   }
12700 
12701   // Create the return statement that returns the block from the conversion
12702   // function.
12703   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12704   if (Return.isInvalid()) {
12705     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12706     Conv->setInvalidDecl();
12707     return;
12708   }
12709 
12710   // Set the body of the conversion function.
12711   Stmt *ReturnS = Return.get();
12712   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12713                                      Conv->getLocation()));
12714   Conv->markUsed(Context);
12715 
12716   // We're done; notify the mutation listener, if any.
12717   if (ASTMutationListener *L = getASTMutationListener()) {
12718     L->CompletedImplicitDefinition(Conv);
12719   }
12720 }
12721 
12722 /// Determine whether the given list arguments contains exactly one
12723 /// "real" (non-default) argument.
12724 static bool hasOneRealArgument(MultiExprArg Args) {
12725   switch (Args.size()) {
12726   case 0:
12727     return false;
12728 
12729   default:
12730     if (!Args[1]->isDefaultArgument())
12731       return false;
12732 
12733     LLVM_FALLTHROUGH;
12734   case 1:
12735     return !Args[0]->isDefaultArgument();
12736   }
12737 
12738   return false;
12739 }
12740 
12741 ExprResult
12742 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12743                             NamedDecl *FoundDecl,
12744                             CXXConstructorDecl *Constructor,
12745                             MultiExprArg ExprArgs,
12746                             bool HadMultipleCandidates,
12747                             bool IsListInitialization,
12748                             bool IsStdInitListInitialization,
12749                             bool RequiresZeroInit,
12750                             unsigned ConstructKind,
12751                             SourceRange ParenRange) {
12752   bool Elidable = false;
12753 
12754   // C++0x [class.copy]p34:
12755   //   When certain criteria are met, an implementation is allowed to
12756   //   omit the copy/move construction of a class object, even if the
12757   //   copy/move constructor and/or destructor for the object have
12758   //   side effects. [...]
12759   //     - when a temporary class object that has not been bound to a
12760   //       reference (12.2) would be copied/moved to a class object
12761   //       with the same cv-unqualified type, the copy/move operation
12762   //       can be omitted by constructing the temporary object
12763   //       directly into the target of the omitted copy/move
12764   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12765       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12766     Expr *SubExpr = ExprArgs[0];
12767     Elidable = SubExpr->isTemporaryObject(
12768         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12769   }
12770 
12771   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12772                                FoundDecl, Constructor,
12773                                Elidable, ExprArgs, HadMultipleCandidates,
12774                                IsListInitialization,
12775                                IsStdInitListInitialization, RequiresZeroInit,
12776                                ConstructKind, ParenRange);
12777 }
12778 
12779 ExprResult
12780 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12781                             NamedDecl *FoundDecl,
12782                             CXXConstructorDecl *Constructor,
12783                             bool Elidable,
12784                             MultiExprArg ExprArgs,
12785                             bool HadMultipleCandidates,
12786                             bool IsListInitialization,
12787                             bool IsStdInitListInitialization,
12788                             bool RequiresZeroInit,
12789                             unsigned ConstructKind,
12790                             SourceRange ParenRange) {
12791   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12792     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12793     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12794       return ExprError();
12795   }
12796 
12797   return BuildCXXConstructExpr(
12798       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12799       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12800       RequiresZeroInit, ConstructKind, ParenRange);
12801 }
12802 
12803 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12804 /// including handling of its default argument expressions.
12805 ExprResult
12806 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12807                             CXXConstructorDecl *Constructor,
12808                             bool Elidable,
12809                             MultiExprArg ExprArgs,
12810                             bool HadMultipleCandidates,
12811                             bool IsListInitialization,
12812                             bool IsStdInitListInitialization,
12813                             bool RequiresZeroInit,
12814                             unsigned ConstructKind,
12815                             SourceRange ParenRange) {
12816   assert(declaresSameEntity(
12817              Constructor->getParent(),
12818              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12819          "given constructor for wrong type");
12820   MarkFunctionReferenced(ConstructLoc, Constructor);
12821   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12822     return ExprError();
12823 
12824   return CXXConstructExpr::Create(
12825       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12826       ExprArgs, HadMultipleCandidates, IsListInitialization,
12827       IsStdInitListInitialization, RequiresZeroInit,
12828       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12829       ParenRange);
12830 }
12831 
12832 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12833   assert(Field->hasInClassInitializer());
12834 
12835   // If we already have the in-class initializer nothing needs to be done.
12836   if (Field->getInClassInitializer())
12837     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12838 
12839   // If we might have already tried and failed to instantiate, don't try again.
12840   if (Field->isInvalidDecl())
12841     return ExprError();
12842 
12843   // Maybe we haven't instantiated the in-class initializer. Go check the
12844   // pattern FieldDecl to see if it has one.
12845   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12846 
12847   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12848     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12849     DeclContext::lookup_result Lookup =
12850         ClassPattern->lookup(Field->getDeclName());
12851 
12852     // Lookup can return at most two results: the pattern for the field, or the
12853     // injected class name of the parent record. No other member can have the
12854     // same name as the field.
12855     // In modules mode, lookup can return multiple results (coming from
12856     // different modules).
12857     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12858            "more than two lookup results for field name");
12859     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12860     if (!Pattern) {
12861       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12862              "cannot have other non-field member with same name");
12863       for (auto L : Lookup)
12864         if (isa<FieldDecl>(L)) {
12865           Pattern = cast<FieldDecl>(L);
12866           break;
12867         }
12868       assert(Pattern && "We must have set the Pattern!");
12869     }
12870 
12871     if (!Pattern->hasInClassInitializer() ||
12872         InstantiateInClassInitializer(Loc, Field, Pattern,
12873                                       getTemplateInstantiationArgs(Field))) {
12874       // Don't diagnose this again.
12875       Field->setInvalidDecl();
12876       return ExprError();
12877     }
12878     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12879   }
12880 
12881   // DR1351:
12882   //   If the brace-or-equal-initializer of a non-static data member
12883   //   invokes a defaulted default constructor of its class or of an
12884   //   enclosing class in a potentially evaluated subexpression, the
12885   //   program is ill-formed.
12886   //
12887   // This resolution is unworkable: the exception specification of the
12888   // default constructor can be needed in an unevaluated context, in
12889   // particular, in the operand of a noexcept-expression, and we can be
12890   // unable to compute an exception specification for an enclosed class.
12891   //
12892   // Any attempt to resolve the exception specification of a defaulted default
12893   // constructor before the initializer is lexically complete will ultimately
12894   // come here at which point we can diagnose it.
12895   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12896   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12897       << OutermostClass << Field;
12898   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
12899   // Recover by marking the field invalid, unless we're in a SFINAE context.
12900   if (!isSFINAEContext())
12901     Field->setInvalidDecl();
12902   return ExprError();
12903 }
12904 
12905 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12906   if (VD->isInvalidDecl()) return;
12907 
12908   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12909   if (ClassDecl->isInvalidDecl()) return;
12910   if (ClassDecl->hasIrrelevantDestructor()) return;
12911   if (ClassDecl->isDependentContext()) return;
12912 
12913   if (VD->isNoDestroy(getASTContext()))
12914     return;
12915 
12916   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12917   MarkFunctionReferenced(VD->getLocation(), Destructor);
12918   CheckDestructorAccess(VD->getLocation(), Destructor,
12919                         PDiag(diag::err_access_dtor_var)
12920                         << VD->getDeclName()
12921                         << VD->getType());
12922   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12923 
12924   if (Destructor->isTrivial()) return;
12925   if (!VD->hasGlobalStorage()) return;
12926 
12927   // Emit warning for non-trivial dtor in global scope (a real global,
12928   // class-static, function-static).
12929   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12930 
12931   // TODO: this should be re-enabled for static locals by !CXAAtExit
12932   if (!VD->isStaticLocal())
12933     Diag(VD->getLocation(), diag::warn_global_destructor);
12934 }
12935 
12936 /// Given a constructor and the set of arguments provided for the
12937 /// constructor, convert the arguments and add any required default arguments
12938 /// to form a proper call to this constructor.
12939 ///
12940 /// \returns true if an error occurred, false otherwise.
12941 bool
12942 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12943                               MultiExprArg ArgsPtr,
12944                               SourceLocation Loc,
12945                               SmallVectorImpl<Expr*> &ConvertedArgs,
12946                               bool AllowExplicit,
12947                               bool IsListInitialization) {
12948   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12949   unsigned NumArgs = ArgsPtr.size();
12950   Expr **Args = ArgsPtr.data();
12951 
12952   const FunctionProtoType *Proto
12953     = Constructor->getType()->getAs<FunctionProtoType>();
12954   assert(Proto && "Constructor without a prototype?");
12955   unsigned NumParams = Proto->getNumParams();
12956 
12957   // If too few arguments are available, we'll fill in the rest with defaults.
12958   if (NumArgs < NumParams)
12959     ConvertedArgs.reserve(NumParams);
12960   else
12961     ConvertedArgs.reserve(NumArgs);
12962 
12963   VariadicCallType CallType =
12964     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12965   SmallVector<Expr *, 8> AllArgs;
12966   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12967                                         Proto, 0,
12968                                         llvm::makeArrayRef(Args, NumArgs),
12969                                         AllArgs,
12970                                         CallType, AllowExplicit,
12971                                         IsListInitialization);
12972   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12973 
12974   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12975 
12976   CheckConstructorCall(Constructor,
12977                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12978                        Proto, Loc);
12979 
12980   return Invalid;
12981 }
12982 
12983 static inline bool
12984 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12985                                        const FunctionDecl *FnDecl) {
12986   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12987   if (isa<NamespaceDecl>(DC)) {
12988     return SemaRef.Diag(FnDecl->getLocation(),
12989                         diag::err_operator_new_delete_declared_in_namespace)
12990       << FnDecl->getDeclName();
12991   }
12992 
12993   if (isa<TranslationUnitDecl>(DC) &&
12994       FnDecl->getStorageClass() == SC_Static) {
12995     return SemaRef.Diag(FnDecl->getLocation(),
12996                         diag::err_operator_new_delete_declared_static)
12997       << FnDecl->getDeclName();
12998   }
12999 
13000   return false;
13001 }
13002 
13003 static QualType
13004 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13005   QualType QTy = PtrTy->getPointeeType();
13006   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13007   return SemaRef.Context.getPointerType(QTy);
13008 }
13009 
13010 static inline bool
13011 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13012                             CanQualType ExpectedResultType,
13013                             CanQualType ExpectedFirstParamType,
13014                             unsigned DependentParamTypeDiag,
13015                             unsigned InvalidParamTypeDiag) {
13016   QualType ResultType =
13017       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13018 
13019   // Check that the result type is not dependent.
13020   if (ResultType->isDependentType())
13021     return SemaRef.Diag(FnDecl->getLocation(),
13022                         diag::err_operator_new_delete_dependent_result_type)
13023     << FnDecl->getDeclName() << ExpectedResultType;
13024 
13025   // OpenCL C++: the operator is valid on any address space.
13026   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13027     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13028       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13029     }
13030   }
13031 
13032   // Check that the result type is what we expect.
13033   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13034     return SemaRef.Diag(FnDecl->getLocation(),
13035                         diag::err_operator_new_delete_invalid_result_type)
13036     << FnDecl->getDeclName() << ExpectedResultType;
13037 
13038   // A function template must have at least 2 parameters.
13039   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13040     return SemaRef.Diag(FnDecl->getLocation(),
13041                       diag::err_operator_new_delete_template_too_few_parameters)
13042         << FnDecl->getDeclName();
13043 
13044   // The function decl must have at least 1 parameter.
13045   if (FnDecl->getNumParams() == 0)
13046     return SemaRef.Diag(FnDecl->getLocation(),
13047                         diag::err_operator_new_delete_too_few_parameters)
13048       << FnDecl->getDeclName();
13049 
13050   // Check the first parameter type is not dependent.
13051   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13052   if (FirstParamType->isDependentType())
13053     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13054       << FnDecl->getDeclName() << ExpectedFirstParamType;
13055 
13056   // Check that the first parameter type is what we expect.
13057   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13058     // OpenCL C++: the operator is valid on any address space.
13059     if (auto *PtrTy =
13060             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13061       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13062     }
13063   }
13064   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13065       ExpectedFirstParamType)
13066     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13067     << FnDecl->getDeclName() << ExpectedFirstParamType;
13068 
13069   return false;
13070 }
13071 
13072 static bool
13073 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13074   // C++ [basic.stc.dynamic.allocation]p1:
13075   //   A program is ill-formed if an allocation function is declared in a
13076   //   namespace scope other than global scope or declared static in global
13077   //   scope.
13078   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13079     return true;
13080 
13081   CanQualType SizeTy =
13082     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13083 
13084   // C++ [basic.stc.dynamic.allocation]p1:
13085   //  The return type shall be void*. The first parameter shall have type
13086   //  std::size_t.
13087   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13088                                   SizeTy,
13089                                   diag::err_operator_new_dependent_param_type,
13090                                   diag::err_operator_new_param_type))
13091     return true;
13092 
13093   // C++ [basic.stc.dynamic.allocation]p1:
13094   //  The first parameter shall not have an associated default argument.
13095   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13096     return SemaRef.Diag(FnDecl->getLocation(),
13097                         diag::err_operator_new_default_arg)
13098       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13099 
13100   return false;
13101 }
13102 
13103 static bool
13104 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13105   // C++ [basic.stc.dynamic.deallocation]p1:
13106   //   A program is ill-formed if deallocation functions are declared in a
13107   //   namespace scope other than global scope or declared static in global
13108   //   scope.
13109   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13110     return true;
13111 
13112   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13113 
13114   // C++ P0722:
13115   //   Within a class C, the first parameter of a destroying operator delete
13116   //   shall be of type C *. The first parameter of any other deallocation
13117   //   function shall be of type void *.
13118   CanQualType ExpectedFirstParamType =
13119       MD && MD->isDestroyingOperatorDelete()
13120           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13121                 SemaRef.Context.getRecordType(MD->getParent())))
13122           : SemaRef.Context.VoidPtrTy;
13123 
13124   // C++ [basic.stc.dynamic.deallocation]p2:
13125   //   Each deallocation function shall return void
13126   if (CheckOperatorNewDeleteTypes(
13127           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13128           diag::err_operator_delete_dependent_param_type,
13129           diag::err_operator_delete_param_type))
13130     return true;
13131 
13132   // C++ P0722:
13133   //   A destroying operator delete shall be a usual deallocation function.
13134   if (MD && !MD->getParent()->isDependentContext() &&
13135       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
13136     SemaRef.Diag(MD->getLocation(),
13137                  diag::err_destroying_operator_delete_not_usual);
13138     return true;
13139   }
13140 
13141   return false;
13142 }
13143 
13144 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13145 /// of this overloaded operator is well-formed. If so, returns false;
13146 /// otherwise, emits appropriate diagnostics and returns true.
13147 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13148   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13149          "Expected an overloaded operator declaration");
13150 
13151   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13152 
13153   // C++ [over.oper]p5:
13154   //   The allocation and deallocation functions, operator new,
13155   //   operator new[], operator delete and operator delete[], are
13156   //   described completely in 3.7.3. The attributes and restrictions
13157   //   found in the rest of this subclause do not apply to them unless
13158   //   explicitly stated in 3.7.3.
13159   if (Op == OO_Delete || Op == OO_Array_Delete)
13160     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13161 
13162   if (Op == OO_New || Op == OO_Array_New)
13163     return CheckOperatorNewDeclaration(*this, FnDecl);
13164 
13165   // C++ [over.oper]p6:
13166   //   An operator function shall either be a non-static member
13167   //   function or be a non-member function and have at least one
13168   //   parameter whose type is a class, a reference to a class, an
13169   //   enumeration, or a reference to an enumeration.
13170   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13171     if (MethodDecl->isStatic())
13172       return Diag(FnDecl->getLocation(),
13173                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13174   } else {
13175     bool ClassOrEnumParam = false;
13176     for (auto Param : FnDecl->parameters()) {
13177       QualType ParamType = Param->getType().getNonReferenceType();
13178       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13179           ParamType->isEnumeralType()) {
13180         ClassOrEnumParam = true;
13181         break;
13182       }
13183     }
13184 
13185     if (!ClassOrEnumParam)
13186       return Diag(FnDecl->getLocation(),
13187                   diag::err_operator_overload_needs_class_or_enum)
13188         << FnDecl->getDeclName();
13189   }
13190 
13191   // C++ [over.oper]p8:
13192   //   An operator function cannot have default arguments (8.3.6),
13193   //   except where explicitly stated below.
13194   //
13195   // Only the function-call operator allows default arguments
13196   // (C++ [over.call]p1).
13197   if (Op != OO_Call) {
13198     for (auto Param : FnDecl->parameters()) {
13199       if (Param->hasDefaultArg())
13200         return Diag(Param->getLocation(),
13201                     diag::err_operator_overload_default_arg)
13202           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13203     }
13204   }
13205 
13206   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13207     { false, false, false }
13208 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13209     , { Unary, Binary, MemberOnly }
13210 #include "clang/Basic/OperatorKinds.def"
13211   };
13212 
13213   bool CanBeUnaryOperator = OperatorUses[Op][0];
13214   bool CanBeBinaryOperator = OperatorUses[Op][1];
13215   bool MustBeMemberOperator = OperatorUses[Op][2];
13216 
13217   // C++ [over.oper]p8:
13218   //   [...] Operator functions cannot have more or fewer parameters
13219   //   than the number required for the corresponding operator, as
13220   //   described in the rest of this subclause.
13221   unsigned NumParams = FnDecl->getNumParams()
13222                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13223   if (Op != OO_Call &&
13224       ((NumParams == 1 && !CanBeUnaryOperator) ||
13225        (NumParams == 2 && !CanBeBinaryOperator) ||
13226        (NumParams < 1) || (NumParams > 2))) {
13227     // We have the wrong number of parameters.
13228     unsigned ErrorKind;
13229     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13230       ErrorKind = 2;  // 2 -> unary or binary.
13231     } else if (CanBeUnaryOperator) {
13232       ErrorKind = 0;  // 0 -> unary
13233     } else {
13234       assert(CanBeBinaryOperator &&
13235              "All non-call overloaded operators are unary or binary!");
13236       ErrorKind = 1;  // 1 -> binary
13237     }
13238 
13239     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13240       << FnDecl->getDeclName() << NumParams << ErrorKind;
13241   }
13242 
13243   // Overloaded operators other than operator() cannot be variadic.
13244   if (Op != OO_Call &&
13245       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13246     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13247       << FnDecl->getDeclName();
13248   }
13249 
13250   // Some operators must be non-static member functions.
13251   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13252     return Diag(FnDecl->getLocation(),
13253                 diag::err_operator_overload_must_be_member)
13254       << FnDecl->getDeclName();
13255   }
13256 
13257   // C++ [over.inc]p1:
13258   //   The user-defined function called operator++ implements the
13259   //   prefix and postfix ++ operator. If this function is a member
13260   //   function with no parameters, or a non-member function with one
13261   //   parameter of class or enumeration type, it defines the prefix
13262   //   increment operator ++ for objects of that type. If the function
13263   //   is a member function with one parameter (which shall be of type
13264   //   int) or a non-member function with two parameters (the second
13265   //   of which shall be of type int), it defines the postfix
13266   //   increment operator ++ for objects of that type.
13267   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13268     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13269     QualType ParamType = LastParam->getType();
13270 
13271     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13272         !ParamType->isDependentType())
13273       return Diag(LastParam->getLocation(),
13274                   diag::err_operator_overload_post_incdec_must_be_int)
13275         << LastParam->getType() << (Op == OO_MinusMinus);
13276   }
13277 
13278   return false;
13279 }
13280 
13281 static bool
13282 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13283                                           FunctionTemplateDecl *TpDecl) {
13284   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13285 
13286   // Must have one or two template parameters.
13287   if (TemplateParams->size() == 1) {
13288     NonTypeTemplateParmDecl *PmDecl =
13289         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13290 
13291     // The template parameter must be a char parameter pack.
13292     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13293         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13294       return false;
13295 
13296   } else if (TemplateParams->size() == 2) {
13297     TemplateTypeParmDecl *PmType =
13298         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13299     NonTypeTemplateParmDecl *PmArgs =
13300         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13301 
13302     // The second template parameter must be a parameter pack with the
13303     // first template parameter as its type.
13304     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13305         PmArgs->isTemplateParameterPack()) {
13306       const TemplateTypeParmType *TArgs =
13307           PmArgs->getType()->getAs<TemplateTypeParmType>();
13308       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13309           TArgs->getIndex() == PmType->getIndex()) {
13310         if (!SemaRef.inTemplateInstantiation())
13311           SemaRef.Diag(TpDecl->getLocation(),
13312                        diag::ext_string_literal_operator_template);
13313         return false;
13314       }
13315     }
13316   }
13317 
13318   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13319                diag::err_literal_operator_template)
13320       << TpDecl->getTemplateParameters()->getSourceRange();
13321   return true;
13322 }
13323 
13324 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13325 /// of this literal operator function is well-formed. If so, returns
13326 /// false; otherwise, emits appropriate diagnostics and returns true.
13327 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13328   if (isa<CXXMethodDecl>(FnDecl)) {
13329     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13330       << FnDecl->getDeclName();
13331     return true;
13332   }
13333 
13334   if (FnDecl->isExternC()) {
13335     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13336     if (const LinkageSpecDecl *LSD =
13337             FnDecl->getDeclContext()->getExternCContext())
13338       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13339     return true;
13340   }
13341 
13342   // This might be the definition of a literal operator template.
13343   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13344 
13345   // This might be a specialization of a literal operator template.
13346   if (!TpDecl)
13347     TpDecl = FnDecl->getPrimaryTemplate();
13348 
13349   // template <char...> type operator "" name() and
13350   // template <class T, T...> type operator "" name() are the only valid
13351   // template signatures, and the only valid signatures with no parameters.
13352   if (TpDecl) {
13353     if (FnDecl->param_size() != 0) {
13354       Diag(FnDecl->getLocation(),
13355            diag::err_literal_operator_template_with_params);
13356       return true;
13357     }
13358 
13359     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13360       return true;
13361 
13362   } else if (FnDecl->param_size() == 1) {
13363     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13364 
13365     QualType ParamType = Param->getType().getUnqualifiedType();
13366 
13367     // Only unsigned long long int, long double, any character type, and const
13368     // char * are allowed as the only parameters.
13369     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13370         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13371         Context.hasSameType(ParamType, Context.CharTy) ||
13372         Context.hasSameType(ParamType, Context.WideCharTy) ||
13373         Context.hasSameType(ParamType, Context.Char8Ty) ||
13374         Context.hasSameType(ParamType, Context.Char16Ty) ||
13375         Context.hasSameType(ParamType, Context.Char32Ty)) {
13376     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13377       QualType InnerType = Ptr->getPointeeType();
13378 
13379       // Pointer parameter must be a const char *.
13380       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13381                                 Context.CharTy) &&
13382             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13383         Diag(Param->getSourceRange().getBegin(),
13384              diag::err_literal_operator_param)
13385             << ParamType << "'const char *'" << Param->getSourceRange();
13386         return true;
13387       }
13388 
13389     } else if (ParamType->isRealFloatingType()) {
13390       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13391           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13392       return true;
13393 
13394     } else if (ParamType->isIntegerType()) {
13395       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13396           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13397       return true;
13398 
13399     } else {
13400       Diag(Param->getSourceRange().getBegin(),
13401            diag::err_literal_operator_invalid_param)
13402           << ParamType << Param->getSourceRange();
13403       return true;
13404     }
13405 
13406   } else if (FnDecl->param_size() == 2) {
13407     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13408 
13409     // First, verify that the first parameter is correct.
13410 
13411     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13412 
13413     // Two parameter function must have a pointer to const as a
13414     // first parameter; let's strip those qualifiers.
13415     const PointerType *PT = FirstParamType->getAs<PointerType>();
13416 
13417     if (!PT) {
13418       Diag((*Param)->getSourceRange().getBegin(),
13419            diag::err_literal_operator_param)
13420           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13421       return true;
13422     }
13423 
13424     QualType PointeeType = PT->getPointeeType();
13425     // First parameter must be const
13426     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13427       Diag((*Param)->getSourceRange().getBegin(),
13428            diag::err_literal_operator_param)
13429           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13430       return true;
13431     }
13432 
13433     QualType InnerType = PointeeType.getUnqualifiedType();
13434     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13435     // const char32_t* are allowed as the first parameter to a two-parameter
13436     // function
13437     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13438           Context.hasSameType(InnerType, Context.WideCharTy) ||
13439           Context.hasSameType(InnerType, Context.Char8Ty) ||
13440           Context.hasSameType(InnerType, Context.Char16Ty) ||
13441           Context.hasSameType(InnerType, Context.Char32Ty))) {
13442       Diag((*Param)->getSourceRange().getBegin(),
13443            diag::err_literal_operator_param)
13444           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13445       return true;
13446     }
13447 
13448     // Move on to the second and final parameter.
13449     ++Param;
13450 
13451     // The second parameter must be a std::size_t.
13452     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13453     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13454       Diag((*Param)->getSourceRange().getBegin(),
13455            diag::err_literal_operator_param)
13456           << SecondParamType << Context.getSizeType()
13457           << (*Param)->getSourceRange();
13458       return true;
13459     }
13460   } else {
13461     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13462     return true;
13463   }
13464 
13465   // Parameters are good.
13466 
13467   // A parameter-declaration-clause containing a default argument is not
13468   // equivalent to any of the permitted forms.
13469   for (auto Param : FnDecl->parameters()) {
13470     if (Param->hasDefaultArg()) {
13471       Diag(Param->getDefaultArgRange().getBegin(),
13472            diag::err_literal_operator_default_argument)
13473         << Param->getDefaultArgRange();
13474       break;
13475     }
13476   }
13477 
13478   StringRef LiteralName
13479     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13480   if (LiteralName[0] != '_' &&
13481       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13482     // C++11 [usrlit.suffix]p1:
13483     //   Literal suffix identifiers that do not start with an underscore
13484     //   are reserved for future standardization.
13485     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13486       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13487   }
13488 
13489   return false;
13490 }
13491 
13492 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13493 /// linkage specification, including the language and (if present)
13494 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13495 /// language string literal. LBraceLoc, if valid, provides the location of
13496 /// the '{' brace. Otherwise, this linkage specification does not
13497 /// have any braces.
13498 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13499                                            Expr *LangStr,
13500                                            SourceLocation LBraceLoc) {
13501   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13502   if (!Lit->isAscii()) {
13503     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13504       << LangStr->getSourceRange();
13505     return nullptr;
13506   }
13507 
13508   StringRef Lang = Lit->getString();
13509   LinkageSpecDecl::LanguageIDs Language;
13510   if (Lang == "C")
13511     Language = LinkageSpecDecl::lang_c;
13512   else if (Lang == "C++")
13513     Language = LinkageSpecDecl::lang_cxx;
13514   else {
13515     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13516       << LangStr->getSourceRange();
13517     return nullptr;
13518   }
13519 
13520   // FIXME: Add all the various semantics of linkage specifications
13521 
13522   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13523                                                LangStr->getExprLoc(), Language,
13524                                                LBraceLoc.isValid());
13525   CurContext->addDecl(D);
13526   PushDeclContext(S, D);
13527   return D;
13528 }
13529 
13530 /// ActOnFinishLinkageSpecification - Complete the definition of
13531 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13532 /// valid, it's the position of the closing '}' brace in a linkage
13533 /// specification that uses braces.
13534 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13535                                             Decl *LinkageSpec,
13536                                             SourceLocation RBraceLoc) {
13537   if (RBraceLoc.isValid()) {
13538     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13539     LSDecl->setRBraceLoc(RBraceLoc);
13540   }
13541   PopDeclContext();
13542   return LinkageSpec;
13543 }
13544 
13545 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13546                                   const ParsedAttributesView &AttrList,
13547                                   SourceLocation SemiLoc) {
13548   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13549   // Attribute declarations appertain to empty declaration so we handle
13550   // them here.
13551   ProcessDeclAttributeList(S, ED, AttrList);
13552 
13553   CurContext->addDecl(ED);
13554   return ED;
13555 }
13556 
13557 /// Perform semantic analysis for the variable declaration that
13558 /// occurs within a C++ catch clause, returning the newly-created
13559 /// variable.
13560 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13561                                          TypeSourceInfo *TInfo,
13562                                          SourceLocation StartLoc,
13563                                          SourceLocation Loc,
13564                                          IdentifierInfo *Name) {
13565   bool Invalid = false;
13566   QualType ExDeclType = TInfo->getType();
13567 
13568   // Arrays and functions decay.
13569   if (ExDeclType->isArrayType())
13570     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13571   else if (ExDeclType->isFunctionType())
13572     ExDeclType = Context.getPointerType(ExDeclType);
13573 
13574   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13575   // The exception-declaration shall not denote a pointer or reference to an
13576   // incomplete type, other than [cv] void*.
13577   // N2844 forbids rvalue references.
13578   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13579     Diag(Loc, diag::err_catch_rvalue_ref);
13580     Invalid = true;
13581   }
13582 
13583   if (ExDeclType->isVariablyModifiedType()) {
13584     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13585     Invalid = true;
13586   }
13587 
13588   QualType BaseType = ExDeclType;
13589   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13590   unsigned DK = diag::err_catch_incomplete;
13591   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13592     BaseType = Ptr->getPointeeType();
13593     Mode = 1;
13594     DK = diag::err_catch_incomplete_ptr;
13595   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13596     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13597     BaseType = Ref->getPointeeType();
13598     Mode = 2;
13599     DK = diag::err_catch_incomplete_ref;
13600   }
13601   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13602       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13603     Invalid = true;
13604 
13605   if (!Invalid && !ExDeclType->isDependentType() &&
13606       RequireNonAbstractType(Loc, ExDeclType,
13607                              diag::err_abstract_type_in_decl,
13608                              AbstractVariableType))
13609     Invalid = true;
13610 
13611   // Only the non-fragile NeXT runtime currently supports C++ catches
13612   // of ObjC types, and no runtime supports catching ObjC types by value.
13613   if (!Invalid && getLangOpts().ObjC1) {
13614     QualType T = ExDeclType;
13615     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13616       T = RT->getPointeeType();
13617 
13618     if (T->isObjCObjectType()) {
13619       Diag(Loc, diag::err_objc_object_catch);
13620       Invalid = true;
13621     } else if (T->isObjCObjectPointerType()) {
13622       // FIXME: should this be a test for macosx-fragile specifically?
13623       if (getLangOpts().ObjCRuntime.isFragile())
13624         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13625     }
13626   }
13627 
13628   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13629                                     ExDeclType, TInfo, SC_None);
13630   ExDecl->setExceptionVariable(true);
13631 
13632   // In ARC, infer 'retaining' for variables of retainable type.
13633   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13634     Invalid = true;
13635 
13636   if (!Invalid && !ExDeclType->isDependentType()) {
13637     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13638       // Insulate this from anything else we might currently be parsing.
13639       EnterExpressionEvaluationContext scope(
13640           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13641 
13642       // C++ [except.handle]p16:
13643       //   The object declared in an exception-declaration or, if the
13644       //   exception-declaration does not specify a name, a temporary (12.2) is
13645       //   copy-initialized (8.5) from the exception object. [...]
13646       //   The object is destroyed when the handler exits, after the destruction
13647       //   of any automatic objects initialized within the handler.
13648       //
13649       // We just pretend to initialize the object with itself, then make sure
13650       // it can be destroyed later.
13651       QualType initType = Context.getExceptionObjectType(ExDeclType);
13652 
13653       InitializedEntity entity =
13654         InitializedEntity::InitializeVariable(ExDecl);
13655       InitializationKind initKind =
13656         InitializationKind::CreateCopy(Loc, SourceLocation());
13657 
13658       Expr *opaqueValue =
13659         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13660       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13661       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13662       if (result.isInvalid())
13663         Invalid = true;
13664       else {
13665         // If the constructor used was non-trivial, set this as the
13666         // "initializer".
13667         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13668         if (!construct->getConstructor()->isTrivial()) {
13669           Expr *init = MaybeCreateExprWithCleanups(construct);
13670           ExDecl->setInit(init);
13671         }
13672 
13673         // And make sure it's destructable.
13674         FinalizeVarWithDestructor(ExDecl, recordType);
13675       }
13676     }
13677   }
13678 
13679   if (Invalid)
13680     ExDecl->setInvalidDecl();
13681 
13682   return ExDecl;
13683 }
13684 
13685 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13686 /// handler.
13687 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13688   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13689   bool Invalid = D.isInvalidType();
13690 
13691   // Check for unexpanded parameter packs.
13692   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13693                                       UPPC_ExceptionType)) {
13694     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13695                                              D.getIdentifierLoc());
13696     Invalid = true;
13697   }
13698 
13699   IdentifierInfo *II = D.getIdentifier();
13700   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13701                                              LookupOrdinaryName,
13702                                              ForVisibleRedeclaration)) {
13703     // The scope should be freshly made just for us. There is just no way
13704     // it contains any previous declaration, except for function parameters in
13705     // a function-try-block's catch statement.
13706     assert(!S->isDeclScope(PrevDecl));
13707     if (isDeclInScope(PrevDecl, CurContext, S)) {
13708       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13709         << D.getIdentifier();
13710       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13711       Invalid = true;
13712     } else if (PrevDecl->isTemplateParameter())
13713       // Maybe we will complain about the shadowed template parameter.
13714       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13715   }
13716 
13717   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13718     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13719       << D.getCXXScopeSpec().getRange();
13720     Invalid = true;
13721   }
13722 
13723   VarDecl *ExDecl = BuildExceptionDeclaration(
13724       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13725   if (Invalid)
13726     ExDecl->setInvalidDecl();
13727 
13728   // Add the exception declaration into this scope.
13729   if (II)
13730     PushOnScopeChains(ExDecl, S);
13731   else
13732     CurContext->addDecl(ExDecl);
13733 
13734   ProcessDeclAttributes(S, ExDecl, D);
13735   return ExDecl;
13736 }
13737 
13738 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13739                                          Expr *AssertExpr,
13740                                          Expr *AssertMessageExpr,
13741                                          SourceLocation RParenLoc) {
13742   StringLiteral *AssertMessage =
13743       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13744 
13745   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13746     return nullptr;
13747 
13748   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13749                                       AssertMessage, RParenLoc, false);
13750 }
13751 
13752 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13753                                          Expr *AssertExpr,
13754                                          StringLiteral *AssertMessage,
13755                                          SourceLocation RParenLoc,
13756                                          bool Failed) {
13757   assert(AssertExpr != nullptr && "Expected non-null condition");
13758   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13759       !Failed) {
13760     // In a static_assert-declaration, the constant-expression shall be a
13761     // constant expression that can be contextually converted to bool.
13762     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13763     if (Converted.isInvalid())
13764       Failed = true;
13765 
13766     llvm::APSInt Cond;
13767     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13768           diag::err_static_assert_expression_is_not_constant,
13769           /*AllowFold=*/false).isInvalid())
13770       Failed = true;
13771 
13772     if (!Failed && !Cond) {
13773       SmallString<256> MsgBuffer;
13774       llvm::raw_svector_ostream Msg(MsgBuffer);
13775       if (AssertMessage)
13776         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13777 
13778       Expr *InnerCond = nullptr;
13779       std::string InnerCondDescription;
13780       std::tie(InnerCond, InnerCondDescription) =
13781         findFailedBooleanCondition(Converted.get(),
13782                                    /*AllowTopLevelCond=*/false);
13783       if (InnerCond) {
13784         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13785           << InnerCondDescription << !AssertMessage
13786           << Msg.str() << InnerCond->getSourceRange();
13787       } else {
13788         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13789           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13790       }
13791       Failed = true;
13792     }
13793   }
13794 
13795   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13796                                                   /*DiscardedValue*/false,
13797                                                   /*IsConstexpr*/true);
13798   if (FullAssertExpr.isInvalid())
13799     Failed = true;
13800   else
13801     AssertExpr = FullAssertExpr.get();
13802 
13803   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13804                                         AssertExpr, AssertMessage, RParenLoc,
13805                                         Failed);
13806 
13807   CurContext->addDecl(Decl);
13808   return Decl;
13809 }
13810 
13811 /// Perform semantic analysis of the given friend type declaration.
13812 ///
13813 /// \returns A friend declaration that.
13814 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13815                                       SourceLocation FriendLoc,
13816                                       TypeSourceInfo *TSInfo) {
13817   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13818 
13819   QualType T = TSInfo->getType();
13820   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13821 
13822   // C++03 [class.friend]p2:
13823   //   An elaborated-type-specifier shall be used in a friend declaration
13824   //   for a class.*
13825   //
13826   //   * The class-key of the elaborated-type-specifier is required.
13827   if (!CodeSynthesisContexts.empty()) {
13828     // Do not complain about the form of friend template types during any kind
13829     // of code synthesis. For template instantiation, we will have complained
13830     // when the template was defined.
13831   } else {
13832     if (!T->isElaboratedTypeSpecifier()) {
13833       // If we evaluated the type to a record type, suggest putting
13834       // a tag in front.
13835       if (const RecordType *RT = T->getAs<RecordType>()) {
13836         RecordDecl *RD = RT->getDecl();
13837 
13838         SmallString<16> InsertionText(" ");
13839         InsertionText += RD->getKindName();
13840 
13841         Diag(TypeRange.getBegin(),
13842              getLangOpts().CPlusPlus11 ?
13843                diag::warn_cxx98_compat_unelaborated_friend_type :
13844                diag::ext_unelaborated_friend_type)
13845           << (unsigned) RD->getTagKind()
13846           << T
13847           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13848                                         InsertionText);
13849       } else {
13850         Diag(FriendLoc,
13851              getLangOpts().CPlusPlus11 ?
13852                diag::warn_cxx98_compat_nonclass_type_friend :
13853                diag::ext_nonclass_type_friend)
13854           << T
13855           << TypeRange;
13856       }
13857     } else if (T->getAs<EnumType>()) {
13858       Diag(FriendLoc,
13859            getLangOpts().CPlusPlus11 ?
13860              diag::warn_cxx98_compat_enum_friend :
13861              diag::ext_enum_friend)
13862         << T
13863         << TypeRange;
13864     }
13865 
13866     // C++11 [class.friend]p3:
13867     //   A friend declaration that does not declare a function shall have one
13868     //   of the following forms:
13869     //     friend elaborated-type-specifier ;
13870     //     friend simple-type-specifier ;
13871     //     friend typename-specifier ;
13872     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13873       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13874   }
13875 
13876   //   If the type specifier in a friend declaration designates a (possibly
13877   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13878   //   the friend declaration is ignored.
13879   return FriendDecl::Create(Context, CurContext,
13880                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
13881                             FriendLoc);
13882 }
13883 
13884 /// Handle a friend tag declaration where the scope specifier was
13885 /// templated.
13886 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13887                                     unsigned TagSpec, SourceLocation TagLoc,
13888                                     CXXScopeSpec &SS, IdentifierInfo *Name,
13889                                     SourceLocation NameLoc,
13890                                     const ParsedAttributesView &Attr,
13891                                     MultiTemplateParamsArg TempParamLists) {
13892   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13893 
13894   bool IsMemberSpecialization = false;
13895   bool Invalid = false;
13896 
13897   if (TemplateParameterList *TemplateParams =
13898           MatchTemplateParametersToScopeSpecifier(
13899               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13900               IsMemberSpecialization, Invalid)) {
13901     if (TemplateParams->size() > 0) {
13902       // This is a declaration of a class template.
13903       if (Invalid)
13904         return nullptr;
13905 
13906       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13907                                 NameLoc, Attr, TemplateParams, AS_public,
13908                                 /*ModulePrivateLoc=*/SourceLocation(),
13909                                 FriendLoc, TempParamLists.size() - 1,
13910                                 TempParamLists.data()).get();
13911     } else {
13912       // The "template<>" header is extraneous.
13913       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13914         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13915       IsMemberSpecialization = true;
13916     }
13917   }
13918 
13919   if (Invalid) return nullptr;
13920 
13921   bool isAllExplicitSpecializations = true;
13922   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13923     if (TempParamLists[I]->size()) {
13924       isAllExplicitSpecializations = false;
13925       break;
13926     }
13927   }
13928 
13929   // FIXME: don't ignore attributes.
13930 
13931   // If it's explicit specializations all the way down, just forget
13932   // about the template header and build an appropriate non-templated
13933   // friend.  TODO: for source fidelity, remember the headers.
13934   if (isAllExplicitSpecializations) {
13935     if (SS.isEmpty()) {
13936       bool Owned = false;
13937       bool IsDependent = false;
13938       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13939                       Attr, AS_public,
13940                       /*ModulePrivateLoc=*/SourceLocation(),
13941                       MultiTemplateParamsArg(), Owned, IsDependent,
13942                       /*ScopedEnumKWLoc=*/SourceLocation(),
13943                       /*ScopedEnumUsesClassTag=*/false,
13944                       /*UnderlyingType=*/TypeResult(),
13945                       /*IsTypeSpecifier=*/false,
13946                       /*IsTemplateParamOrArg=*/false);
13947     }
13948 
13949     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13950     ElaboratedTypeKeyword Keyword
13951       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13952     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13953                                    *Name, NameLoc);
13954     if (T.isNull())
13955       return nullptr;
13956 
13957     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13958     if (isa<DependentNameType>(T)) {
13959       DependentNameTypeLoc TL =
13960           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13961       TL.setElaboratedKeywordLoc(TagLoc);
13962       TL.setQualifierLoc(QualifierLoc);
13963       TL.setNameLoc(NameLoc);
13964     } else {
13965       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13966       TL.setElaboratedKeywordLoc(TagLoc);
13967       TL.setQualifierLoc(QualifierLoc);
13968       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13969     }
13970 
13971     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13972                                             TSI, FriendLoc, TempParamLists);
13973     Friend->setAccess(AS_public);
13974     CurContext->addDecl(Friend);
13975     return Friend;
13976   }
13977 
13978   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13979 
13980 
13981 
13982   // Handle the case of a templated-scope friend class.  e.g.
13983   //   template <class T> class A<T>::B;
13984   // FIXME: we don't support these right now.
13985   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13986     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13987   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13988   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13989   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13990   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13991   TL.setElaboratedKeywordLoc(TagLoc);
13992   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13993   TL.setNameLoc(NameLoc);
13994 
13995   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13996                                           TSI, FriendLoc, TempParamLists);
13997   Friend->setAccess(AS_public);
13998   Friend->setUnsupportedFriend(true);
13999   CurContext->addDecl(Friend);
14000   return Friend;
14001 }
14002 
14003 /// Handle a friend type declaration.  This works in tandem with
14004 /// ActOnTag.
14005 ///
14006 /// Notes on friend class templates:
14007 ///
14008 /// We generally treat friend class declarations as if they were
14009 /// declaring a class.  So, for example, the elaborated type specifier
14010 /// in a friend declaration is required to obey the restrictions of a
14011 /// class-head (i.e. no typedefs in the scope chain), template
14012 /// parameters are required to match up with simple template-ids, &c.
14013 /// However, unlike when declaring a template specialization, it's
14014 /// okay to refer to a template specialization without an empty
14015 /// template parameter declaration, e.g.
14016 ///   friend class A<T>::B<unsigned>;
14017 /// We permit this as a special case; if there are any template
14018 /// parameters present at all, require proper matching, i.e.
14019 ///   template <> template \<class T> friend class A<int>::B;
14020 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14021                                 MultiTemplateParamsArg TempParams) {
14022   SourceLocation Loc = DS.getBeginLoc();
14023 
14024   assert(DS.isFriendSpecified());
14025   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14026 
14027   // C++ [class.friend]p3:
14028   // A friend declaration that does not declare a function shall have one of
14029   // the following forms:
14030   //     friend elaborated-type-specifier ;
14031   //     friend simple-type-specifier ;
14032   //     friend typename-specifier ;
14033   //
14034   // Any declaration with a type qualifier does not have that form. (It's
14035   // legal to specify a qualified type as a friend, you just can't write the
14036   // keywords.)
14037   if (DS.getTypeQualifiers()) {
14038     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14039       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14040     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14041       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14042     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14043       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14044     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14045       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14046     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14047       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14048   }
14049 
14050   // Try to convert the decl specifier to a type.  This works for
14051   // friend templates because ActOnTag never produces a ClassTemplateDecl
14052   // for a TUK_Friend.
14053   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14054   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14055   QualType T = TSI->getType();
14056   if (TheDeclarator.isInvalidType())
14057     return nullptr;
14058 
14059   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14060     return nullptr;
14061 
14062   // This is definitely an error in C++98.  It's probably meant to
14063   // be forbidden in C++0x, too, but the specification is just
14064   // poorly written.
14065   //
14066   // The problem is with declarations like the following:
14067   //   template <T> friend A<T>::foo;
14068   // where deciding whether a class C is a friend or not now hinges
14069   // on whether there exists an instantiation of A that causes
14070   // 'foo' to equal C.  There are restrictions on class-heads
14071   // (which we declare (by fiat) elaborated friend declarations to
14072   // be) that makes this tractable.
14073   //
14074   // FIXME: handle "template <> friend class A<T>;", which
14075   // is possibly well-formed?  Who even knows?
14076   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14077     Diag(Loc, diag::err_tagless_friend_type_template)
14078       << DS.getSourceRange();
14079     return nullptr;
14080   }
14081 
14082   // C++98 [class.friend]p1: A friend of a class is a function
14083   //   or class that is not a member of the class . . .
14084   // This is fixed in DR77, which just barely didn't make the C++03
14085   // deadline.  It's also a very silly restriction that seriously
14086   // affects inner classes and which nobody else seems to implement;
14087   // thus we never diagnose it, not even in -pedantic.
14088   //
14089   // But note that we could warn about it: it's always useless to
14090   // friend one of your own members (it's not, however, worthless to
14091   // friend a member of an arbitrary specialization of your template).
14092 
14093   Decl *D;
14094   if (!TempParams.empty())
14095     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14096                                    TempParams,
14097                                    TSI,
14098                                    DS.getFriendSpecLoc());
14099   else
14100     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14101 
14102   if (!D)
14103     return nullptr;
14104 
14105   D->setAccess(AS_public);
14106   CurContext->addDecl(D);
14107 
14108   return D;
14109 }
14110 
14111 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14112                                         MultiTemplateParamsArg TemplateParams) {
14113   const DeclSpec &DS = D.getDeclSpec();
14114 
14115   assert(DS.isFriendSpecified());
14116   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14117 
14118   SourceLocation Loc = D.getIdentifierLoc();
14119   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14120 
14121   // C++ [class.friend]p1
14122   //   A friend of a class is a function or class....
14123   // Note that this sees through typedefs, which is intended.
14124   // It *doesn't* see through dependent types, which is correct
14125   // according to [temp.arg.type]p3:
14126   //   If a declaration acquires a function type through a
14127   //   type dependent on a template-parameter and this causes
14128   //   a declaration that does not use the syntactic form of a
14129   //   function declarator to have a function type, the program
14130   //   is ill-formed.
14131   if (!TInfo->getType()->isFunctionType()) {
14132     Diag(Loc, diag::err_unexpected_friend);
14133 
14134     // It might be worthwhile to try to recover by creating an
14135     // appropriate declaration.
14136     return nullptr;
14137   }
14138 
14139   // C++ [namespace.memdef]p3
14140   //  - If a friend declaration in a non-local class first declares a
14141   //    class or function, the friend class or function is a member
14142   //    of the innermost enclosing namespace.
14143   //  - The name of the friend is not found by simple name lookup
14144   //    until a matching declaration is provided in that namespace
14145   //    scope (either before or after the class declaration granting
14146   //    friendship).
14147   //  - If a friend function is called, its name may be found by the
14148   //    name lookup that considers functions from namespaces and
14149   //    classes associated with the types of the function arguments.
14150   //  - When looking for a prior declaration of a class or a function
14151   //    declared as a friend, scopes outside the innermost enclosing
14152   //    namespace scope are not considered.
14153 
14154   CXXScopeSpec &SS = D.getCXXScopeSpec();
14155   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14156   DeclarationName Name = NameInfo.getName();
14157   assert(Name);
14158 
14159   // Check for unexpanded parameter packs.
14160   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14161       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14162       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14163     return nullptr;
14164 
14165   // The context we found the declaration in, or in which we should
14166   // create the declaration.
14167   DeclContext *DC;
14168   Scope *DCScope = S;
14169   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14170                         ForExternalRedeclaration);
14171 
14172   // There are five cases here.
14173   //   - There's no scope specifier and we're in a local class. Only look
14174   //     for functions declared in the immediately-enclosing block scope.
14175   // We recover from invalid scope qualifiers as if they just weren't there.
14176   FunctionDecl *FunctionContainingLocalClass = nullptr;
14177   if ((SS.isInvalid() || !SS.isSet()) &&
14178       (FunctionContainingLocalClass =
14179            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14180     // C++11 [class.friend]p11:
14181     //   If a friend declaration appears in a local class and the name
14182     //   specified is an unqualified name, a prior declaration is
14183     //   looked up without considering scopes that are outside the
14184     //   innermost enclosing non-class scope. For a friend function
14185     //   declaration, if there is no prior declaration, the program is
14186     //   ill-formed.
14187 
14188     // Find the innermost enclosing non-class scope. This is the block
14189     // scope containing the local class definition (or for a nested class,
14190     // the outer local class).
14191     DCScope = S->getFnParent();
14192 
14193     // Look up the function name in the scope.
14194     Previous.clear(LookupLocalFriendName);
14195     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14196 
14197     if (!Previous.empty()) {
14198       // All possible previous declarations must have the same context:
14199       // either they were declared at block scope or they are members of
14200       // one of the enclosing local classes.
14201       DC = Previous.getRepresentativeDecl()->getDeclContext();
14202     } else {
14203       // This is ill-formed, but provide the context that we would have
14204       // declared the function in, if we were permitted to, for error recovery.
14205       DC = FunctionContainingLocalClass;
14206     }
14207     adjustContextForLocalExternDecl(DC);
14208 
14209     // C++ [class.friend]p6:
14210     //   A function can be defined in a friend declaration of a class if and
14211     //   only if the class is a non-local class (9.8), the function name is
14212     //   unqualified, and the function has namespace scope.
14213     if (D.isFunctionDefinition()) {
14214       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14215     }
14216 
14217   //   - There's no scope specifier, in which case we just go to the
14218   //     appropriate scope and look for a function or function template
14219   //     there as appropriate.
14220   } else if (SS.isInvalid() || !SS.isSet()) {
14221     // C++11 [namespace.memdef]p3:
14222     //   If the name in a friend declaration is neither qualified nor
14223     //   a template-id and the declaration is a function or an
14224     //   elaborated-type-specifier, the lookup to determine whether
14225     //   the entity has been previously declared shall not consider
14226     //   any scopes outside the innermost enclosing namespace.
14227     bool isTemplateId =
14228         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14229 
14230     // Find the appropriate context according to the above.
14231     DC = CurContext;
14232 
14233     // Skip class contexts.  If someone can cite chapter and verse
14234     // for this behavior, that would be nice --- it's what GCC and
14235     // EDG do, and it seems like a reasonable intent, but the spec
14236     // really only says that checks for unqualified existing
14237     // declarations should stop at the nearest enclosing namespace,
14238     // not that they should only consider the nearest enclosing
14239     // namespace.
14240     while (DC->isRecord())
14241       DC = DC->getParent();
14242 
14243     DeclContext *LookupDC = DC;
14244     while (LookupDC->isTransparentContext())
14245       LookupDC = LookupDC->getParent();
14246 
14247     while (true) {
14248       LookupQualifiedName(Previous, LookupDC);
14249 
14250       if (!Previous.empty()) {
14251         DC = LookupDC;
14252         break;
14253       }
14254 
14255       if (isTemplateId) {
14256         if (isa<TranslationUnitDecl>(LookupDC)) break;
14257       } else {
14258         if (LookupDC->isFileContext()) break;
14259       }
14260       LookupDC = LookupDC->getParent();
14261     }
14262 
14263     DCScope = getScopeForDeclContext(S, DC);
14264 
14265   //   - There's a non-dependent scope specifier, in which case we
14266   //     compute it and do a previous lookup there for a function
14267   //     or function template.
14268   } else if (!SS.getScopeRep()->isDependent()) {
14269     DC = computeDeclContext(SS);
14270     if (!DC) return nullptr;
14271 
14272     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14273 
14274     LookupQualifiedName(Previous, DC);
14275 
14276     // Ignore things found implicitly in the wrong scope.
14277     // TODO: better diagnostics for this case.  Suggesting the right
14278     // qualified scope would be nice...
14279     LookupResult::Filter F = Previous.makeFilter();
14280     while (F.hasNext()) {
14281       NamedDecl *D = F.next();
14282       if (!DC->InEnclosingNamespaceSetOf(
14283               D->getDeclContext()->getRedeclContext()))
14284         F.erase();
14285     }
14286     F.done();
14287 
14288     if (Previous.empty()) {
14289       D.setInvalidType();
14290       Diag(Loc, diag::err_qualified_friend_not_found)
14291           << Name << TInfo->getType();
14292       return nullptr;
14293     }
14294 
14295     // C++ [class.friend]p1: A friend of a class is a function or
14296     //   class that is not a member of the class . . .
14297     if (DC->Equals(CurContext))
14298       Diag(DS.getFriendSpecLoc(),
14299            getLangOpts().CPlusPlus11 ?
14300              diag::warn_cxx98_compat_friend_is_member :
14301              diag::err_friend_is_member);
14302 
14303     if (D.isFunctionDefinition()) {
14304       // C++ [class.friend]p6:
14305       //   A function can be defined in a friend declaration of a class if and
14306       //   only if the class is a non-local class (9.8), the function name is
14307       //   unqualified, and the function has namespace scope.
14308       SemaDiagnosticBuilder DB
14309         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14310 
14311       DB << SS.getScopeRep();
14312       if (DC->isFileContext())
14313         DB << FixItHint::CreateRemoval(SS.getRange());
14314       SS.clear();
14315     }
14316 
14317   //   - There's a scope specifier that does not match any template
14318   //     parameter lists, in which case we use some arbitrary context,
14319   //     create a method or method template, and wait for instantiation.
14320   //   - There's a scope specifier that does match some template
14321   //     parameter lists, which we don't handle right now.
14322   } else {
14323     if (D.isFunctionDefinition()) {
14324       // C++ [class.friend]p6:
14325       //   A function can be defined in a friend declaration of a class if and
14326       //   only if the class is a non-local class (9.8), the function name is
14327       //   unqualified, and the function has namespace scope.
14328       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14329         << SS.getScopeRep();
14330     }
14331 
14332     DC = CurContext;
14333     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14334   }
14335 
14336   if (!DC->isRecord()) {
14337     int DiagArg = -1;
14338     switch (D.getName().getKind()) {
14339     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14340     case UnqualifiedIdKind::IK_ConstructorName:
14341       DiagArg = 0;
14342       break;
14343     case UnqualifiedIdKind::IK_DestructorName:
14344       DiagArg = 1;
14345       break;
14346     case UnqualifiedIdKind::IK_ConversionFunctionId:
14347       DiagArg = 2;
14348       break;
14349     case UnqualifiedIdKind::IK_DeductionGuideName:
14350       DiagArg = 3;
14351       break;
14352     case UnqualifiedIdKind::IK_Identifier:
14353     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14354     case UnqualifiedIdKind::IK_LiteralOperatorId:
14355     case UnqualifiedIdKind::IK_OperatorFunctionId:
14356     case UnqualifiedIdKind::IK_TemplateId:
14357       break;
14358     }
14359     // This implies that it has to be an operator or function.
14360     if (DiagArg >= 0) {
14361       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14362       return nullptr;
14363     }
14364   }
14365 
14366   // FIXME: This is an egregious hack to cope with cases where the scope stack
14367   // does not contain the declaration context, i.e., in an out-of-line
14368   // definition of a class.
14369   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14370   if (!DCScope) {
14371     FakeDCScope.setEntity(DC);
14372     DCScope = &FakeDCScope;
14373   }
14374 
14375   bool AddToScope = true;
14376   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14377                                           TemplateParams, AddToScope);
14378   if (!ND) return nullptr;
14379 
14380   assert(ND->getLexicalDeclContext() == CurContext);
14381 
14382   // If we performed typo correction, we might have added a scope specifier
14383   // and changed the decl context.
14384   DC = ND->getDeclContext();
14385 
14386   // Add the function declaration to the appropriate lookup tables,
14387   // adjusting the redeclarations list as necessary.  We don't
14388   // want to do this yet if the friending class is dependent.
14389   //
14390   // Also update the scope-based lookup if the target context's
14391   // lookup context is in lexical scope.
14392   if (!CurContext->isDependentContext()) {
14393     DC = DC->getRedeclContext();
14394     DC->makeDeclVisibleInContext(ND);
14395     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14396       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14397   }
14398 
14399   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14400                                        D.getIdentifierLoc(), ND,
14401                                        DS.getFriendSpecLoc());
14402   FrD->setAccess(AS_public);
14403   CurContext->addDecl(FrD);
14404 
14405   if (ND->isInvalidDecl()) {
14406     FrD->setInvalidDecl();
14407   } else {
14408     if (DC->isRecord()) CheckFriendAccess(ND);
14409 
14410     FunctionDecl *FD;
14411     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14412       FD = FTD->getTemplatedDecl();
14413     else
14414       FD = cast<FunctionDecl>(ND);
14415 
14416     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14417     // default argument expression, that declaration shall be a definition
14418     // and shall be the only declaration of the function or function
14419     // template in the translation unit.
14420     if (functionDeclHasDefaultArgument(FD)) {
14421       // We can't look at FD->getPreviousDecl() because it may not have been set
14422       // if we're in a dependent context. If the function is known to be a
14423       // redeclaration, we will have narrowed Previous down to the right decl.
14424       if (D.isRedeclaration()) {
14425         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14426         Diag(Previous.getRepresentativeDecl()->getLocation(),
14427              diag::note_previous_declaration);
14428       } else if (!D.isFunctionDefinition())
14429         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14430     }
14431 
14432     // Mark templated-scope function declarations as unsupported.
14433     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14434       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14435         << SS.getScopeRep() << SS.getRange()
14436         << cast<CXXRecordDecl>(CurContext);
14437       FrD->setUnsupportedFriend(true);
14438     }
14439   }
14440 
14441   return ND;
14442 }
14443 
14444 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14445   AdjustDeclIfTemplate(Dcl);
14446 
14447   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14448   if (!Fn) {
14449     Diag(DelLoc, diag::err_deleted_non_function);
14450     return;
14451   }
14452 
14453   // Deleted function does not have a body.
14454   Fn->setWillHaveBody(false);
14455 
14456   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14457     // Don't consider the implicit declaration we generate for explicit
14458     // specializations. FIXME: Do not generate these implicit declarations.
14459     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14460          Prev->getPreviousDecl()) &&
14461         !Prev->isDefined()) {
14462       Diag(DelLoc, diag::err_deleted_decl_not_first);
14463       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14464            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14465                               : diag::note_previous_declaration);
14466     }
14467     // If the declaration wasn't the first, we delete the function anyway for
14468     // recovery.
14469     Fn = Fn->getCanonicalDecl();
14470   }
14471 
14472   // dllimport/dllexport cannot be deleted.
14473   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14474     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14475     Fn->setInvalidDecl();
14476   }
14477 
14478   if (Fn->isDeleted())
14479     return;
14480 
14481   // See if we're deleting a function which is already known to override a
14482   // non-deleted virtual function.
14483   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14484     bool IssuedDiagnostic = false;
14485     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14486       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14487         if (!IssuedDiagnostic) {
14488           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14489           IssuedDiagnostic = true;
14490         }
14491         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14492       }
14493     }
14494     // If this function was implicitly deleted because it was defaulted,
14495     // explain why it was deleted.
14496     if (IssuedDiagnostic && MD->isDefaulted())
14497       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14498                                 /*Diagnose*/true);
14499   }
14500 
14501   // C++11 [basic.start.main]p3:
14502   //   A program that defines main as deleted [...] is ill-formed.
14503   if (Fn->isMain())
14504     Diag(DelLoc, diag::err_deleted_main);
14505 
14506   // C++11 [dcl.fct.def.delete]p4:
14507   //  A deleted function is implicitly inline.
14508   Fn->setImplicitlyInline();
14509   Fn->setDeletedAsWritten();
14510 }
14511 
14512 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14513   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14514 
14515   if (MD) {
14516     if (MD->getParent()->isDependentType()) {
14517       MD->setDefaulted();
14518       MD->setExplicitlyDefaulted();
14519       return;
14520     }
14521 
14522     CXXSpecialMember Member = getSpecialMember(MD);
14523     if (Member == CXXInvalid) {
14524       if (!MD->isInvalidDecl())
14525         Diag(DefaultLoc, diag::err_default_special_members);
14526       return;
14527     }
14528 
14529     MD->setDefaulted();
14530     MD->setExplicitlyDefaulted();
14531 
14532     // Unset that we will have a body for this function. We might not,
14533     // if it turns out to be trivial, and we don't need this marking now
14534     // that we've marked it as defaulted.
14535     MD->setWillHaveBody(false);
14536 
14537     // If this definition appears within the record, do the checking when
14538     // the record is complete.
14539     const FunctionDecl *Primary = MD;
14540     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14541       // Ask the template instantiation pattern that actually had the
14542       // '= default' on it.
14543       Primary = Pattern;
14544 
14545     // If the method was defaulted on its first declaration, we will have
14546     // already performed the checking in CheckCompletedCXXClass. Such a
14547     // declaration doesn't trigger an implicit definition.
14548     if (Primary->getCanonicalDecl()->isDefaulted())
14549       return;
14550 
14551     CheckExplicitlyDefaultedSpecialMember(MD);
14552 
14553     if (!MD->isInvalidDecl())
14554       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14555   } else {
14556     Diag(DefaultLoc, diag::err_default_special_members);
14557   }
14558 }
14559 
14560 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14561   for (Stmt *SubStmt : S->children()) {
14562     if (!SubStmt)
14563       continue;
14564     if (isa<ReturnStmt>(SubStmt))
14565       Self.Diag(SubStmt->getBeginLoc(),
14566                 diag::err_return_in_constructor_handler);
14567     if (!isa<Expr>(SubStmt))
14568       SearchForReturnInStmt(Self, SubStmt);
14569   }
14570 }
14571 
14572 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14573   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14574     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14575     SearchForReturnInStmt(*this, Handler);
14576   }
14577 }
14578 
14579 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14580                                              const CXXMethodDecl *Old) {
14581   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14582   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14583 
14584   if (OldFT->hasExtParameterInfos()) {
14585     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14586       // A parameter of the overriding method should be annotated with noescape
14587       // if the corresponding parameter of the overridden method is annotated.
14588       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14589           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14590         Diag(New->getParamDecl(I)->getLocation(),
14591              diag::warn_overriding_method_missing_noescape);
14592         Diag(Old->getParamDecl(I)->getLocation(),
14593              diag::note_overridden_marked_noescape);
14594       }
14595   }
14596 
14597   // Virtual overrides must have the same code_seg.
14598   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14599   const auto *NewCSA = New->getAttr<CodeSegAttr>();
14600   if ((NewCSA || OldCSA) &&
14601       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14602     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14603     Diag(Old->getLocation(), diag::note_previous_declaration);
14604     return true;
14605   }
14606 
14607   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14608 
14609   // If the calling conventions match, everything is fine
14610   if (NewCC == OldCC)
14611     return false;
14612 
14613   // If the calling conventions mismatch because the new function is static,
14614   // suppress the calling convention mismatch error; the error about static
14615   // function override (err_static_overrides_virtual from
14616   // Sema::CheckFunctionDeclaration) is more clear.
14617   if (New->getStorageClass() == SC_Static)
14618     return false;
14619 
14620   Diag(New->getLocation(),
14621        diag::err_conflicting_overriding_cc_attributes)
14622     << New->getDeclName() << New->getType() << Old->getType();
14623   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14624   return true;
14625 }
14626 
14627 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14628                                              const CXXMethodDecl *Old) {
14629   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14630   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14631 
14632   if (Context.hasSameType(NewTy, OldTy) ||
14633       NewTy->isDependentType() || OldTy->isDependentType())
14634     return false;
14635 
14636   // Check if the return types are covariant
14637   QualType NewClassTy, OldClassTy;
14638 
14639   /// Both types must be pointers or references to classes.
14640   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14641     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14642       NewClassTy = NewPT->getPointeeType();
14643       OldClassTy = OldPT->getPointeeType();
14644     }
14645   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14646     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14647       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14648         NewClassTy = NewRT->getPointeeType();
14649         OldClassTy = OldRT->getPointeeType();
14650       }
14651     }
14652   }
14653 
14654   // The return types aren't either both pointers or references to a class type.
14655   if (NewClassTy.isNull()) {
14656     Diag(New->getLocation(),
14657          diag::err_different_return_type_for_overriding_virtual_function)
14658         << New->getDeclName() << NewTy << OldTy
14659         << New->getReturnTypeSourceRange();
14660     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14661         << Old->getReturnTypeSourceRange();
14662 
14663     return true;
14664   }
14665 
14666   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14667     // C++14 [class.virtual]p8:
14668     //   If the class type in the covariant return type of D::f differs from
14669     //   that of B::f, the class type in the return type of D::f shall be
14670     //   complete at the point of declaration of D::f or shall be the class
14671     //   type D.
14672     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14673       if (!RT->isBeingDefined() &&
14674           RequireCompleteType(New->getLocation(), NewClassTy,
14675                               diag::err_covariant_return_incomplete,
14676                               New->getDeclName()))
14677         return true;
14678     }
14679 
14680     // Check if the new class derives from the old class.
14681     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14682       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14683           << New->getDeclName() << NewTy << OldTy
14684           << New->getReturnTypeSourceRange();
14685       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14686           << Old->getReturnTypeSourceRange();
14687       return true;
14688     }
14689 
14690     // Check if we the conversion from derived to base is valid.
14691     if (CheckDerivedToBaseConversion(
14692             NewClassTy, OldClassTy,
14693             diag::err_covariant_return_inaccessible_base,
14694             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14695             New->getLocation(), New->getReturnTypeSourceRange(),
14696             New->getDeclName(), nullptr)) {
14697       // FIXME: this note won't trigger for delayed access control
14698       // diagnostics, and it's impossible to get an undelayed error
14699       // here from access control during the original parse because
14700       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14701       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14702           << Old->getReturnTypeSourceRange();
14703       return true;
14704     }
14705   }
14706 
14707   // The qualifiers of the return types must be the same.
14708   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14709     Diag(New->getLocation(),
14710          diag::err_covariant_return_type_different_qualifications)
14711         << New->getDeclName() << NewTy << OldTy
14712         << New->getReturnTypeSourceRange();
14713     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14714         << Old->getReturnTypeSourceRange();
14715     return true;
14716   }
14717 
14718 
14719   // The new class type must have the same or less qualifiers as the old type.
14720   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14721     Diag(New->getLocation(),
14722          diag::err_covariant_return_type_class_type_more_qualified)
14723         << New->getDeclName() << NewTy << OldTy
14724         << New->getReturnTypeSourceRange();
14725     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14726         << Old->getReturnTypeSourceRange();
14727     return true;
14728   }
14729 
14730   return false;
14731 }
14732 
14733 /// Mark the given method pure.
14734 ///
14735 /// \param Method the method to be marked pure.
14736 ///
14737 /// \param InitRange the source range that covers the "0" initializer.
14738 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14739   SourceLocation EndLoc = InitRange.getEnd();
14740   if (EndLoc.isValid())
14741     Method->setRangeEnd(EndLoc);
14742 
14743   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14744     Method->setPure();
14745     return false;
14746   }
14747 
14748   if (!Method->isInvalidDecl())
14749     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14750       << Method->getDeclName() << InitRange;
14751   return true;
14752 }
14753 
14754 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14755   if (D->getFriendObjectKind())
14756     Diag(D->getLocation(), diag::err_pure_friend);
14757   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14758     CheckPureMethod(M, ZeroLoc);
14759   else
14760     Diag(D->getLocation(), diag::err_illegal_initializer);
14761 }
14762 
14763 /// Determine whether the given declaration is a global variable or
14764 /// static data member.
14765 static bool isNonlocalVariable(const Decl *D) {
14766   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14767     return Var->hasGlobalStorage();
14768 
14769   return false;
14770 }
14771 
14772 /// Invoked when we are about to parse an initializer for the declaration
14773 /// 'Dcl'.
14774 ///
14775 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14776 /// static data member of class X, names should be looked up in the scope of
14777 /// class X. If the declaration had a scope specifier, a scope will have
14778 /// been created and passed in for this purpose. Otherwise, S will be null.
14779 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14780   // If there is no declaration, there was an error parsing it.
14781   if (!D || D->isInvalidDecl())
14782     return;
14783 
14784   // We will always have a nested name specifier here, but this declaration
14785   // might not be out of line if the specifier names the current namespace:
14786   //   extern int n;
14787   //   int ::n = 0;
14788   if (S && D->isOutOfLine())
14789     EnterDeclaratorContext(S, D->getDeclContext());
14790 
14791   // If we are parsing the initializer for a static data member, push a
14792   // new expression evaluation context that is associated with this static
14793   // data member.
14794   if (isNonlocalVariable(D))
14795     PushExpressionEvaluationContext(
14796         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14797 }
14798 
14799 /// Invoked after we are finished parsing an initializer for the declaration D.
14800 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14801   // If there is no declaration, there was an error parsing it.
14802   if (!D || D->isInvalidDecl())
14803     return;
14804 
14805   if (isNonlocalVariable(D))
14806     PopExpressionEvaluationContext();
14807 
14808   if (S && D->isOutOfLine())
14809     ExitDeclaratorContext(S);
14810 }
14811 
14812 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14813 /// C++ if/switch/while/for statement.
14814 /// e.g: "if (int x = f()) {...}"
14815 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14816   // C++ 6.4p2:
14817   // The declarator shall not specify a function or an array.
14818   // The type-specifier-seq shall not contain typedef and shall not declare a
14819   // new class or enumeration.
14820   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14821          "Parser allowed 'typedef' as storage class of condition decl.");
14822 
14823   Decl *Dcl = ActOnDeclarator(S, D);
14824   if (!Dcl)
14825     return true;
14826 
14827   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14828     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14829       << D.getSourceRange();
14830     return true;
14831   }
14832 
14833   return Dcl;
14834 }
14835 
14836 void Sema::LoadExternalVTableUses() {
14837   if (!ExternalSource)
14838     return;
14839 
14840   SmallVector<ExternalVTableUse, 4> VTables;
14841   ExternalSource->ReadUsedVTables(VTables);
14842   SmallVector<VTableUse, 4> NewUses;
14843   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14844     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14845       = VTablesUsed.find(VTables[I].Record);
14846     // Even if a definition wasn't required before, it may be required now.
14847     if (Pos != VTablesUsed.end()) {
14848       if (!Pos->second && VTables[I].DefinitionRequired)
14849         Pos->second = true;
14850       continue;
14851     }
14852 
14853     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14854     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14855   }
14856 
14857   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14858 }
14859 
14860 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14861                           bool DefinitionRequired) {
14862   // Ignore any vtable uses in unevaluated operands or for classes that do
14863   // not have a vtable.
14864   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14865       CurContext->isDependentContext() || isUnevaluatedContext())
14866     return;
14867 
14868   // Try to insert this class into the map.
14869   LoadExternalVTableUses();
14870   Class = Class->getCanonicalDecl();
14871   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14872     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14873   if (!Pos.second) {
14874     // If we already had an entry, check to see if we are promoting this vtable
14875     // to require a definition. If so, we need to reappend to the VTableUses
14876     // list, since we may have already processed the first entry.
14877     if (DefinitionRequired && !Pos.first->second) {
14878       Pos.first->second = true;
14879     } else {
14880       // Otherwise, we can early exit.
14881       return;
14882     }
14883   } else {
14884     // The Microsoft ABI requires that we perform the destructor body
14885     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14886     // the deleting destructor is emitted with the vtable, not with the
14887     // destructor definition as in the Itanium ABI.
14888     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14889       CXXDestructorDecl *DD = Class->getDestructor();
14890       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14891         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14892           // If this is an out-of-line declaration, marking it referenced will
14893           // not do anything. Manually call CheckDestructor to look up operator
14894           // delete().
14895           ContextRAII SavedContext(*this, DD);
14896           CheckDestructor(DD);
14897         } else {
14898           MarkFunctionReferenced(Loc, Class->getDestructor());
14899         }
14900       }
14901     }
14902   }
14903 
14904   // Local classes need to have their virtual members marked
14905   // immediately. For all other classes, we mark their virtual members
14906   // at the end of the translation unit.
14907   if (Class->isLocalClass())
14908     MarkVirtualMembersReferenced(Loc, Class);
14909   else
14910     VTableUses.push_back(std::make_pair(Class, Loc));
14911 }
14912 
14913 bool Sema::DefineUsedVTables() {
14914   LoadExternalVTableUses();
14915   if (VTableUses.empty())
14916     return false;
14917 
14918   // Note: The VTableUses vector could grow as a result of marking
14919   // the members of a class as "used", so we check the size each
14920   // time through the loop and prefer indices (which are stable) to
14921   // iterators (which are not).
14922   bool DefinedAnything = false;
14923   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14924     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14925     if (!Class)
14926       continue;
14927     TemplateSpecializationKind ClassTSK =
14928         Class->getTemplateSpecializationKind();
14929 
14930     SourceLocation Loc = VTableUses[I].second;
14931 
14932     bool DefineVTable = true;
14933 
14934     // If this class has a key function, but that key function is
14935     // defined in another translation unit, we don't need to emit the
14936     // vtable even though we're using it.
14937     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14938     if (KeyFunction && !KeyFunction->hasBody()) {
14939       // The key function is in another translation unit.
14940       DefineVTable = false;
14941       TemplateSpecializationKind TSK =
14942           KeyFunction->getTemplateSpecializationKind();
14943       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14944              TSK != TSK_ImplicitInstantiation &&
14945              "Instantiations don't have key functions");
14946       (void)TSK;
14947     } else if (!KeyFunction) {
14948       // If we have a class with no key function that is the subject
14949       // of an explicit instantiation declaration, suppress the
14950       // vtable; it will live with the explicit instantiation
14951       // definition.
14952       bool IsExplicitInstantiationDeclaration =
14953           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14954       for (auto R : Class->redecls()) {
14955         TemplateSpecializationKind TSK
14956           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14957         if (TSK == TSK_ExplicitInstantiationDeclaration)
14958           IsExplicitInstantiationDeclaration = true;
14959         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14960           IsExplicitInstantiationDeclaration = false;
14961           break;
14962         }
14963       }
14964 
14965       if (IsExplicitInstantiationDeclaration)
14966         DefineVTable = false;
14967     }
14968 
14969     // The exception specifications for all virtual members may be needed even
14970     // if we are not providing an authoritative form of the vtable in this TU.
14971     // We may choose to emit it available_externally anyway.
14972     if (!DefineVTable) {
14973       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14974       continue;
14975     }
14976 
14977     // Mark all of the virtual members of this class as referenced, so
14978     // that we can build a vtable. Then, tell the AST consumer that a
14979     // vtable for this class is required.
14980     DefinedAnything = true;
14981     MarkVirtualMembersReferenced(Loc, Class);
14982     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
14983     if (VTablesUsed[Canonical])
14984       Consumer.HandleVTable(Class);
14985 
14986     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14987     // no key function or the key function is inlined. Don't warn in C++ ABIs
14988     // that lack key functions, since the user won't be able to make one.
14989     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14990         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14991       const FunctionDecl *KeyFunctionDef = nullptr;
14992       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14993                            KeyFunctionDef->isInlined())) {
14994         Diag(Class->getLocation(),
14995              ClassTSK == TSK_ExplicitInstantiationDefinition
14996                  ? diag::warn_weak_template_vtable
14997                  : diag::warn_weak_vtable)
14998             << Class;
14999       }
15000     }
15001   }
15002   VTableUses.clear();
15003 
15004   return DefinedAnything;
15005 }
15006 
15007 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15008                                                  const CXXRecordDecl *RD) {
15009   for (const auto *I : RD->methods())
15010     if (I->isVirtual() && !I->isPure())
15011       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15012 }
15013 
15014 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15015                                         const CXXRecordDecl *RD) {
15016   // Mark all functions which will appear in RD's vtable as used.
15017   CXXFinalOverriderMap FinalOverriders;
15018   RD->getFinalOverriders(FinalOverriders);
15019   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15020                                             E = FinalOverriders.end();
15021        I != E; ++I) {
15022     for (OverridingMethods::const_iterator OI = I->second.begin(),
15023                                            OE = I->second.end();
15024          OI != OE; ++OI) {
15025       assert(OI->second.size() > 0 && "no final overrider");
15026       CXXMethodDecl *Overrider = OI->second.front().Method;
15027 
15028       // C++ [basic.def.odr]p2:
15029       //   [...] A virtual member function is used if it is not pure. [...]
15030       if (!Overrider->isPure())
15031         MarkFunctionReferenced(Loc, Overrider);
15032     }
15033   }
15034 
15035   // Only classes that have virtual bases need a VTT.
15036   if (RD->getNumVBases() == 0)
15037     return;
15038 
15039   for (const auto &I : RD->bases()) {
15040     const CXXRecordDecl *Base =
15041         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15042     if (Base->getNumVBases() == 0)
15043       continue;
15044     MarkVirtualMembersReferenced(Loc, Base);
15045   }
15046 }
15047 
15048 /// SetIvarInitializers - This routine builds initialization ASTs for the
15049 /// Objective-C implementation whose ivars need be initialized.
15050 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15051   if (!getLangOpts().CPlusPlus)
15052     return;
15053   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15054     SmallVector<ObjCIvarDecl*, 8> ivars;
15055     CollectIvarsToConstructOrDestruct(OID, ivars);
15056     if (ivars.empty())
15057       return;
15058     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15059     for (unsigned i = 0; i < ivars.size(); i++) {
15060       FieldDecl *Field = ivars[i];
15061       if (Field->isInvalidDecl())
15062         continue;
15063 
15064       CXXCtorInitializer *Member;
15065       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15066       InitializationKind InitKind =
15067         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15068 
15069       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15070       ExprResult MemberInit =
15071         InitSeq.Perform(*this, InitEntity, InitKind, None);
15072       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15073       // Note, MemberInit could actually come back empty if no initialization
15074       // is required (e.g., because it would call a trivial default constructor)
15075       if (!MemberInit.get() || MemberInit.isInvalid())
15076         continue;
15077 
15078       Member =
15079         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15080                                          SourceLocation(),
15081                                          MemberInit.getAs<Expr>(),
15082                                          SourceLocation());
15083       AllToInit.push_back(Member);
15084 
15085       // Be sure that the destructor is accessible and is marked as referenced.
15086       if (const RecordType *RecordTy =
15087               Context.getBaseElementType(Field->getType())
15088                   ->getAs<RecordType>()) {
15089         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15090         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15091           MarkFunctionReferenced(Field->getLocation(), Destructor);
15092           CheckDestructorAccess(Field->getLocation(), Destructor,
15093                             PDiag(diag::err_access_dtor_ivar)
15094                               << Context.getBaseElementType(Field->getType()));
15095         }
15096       }
15097     }
15098     ObjCImplementation->setIvarInitializers(Context,
15099                                             AllToInit.data(), AllToInit.size());
15100   }
15101 }
15102 
15103 static
15104 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15105                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15106                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15107                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15108                            Sema &S) {
15109   if (Ctor->isInvalidDecl())
15110     return;
15111 
15112   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15113 
15114   // Target may not be determinable yet, for instance if this is a dependent
15115   // call in an uninstantiated template.
15116   if (Target) {
15117     const FunctionDecl *FNTarget = nullptr;
15118     (void)Target->hasBody(FNTarget);
15119     Target = const_cast<CXXConstructorDecl*>(
15120       cast_or_null<CXXConstructorDecl>(FNTarget));
15121   }
15122 
15123   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15124                      // Avoid dereferencing a null pointer here.
15125                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15126 
15127   if (!Current.insert(Canonical).second)
15128     return;
15129 
15130   // We know that beyond here, we aren't chaining into a cycle.
15131   if (!Target || !Target->isDelegatingConstructor() ||
15132       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15133     Valid.insert(Current.begin(), Current.end());
15134     Current.clear();
15135   // We've hit a cycle.
15136   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15137              Current.count(TCanonical)) {
15138     // If we haven't diagnosed this cycle yet, do so now.
15139     if (!Invalid.count(TCanonical)) {
15140       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15141              diag::warn_delegating_ctor_cycle)
15142         << Ctor;
15143 
15144       // Don't add a note for a function delegating directly to itself.
15145       if (TCanonical != Canonical)
15146         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15147 
15148       CXXConstructorDecl *C = Target;
15149       while (C->getCanonicalDecl() != Canonical) {
15150         const FunctionDecl *FNTarget = nullptr;
15151         (void)C->getTargetConstructor()->hasBody(FNTarget);
15152         assert(FNTarget && "Ctor cycle through bodiless function");
15153 
15154         C = const_cast<CXXConstructorDecl*>(
15155           cast<CXXConstructorDecl>(FNTarget));
15156         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15157       }
15158     }
15159 
15160     Invalid.insert(Current.begin(), Current.end());
15161     Current.clear();
15162   } else {
15163     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15164   }
15165 }
15166 
15167 
15168 void Sema::CheckDelegatingCtorCycles() {
15169   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15170 
15171   for (DelegatingCtorDeclsType::iterator
15172          I = DelegatingCtorDecls.begin(ExternalSource),
15173          E = DelegatingCtorDecls.end();
15174        I != E; ++I)
15175     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15176 
15177   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15178     (*CI)->setInvalidDecl();
15179 }
15180 
15181 namespace {
15182   /// AST visitor that finds references to the 'this' expression.
15183   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15184     Sema &S;
15185 
15186   public:
15187     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15188 
15189     bool VisitCXXThisExpr(CXXThisExpr *E) {
15190       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15191         << E->isImplicit();
15192       return false;
15193     }
15194   };
15195 }
15196 
15197 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15198   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15199   if (!TSInfo)
15200     return false;
15201 
15202   TypeLoc TL = TSInfo->getTypeLoc();
15203   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15204   if (!ProtoTL)
15205     return false;
15206 
15207   // C++11 [expr.prim.general]p3:
15208   //   [The expression this] shall not appear before the optional
15209   //   cv-qualifier-seq and it shall not appear within the declaration of a
15210   //   static member function (although its type and value category are defined
15211   //   within a static member function as they are within a non-static member
15212   //   function). [ Note: this is because declaration matching does not occur
15213   //  until the complete declarator is known. - end note ]
15214   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15215   FindCXXThisExpr Finder(*this);
15216 
15217   // If the return type came after the cv-qualifier-seq, check it now.
15218   if (Proto->hasTrailingReturn() &&
15219       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15220     return true;
15221 
15222   // Check the exception specification.
15223   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15224     return true;
15225 
15226   return checkThisInStaticMemberFunctionAttributes(Method);
15227 }
15228 
15229 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15230   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15231   if (!TSInfo)
15232     return false;
15233 
15234   TypeLoc TL = TSInfo->getTypeLoc();
15235   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15236   if (!ProtoTL)
15237     return false;
15238 
15239   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15240   FindCXXThisExpr Finder(*this);
15241 
15242   switch (Proto->getExceptionSpecType()) {
15243   case EST_Unparsed:
15244   case EST_Uninstantiated:
15245   case EST_Unevaluated:
15246   case EST_BasicNoexcept:
15247   case EST_DynamicNone:
15248   case EST_MSAny:
15249   case EST_None:
15250     break;
15251 
15252   case EST_DependentNoexcept:
15253   case EST_NoexceptFalse:
15254   case EST_NoexceptTrue:
15255     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15256       return true;
15257     LLVM_FALLTHROUGH;
15258 
15259   case EST_Dynamic:
15260     for (const auto &E : Proto->exceptions()) {
15261       if (!Finder.TraverseType(E))
15262         return true;
15263     }
15264     break;
15265   }
15266 
15267   return false;
15268 }
15269 
15270 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15271   FindCXXThisExpr Finder(*this);
15272 
15273   // Check attributes.
15274   for (const auto *A : Method->attrs()) {
15275     // FIXME: This should be emitted by tblgen.
15276     Expr *Arg = nullptr;
15277     ArrayRef<Expr *> Args;
15278     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15279       Arg = G->getArg();
15280     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15281       Arg = G->getArg();
15282     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15283       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15284     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15285       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15286     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15287       Arg = ETLF->getSuccessValue();
15288       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15289     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15290       Arg = STLF->getSuccessValue();
15291       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15292     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15293       Arg = LR->getArg();
15294     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15295       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15296     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15297       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15298     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15299       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15300     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15301       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15302     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15303       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15304 
15305     if (Arg && !Finder.TraverseStmt(Arg))
15306       return true;
15307 
15308     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15309       if (!Finder.TraverseStmt(Args[I]))
15310         return true;
15311     }
15312   }
15313 
15314   return false;
15315 }
15316 
15317 void Sema::checkExceptionSpecification(
15318     bool IsTopLevel, ExceptionSpecificationType EST,
15319     ArrayRef<ParsedType> DynamicExceptions,
15320     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15321     SmallVectorImpl<QualType> &Exceptions,
15322     FunctionProtoType::ExceptionSpecInfo &ESI) {
15323   Exceptions.clear();
15324   ESI.Type = EST;
15325   if (EST == EST_Dynamic) {
15326     Exceptions.reserve(DynamicExceptions.size());
15327     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15328       // FIXME: Preserve type source info.
15329       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15330 
15331       if (IsTopLevel) {
15332         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15333         collectUnexpandedParameterPacks(ET, Unexpanded);
15334         if (!Unexpanded.empty()) {
15335           DiagnoseUnexpandedParameterPacks(
15336               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15337               Unexpanded);
15338           continue;
15339         }
15340       }
15341 
15342       // Check that the type is valid for an exception spec, and
15343       // drop it if not.
15344       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15345         Exceptions.push_back(ET);
15346     }
15347     ESI.Exceptions = Exceptions;
15348     return;
15349   }
15350 
15351   if (isComputedNoexcept(EST)) {
15352     assert((NoexceptExpr->isTypeDependent() ||
15353             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15354             Context.BoolTy) &&
15355            "Parser should have made sure that the expression is boolean");
15356     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15357       ESI.Type = EST_BasicNoexcept;
15358       return;
15359     }
15360 
15361     ESI.NoexceptExpr = NoexceptExpr;
15362     return;
15363   }
15364 }
15365 
15366 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15367              ExceptionSpecificationType EST,
15368              SourceRange SpecificationRange,
15369              ArrayRef<ParsedType> DynamicExceptions,
15370              ArrayRef<SourceRange> DynamicExceptionRanges,
15371              Expr *NoexceptExpr) {
15372   if (!MethodD)
15373     return;
15374 
15375   // Dig out the method we're referring to.
15376   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15377     MethodD = FunTmpl->getTemplatedDecl();
15378 
15379   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15380   if (!Method)
15381     return;
15382 
15383   // Check the exception specification.
15384   llvm::SmallVector<QualType, 4> Exceptions;
15385   FunctionProtoType::ExceptionSpecInfo ESI;
15386   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15387                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15388                               ESI);
15389 
15390   // Update the exception specification on the function type.
15391   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15392 
15393   if (Method->isStatic())
15394     checkThisInStaticMemberFunctionExceptionSpec(Method);
15395 
15396   if (Method->isVirtual()) {
15397     // Check overrides, which we previously had to delay.
15398     for (const CXXMethodDecl *O : Method->overridden_methods())
15399       CheckOverridingFunctionExceptionSpec(Method, O);
15400   }
15401 }
15402 
15403 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15404 ///
15405 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15406                                        SourceLocation DeclStart, Declarator &D,
15407                                        Expr *BitWidth,
15408                                        InClassInitStyle InitStyle,
15409                                        AccessSpecifier AS,
15410                                        const ParsedAttr &MSPropertyAttr) {
15411   IdentifierInfo *II = D.getIdentifier();
15412   if (!II) {
15413     Diag(DeclStart, diag::err_anonymous_property);
15414     return nullptr;
15415   }
15416   SourceLocation Loc = D.getIdentifierLoc();
15417 
15418   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15419   QualType T = TInfo->getType();
15420   if (getLangOpts().CPlusPlus) {
15421     CheckExtraCXXDefaultArguments(D);
15422 
15423     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15424                                         UPPC_DataMemberType)) {
15425       D.setInvalidType();
15426       T = Context.IntTy;
15427       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15428     }
15429   }
15430 
15431   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15432 
15433   if (D.getDeclSpec().isInlineSpecified())
15434     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15435         << getLangOpts().CPlusPlus17;
15436   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15437     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15438          diag::err_invalid_thread)
15439       << DeclSpec::getSpecifierName(TSCS);
15440 
15441   // Check to see if this name was declared as a member previously
15442   NamedDecl *PrevDecl = nullptr;
15443   LookupResult Previous(*this, II, Loc, LookupMemberName,
15444                         ForVisibleRedeclaration);
15445   LookupName(Previous, S);
15446   switch (Previous.getResultKind()) {
15447   case LookupResult::Found:
15448   case LookupResult::FoundUnresolvedValue:
15449     PrevDecl = Previous.getAsSingle<NamedDecl>();
15450     break;
15451 
15452   case LookupResult::FoundOverloaded:
15453     PrevDecl = Previous.getRepresentativeDecl();
15454     break;
15455 
15456   case LookupResult::NotFound:
15457   case LookupResult::NotFoundInCurrentInstantiation:
15458   case LookupResult::Ambiguous:
15459     break;
15460   }
15461 
15462   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15463     // Maybe we will complain about the shadowed template parameter.
15464     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15465     // Just pretend that we didn't see the previous declaration.
15466     PrevDecl = nullptr;
15467   }
15468 
15469   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15470     PrevDecl = nullptr;
15471 
15472   SourceLocation TSSL = D.getBeginLoc();
15473   MSPropertyDecl *NewPD =
15474       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15475                              MSPropertyAttr.getPropertyDataGetter(),
15476                              MSPropertyAttr.getPropertyDataSetter());
15477   ProcessDeclAttributes(TUScope, NewPD, D);
15478   NewPD->setAccess(AS);
15479 
15480   if (NewPD->isInvalidDecl())
15481     Record->setInvalidDecl();
15482 
15483   if (D.getDeclSpec().isModulePrivateSpecified())
15484     NewPD->setModulePrivate();
15485 
15486   if (NewPD->isInvalidDecl() && PrevDecl) {
15487     // Don't introduce NewFD into scope; there's already something
15488     // with the same name in the same scope.
15489   } else if (II) {
15490     PushOnScopeChains(NewPD, S);
15491   } else
15492     Record->addDecl(NewPD);
15493 
15494   return NewPD;
15495 }
15496