1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65       : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getLocStart(),
97                      diag::err_param_default_argument_references_param)
98          << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getLocStart(),
105                        diag::err_param_default_argument_references_local)
106           << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getLocStart(),
118                    diag::err_param_default_argument_references_this)
119                << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getLocStart(),
147                    diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171     EST = EST_BasicNoexcept;
172 
173   switch(EST) {
174   // If this function can throw any exceptions, make a note of that.
175   case EST_MSAny:
176   case EST_None:
177     ClearExceptions();
178     ComputedEST = EST;
179     return;
180   // FIXME: If the call to this decl is using any of its default arguments, we
181   // need to search them for potentially-throwing calls.
182   // If this function has a basic noexcept, it doesn't affect the outcome.
183   case EST_BasicNoexcept:
184     return;
185   // If we're still at noexcept(true) and there's a nothrow() callee,
186   // change to that specification.
187   case EST_DynamicNone:
188     if (ComputedEST == EST_BasicNoexcept)
189       ComputedEST = EST_DynamicNone;
190     return;
191   // Check out noexcept specs.
192   case EST_ComputedNoexcept:
193   {
194     FunctionProtoType::NoexceptResult NR =
195         Proto->getNoexceptSpec(Self->Context);
196     assert(NR != FunctionProtoType::NR_NoNoexcept &&
197            "Must have noexcept result for EST_ComputedNoexcept.");
198     assert(NR != FunctionProtoType::NR_Dependent &&
199            "Should not generate implicit declarations for dependent cases, "
200            "and don't know how to handle them anyway.");
201     // noexcept(false) -> no spec on the new function
202     if (NR == FunctionProtoType::NR_Throw) {
203       ClearExceptions();
204       ComputedEST = EST_None;
205     }
206     // noexcept(true) won't change anything either.
207     return;
208   }
209   default:
210     break;
211   }
212   assert(EST == EST_Dynamic && "EST case not considered earlier.");
213   assert(ComputedEST != EST_None &&
214          "Shouldn't collect exceptions when throw-all is guaranteed.");
215   ComputedEST = EST_Dynamic;
216   // Record the exceptions in this function's exception specification.
217   for (const auto &E : Proto->exceptions())
218     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
219       Exceptions.push_back(E);
220 }
221 
222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
223   if (!E || ComputedEST == EST_MSAny)
224     return;
225 
226   // FIXME:
227   //
228   // C++0x [except.spec]p14:
229   //   [An] implicit exception-specification specifies the type-id T if and
230   // only if T is allowed by the exception-specification of a function directly
231   // invoked by f's implicit definition; f shall allow all exceptions if any
232   // function it directly invokes allows all exceptions, and f shall allow no
233   // exceptions if every function it directly invokes allows no exceptions.
234   //
235   // Note in particular that if an implicit exception-specification is generated
236   // for a function containing a throw-expression, that specification can still
237   // be noexcept(true).
238   //
239   // Note also that 'directly invoked' is not defined in the standard, and there
240   // is no indication that we should only consider potentially-evaluated calls.
241   //
242   // Ultimately we should implement the intent of the standard: the exception
243   // specification should be the set of exceptions which can be thrown by the
244   // implicit definition. For now, we assume that any non-nothrow expression can
245   // throw any exception.
246 
247   if (Self->canThrow(E))
248     ComputedEST = EST_None;
249 }
250 
251 bool
252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
253                               SourceLocation EqualLoc) {
254   if (RequireCompleteType(Param->getLocation(), Param->getType(),
255                           diag::err_typecheck_decl_incomplete_type)) {
256     Param->setInvalidDecl();
257     return true;
258   }
259 
260   // C++ [dcl.fct.default]p5
261   //   A default argument expression is implicitly converted (clause
262   //   4) to the parameter type. The default argument expression has
263   //   the same semantic constraints as the initializer expression in
264   //   a declaration of a variable of the parameter type, using the
265   //   copy-initialization semantics (8.5).
266   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267                                                                     Param);
268   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269                                                            EqualLoc);
270   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
271   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
272   if (Result.isInvalid())
273     return true;
274   Arg = Result.getAs<Expr>();
275 
276   CheckCompletedExpr(Arg, EqualLoc);
277   Arg = MaybeCreateExprWithCleanups(Arg);
278 
279   // Okay: add the default argument to the parameter
280   Param->setDefaultArg(Arg);
281 
282   // We have already instantiated this parameter; provide each of the
283   // instantiations with the uninstantiated default argument.
284   UnparsedDefaultArgInstantiationsMap::iterator InstPos
285     = UnparsedDefaultArgInstantiations.find(Param);
286   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289 
290     // We're done tracking this parameter's instantiations.
291     UnparsedDefaultArgInstantiations.erase(InstPos);
292   }
293 
294   return false;
295 }
296 
297 /// ActOnParamDefaultArgument - Check whether the default argument
298 /// provided for a function parameter is well-formed. If so, attach it
299 /// to the parameter declaration.
300 void
301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
302                                 Expr *DefaultArg) {
303   if (!param || !DefaultArg)
304     return;
305 
306   ParmVarDecl *Param = cast<ParmVarDecl>(param);
307   UnparsedDefaultArgLocs.erase(Param);
308 
309   // Default arguments are only permitted in C++
310   if (!getLangOpts().CPlusPlus) {
311     Diag(EqualLoc, diag::err_param_default_argument)
312       << DefaultArg->getSourceRange();
313     Param->setInvalidDecl();
314     return;
315   }
316 
317   // Check for unexpanded parameter packs.
318   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319     Param->setInvalidDecl();
320     return;
321   }
322 
323   // C++11 [dcl.fct.default]p3
324   //   A default argument expression [...] shall not be specified for a
325   //   parameter pack.
326   if (Param->isParameterPack()) {
327     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
328         << DefaultArg->getSourceRange();
329     return;
330   }
331 
332   // Check that the default argument is well-formed
333   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
334   if (DefaultArgChecker.Visit(DefaultArg)) {
335     Param->setInvalidDecl();
336     return;
337   }
338 
339   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
340 }
341 
342 /// ActOnParamUnparsedDefaultArgument - We've seen a default
343 /// argument for a function parameter, but we can't parse it yet
344 /// because we're inside a class definition. Note that this default
345 /// argument will be parsed later.
346 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
347                                              SourceLocation EqualLoc,
348                                              SourceLocation ArgLoc) {
349   if (!param)
350     return;
351 
352   ParmVarDecl *Param = cast<ParmVarDecl>(param);
353   Param->setUnparsedDefaultArg();
354   UnparsedDefaultArgLocs[Param] = ArgLoc;
355 }
356 
357 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
358 /// the default argument for the parameter param failed.
359 void Sema::ActOnParamDefaultArgumentError(Decl *param,
360                                           SourceLocation EqualLoc) {
361   if (!param)
362     return;
363 
364   ParmVarDecl *Param = cast<ParmVarDecl>(param);
365   Param->setInvalidDecl();
366   UnparsedDefaultArgLocs.erase(Param);
367   Param->setDefaultArg(new(Context)
368                        OpaqueValueExpr(EqualLoc,
369                                        Param->getType().getNonReferenceType(),
370                                        VK_RValue));
371 }
372 
373 /// CheckExtraCXXDefaultArguments - Check for any extra default
374 /// arguments in the declarator, which is not a function declaration
375 /// or definition and therefore is not permitted to have default
376 /// arguments. This routine should be invoked for every declarator
377 /// that is not a function declaration or definition.
378 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
379   // C++ [dcl.fct.default]p3
380   //   A default argument expression shall be specified only in the
381   //   parameter-declaration-clause of a function declaration or in a
382   //   template-parameter (14.1). It shall not be specified for a
383   //   parameter pack. If it is specified in a
384   //   parameter-declaration-clause, it shall not occur within a
385   //   declarator or abstract-declarator of a parameter-declaration.
386   bool MightBeFunction = D.isFunctionDeclarationContext();
387   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
388     DeclaratorChunk &chunk = D.getTypeObject(i);
389     if (chunk.Kind == DeclaratorChunk::Function) {
390       if (MightBeFunction) {
391         // This is a function declaration. It can have default arguments, but
392         // keep looking in case its return type is a function type with default
393         // arguments.
394         MightBeFunction = false;
395         continue;
396       }
397       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
398            ++argIdx) {
399         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
400         if (Param->hasUnparsedDefaultArg()) {
401           std::unique_ptr<CachedTokens> Toks =
402               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
403           SourceRange SR;
404           if (Toks->size() > 1)
405             SR = SourceRange((*Toks)[1].getLocation(),
406                              Toks->back().getLocation());
407           else
408             SR = UnparsedDefaultArgLocs[Param];
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << SR;
411         } else if (Param->getDefaultArg()) {
412           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
413             << Param->getDefaultArg()->getSourceRange();
414           Param->setDefaultArg(nullptr);
415         }
416       }
417     } else if (chunk.Kind != DeclaratorChunk::Paren) {
418       MightBeFunction = false;
419     }
420   }
421 }
422 
423 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
424   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
425     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
426     if (!PVD->hasDefaultArg())
427       return false;
428     if (!PVD->hasInheritedDefaultArg())
429       return true;
430   }
431   return false;
432 }
433 
434 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
435 /// function, once we already know that they have the same
436 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
437 /// error, false otherwise.
438 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
439                                 Scope *S) {
440   bool Invalid = false;
441 
442   // The declaration context corresponding to the scope is the semantic
443   // parent, unless this is a local function declaration, in which case
444   // it is that surrounding function.
445   DeclContext *ScopeDC = New->isLocalExternDecl()
446                              ? New->getLexicalDeclContext()
447                              : New->getDeclContext();
448 
449   // Find the previous declaration for the purpose of default arguments.
450   FunctionDecl *PrevForDefaultArgs = Old;
451   for (/**/; PrevForDefaultArgs;
452        // Don't bother looking back past the latest decl if this is a local
453        // extern declaration; nothing else could work.
454        PrevForDefaultArgs = New->isLocalExternDecl()
455                                 ? nullptr
456                                 : PrevForDefaultArgs->getPreviousDecl()) {
457     // Ignore hidden declarations.
458     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
459       continue;
460 
461     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
462         !New->isCXXClassMember()) {
463       // Ignore default arguments of old decl if they are not in
464       // the same scope and this is not an out-of-line definition of
465       // a member function.
466       continue;
467     }
468 
469     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
470       // If only one of these is a local function declaration, then they are
471       // declared in different scopes, even though isDeclInScope may think
472       // they're in the same scope. (If both are local, the scope check is
473       // sufficient, and if neither is local, then they are in the same scope.)
474       continue;
475     }
476 
477     // We found the right previous declaration.
478     break;
479   }
480 
481   // C++ [dcl.fct.default]p4:
482   //   For non-template functions, default arguments can be added in
483   //   later declarations of a function in the same
484   //   scope. Declarations in different scopes have completely
485   //   distinct sets of default arguments. That is, declarations in
486   //   inner scopes do not acquire default arguments from
487   //   declarations in outer scopes, and vice versa. In a given
488   //   function declaration, all parameters subsequent to a
489   //   parameter with a default argument shall have default
490   //   arguments supplied in this or previous declarations. A
491   //   default argument shall not be redefined by a later
492   //   declaration (not even to the same value).
493   //
494   // C++ [dcl.fct.default]p6:
495   //   Except for member functions of class templates, the default arguments
496   //   in a member function definition that appears outside of the class
497   //   definition are added to the set of default arguments provided by the
498   //   member function declaration in the class definition.
499   for (unsigned p = 0, NumParams = PrevForDefaultArgs
500                                        ? PrevForDefaultArgs->getNumParams()
501                                        : 0;
502        p < NumParams; ++p) {
503     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
504     ParmVarDecl *NewParam = New->getParamDecl(p);
505 
506     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
507     bool NewParamHasDfl = NewParam->hasDefaultArg();
508 
509     if (OldParamHasDfl && NewParamHasDfl) {
510       unsigned DiagDefaultParamID =
511         diag::err_param_default_argument_redefinition;
512 
513       // MSVC accepts that default parameters be redefined for member functions
514       // of template class. The new default parameter's value is ignored.
515       Invalid = true;
516       if (getLangOpts().MicrosoftExt) {
517         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
518         if (MD && MD->getParent()->getDescribedClassTemplate()) {
519           // Merge the old default argument into the new parameter.
520           NewParam->setHasInheritedDefaultArg();
521           if (OldParam->hasUninstantiatedDefaultArg())
522             NewParam->setUninstantiatedDefaultArg(
523                                       OldParam->getUninstantiatedDefaultArg());
524           else
525             NewParam->setDefaultArg(OldParam->getInit());
526           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
527           Invalid = false;
528         }
529       }
530 
531       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
532       // hint here. Alternatively, we could walk the type-source information
533       // for NewParam to find the last source location in the type... but it
534       // isn't worth the effort right now. This is the kind of test case that
535       // is hard to get right:
536       //   int f(int);
537       //   void g(int (*fp)(int) = f);
538       //   void g(int (*fp)(int) = &f);
539       Diag(NewParam->getLocation(), DiagDefaultParamID)
540         << NewParam->getDefaultArgRange();
541 
542       // Look for the function declaration where the default argument was
543       // actually written, which may be a declaration prior to Old.
544       for (auto Older = PrevForDefaultArgs;
545            OldParam->hasInheritedDefaultArg(); /**/) {
546         Older = Older->getPreviousDecl();
547         OldParam = Older->getParamDecl(p);
548       }
549 
550       Diag(OldParam->getLocation(), diag::note_previous_definition)
551         << OldParam->getDefaultArgRange();
552     } else if (OldParamHasDfl) {
553       // Merge the old default argument into the new parameter unless the new
554       // function is a friend declaration in a template class. In the latter
555       // case the default arguments will be inherited when the friend
556       // declaration will be instantiated.
557       if (New->getFriendObjectKind() == Decl::FOK_None ||
558           !New->getLexicalDeclContext()->isDependentContext()) {
559         // It's important to use getInit() here;  getDefaultArg()
560         // strips off any top-level ExprWithCleanups.
561         NewParam->setHasInheritedDefaultArg();
562         if (OldParam->hasUnparsedDefaultArg())
563           NewParam->setUnparsedDefaultArg();
564         else if (OldParam->hasUninstantiatedDefaultArg())
565           NewParam->setUninstantiatedDefaultArg(
566                                        OldParam->getUninstantiatedDefaultArg());
567         else
568           NewParam->setDefaultArg(OldParam->getInit());
569       }
570     } else if (NewParamHasDfl) {
571       if (New->getDescribedFunctionTemplate()) {
572         // Paragraph 4, quoted above, only applies to non-template functions.
573         Diag(NewParam->getLocation(),
574              diag::err_param_default_argument_template_redecl)
575           << NewParam->getDefaultArgRange();
576         Diag(PrevForDefaultArgs->getLocation(),
577              diag::note_template_prev_declaration)
578             << false;
579       } else if (New->getTemplateSpecializationKind()
580                    != TSK_ImplicitInstantiation &&
581                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
582         // C++ [temp.expr.spec]p21:
583         //   Default function arguments shall not be specified in a declaration
584         //   or a definition for one of the following explicit specializations:
585         //     - the explicit specialization of a function template;
586         //     - the explicit specialization of a member function template;
587         //     - the explicit specialization of a member function of a class
588         //       template where the class template specialization to which the
589         //       member function specialization belongs is implicitly
590         //       instantiated.
591         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
592           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
593           << New->getDeclName()
594           << NewParam->getDefaultArgRange();
595       } else if (New->getDeclContext()->isDependentContext()) {
596         // C++ [dcl.fct.default]p6 (DR217):
597         //   Default arguments for a member function of a class template shall
598         //   be specified on the initial declaration of the member function
599         //   within the class template.
600         //
601         // Reading the tea leaves a bit in DR217 and its reference to DR205
602         // leads me to the conclusion that one cannot add default function
603         // arguments for an out-of-line definition of a member function of a
604         // dependent type.
605         int WhichKind = 2;
606         if (CXXRecordDecl *Record
607               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
608           if (Record->getDescribedClassTemplate())
609             WhichKind = 0;
610           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
611             WhichKind = 1;
612           else
613             WhichKind = 2;
614         }
615 
616         Diag(NewParam->getLocation(),
617              diag::err_param_default_argument_member_template_redecl)
618           << WhichKind
619           << NewParam->getDefaultArgRange();
620       }
621     }
622   }
623 
624   // DR1344: If a default argument is added outside a class definition and that
625   // default argument makes the function a special member function, the program
626   // is ill-formed. This can only happen for constructors.
627   if (isa<CXXConstructorDecl>(New) &&
628       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
629     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
630                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
631     if (NewSM != OldSM) {
632       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
633       assert(NewParam->hasDefaultArg());
634       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
635         << NewParam->getDefaultArgRange() << NewSM;
636       Diag(Old->getLocation(), diag::note_previous_declaration);
637     }
638   }
639 
640   const FunctionDecl *Def;
641   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
642   // template has a constexpr specifier then all its declarations shall
643   // contain the constexpr specifier.
644   if (New->isConstexpr() != Old->isConstexpr()) {
645     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
646       << New << New->isConstexpr();
647     Diag(Old->getLocation(), diag::note_previous_declaration);
648     Invalid = true;
649   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
650              Old->isDefined(Def) &&
651              // If a friend function is inlined but does not have 'inline'
652              // specifier, it is a definition. Do not report attribute conflict
653              // in this case, redefinition will be diagnosed later.
654              (New->isInlineSpecified() ||
655               New->getFriendObjectKind() == Decl::FOK_None)) {
656     // C++11 [dcl.fcn.spec]p4:
657     //   If the definition of a function appears in a translation unit before its
658     //   first declaration as inline, the program is ill-formed.
659     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
660     Diag(Def->getLocation(), diag::note_previous_definition);
661     Invalid = true;
662   }
663 
664   // FIXME: It's not clear what should happen if multiple declarations of a
665   // deduction guide have different explicitness. For now at least we simply
666   // reject any case where the explicitness changes.
667   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
668   if (NewGuide && NewGuide->isExplicitSpecified() !=
669                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
670     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
671       << NewGuide->isExplicitSpecified();
672     Diag(Old->getLocation(), diag::note_previous_declaration);
673   }
674 
675   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
676   // argument expression, that declaration shall be a definition and shall be
677   // the only declaration of the function or function template in the
678   // translation unit.
679   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
680       functionDeclHasDefaultArgument(Old)) {
681     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
682     Diag(Old->getLocation(), diag::note_previous_declaration);
683     Invalid = true;
684   }
685 
686   return Invalid;
687 }
688 
689 NamedDecl *
690 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
691                                    MultiTemplateParamsArg TemplateParamLists) {
692   assert(D.isDecompositionDeclarator());
693   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
694 
695   // The syntax only allows a decomposition declarator as a simple-declaration
696   // or a for-range-declaration, but we parse it in more cases than that.
697   if (!D.mayHaveDecompositionDeclarator()) {
698     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
699       << Decomp.getSourceRange();
700     return nullptr;
701   }
702 
703   if (!TemplateParamLists.empty()) {
704     // FIXME: There's no rule against this, but there are also no rules that
705     // would actually make it usable, so we reject it for now.
706     Diag(TemplateParamLists.front()->getTemplateLoc(),
707          diag::err_decomp_decl_template);
708     return nullptr;
709   }
710 
711   Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
712                                    ? diag::warn_cxx14_compat_decomp_decl
713                                    : diag::ext_decomp_decl)
714       << Decomp.getSourceRange();
715 
716   // The semantic context is always just the current context.
717   DeclContext *const DC = CurContext;
718 
719   // C++1z [dcl.dcl]/8:
720   //   The decl-specifier-seq shall contain only the type-specifier auto
721   //   and cv-qualifiers.
722   auto &DS = D.getDeclSpec();
723   {
724     SmallVector<StringRef, 8> BadSpecifiers;
725     SmallVector<SourceLocation, 8> BadSpecifierLocs;
726     if (auto SCS = DS.getStorageClassSpec()) {
727       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
728       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
729     }
730     if (auto TSCS = DS.getThreadStorageClassSpec()) {
731       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
732       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
733     }
734     if (DS.isConstexprSpecified()) {
735       BadSpecifiers.push_back("constexpr");
736       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
737     }
738     if (DS.isInlineSpecified()) {
739       BadSpecifiers.push_back("inline");
740       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
741     }
742     if (!BadSpecifiers.empty()) {
743       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
744       Err << (int)BadSpecifiers.size()
745           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
746       // Don't add FixItHints to remove the specifiers; we do still respect
747       // them when building the underlying variable.
748       for (auto Loc : BadSpecifierLocs)
749         Err << SourceRange(Loc, Loc);
750     }
751     // We can't recover from it being declared as a typedef.
752     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
753       return nullptr;
754   }
755 
756   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
757   QualType R = TInfo->getType();
758 
759   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
760                                       UPPC_DeclarationType))
761     D.setInvalidType();
762 
763   // The syntax only allows a single ref-qualifier prior to the decomposition
764   // declarator. No other declarator chunks are permitted. Also check the type
765   // specifier here.
766   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
767       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
768       (D.getNumTypeObjects() == 1 &&
769        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
770     Diag(Decomp.getLSquareLoc(),
771          (D.hasGroupingParens() ||
772           (D.getNumTypeObjects() &&
773            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
774              ? diag::err_decomp_decl_parens
775              : diag::err_decomp_decl_type)
776         << R;
777 
778     // In most cases, there's no actual problem with an explicitly-specified
779     // type, but a function type won't work here, and ActOnVariableDeclarator
780     // shouldn't be called for such a type.
781     if (R->isFunctionType())
782       D.setInvalidType();
783   }
784 
785   // Build the BindingDecls.
786   SmallVector<BindingDecl*, 8> Bindings;
787 
788   // Build the BindingDecls.
789   for (auto &B : D.getDecompositionDeclarator().bindings()) {
790     // Check for name conflicts.
791     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
792     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
793                           ForRedeclaration);
794     LookupName(Previous, S,
795                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
796 
797     // It's not permitted to shadow a template parameter name.
798     if (Previous.isSingleResult() &&
799         Previous.getFoundDecl()->isTemplateParameter()) {
800       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
801                                       Previous.getFoundDecl());
802       Previous.clear();
803     }
804 
805     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
806                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
807     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
808                          /*AllowInlineNamespace*/false);
809     if (!Previous.empty()) {
810       auto *Old = Previous.getRepresentativeDecl();
811       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
812       Diag(Old->getLocation(), diag::note_previous_definition);
813     }
814 
815     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
816     PushOnScopeChains(BD, S, true);
817     Bindings.push_back(BD);
818     ParsingInitForAutoVars.insert(BD);
819   }
820 
821   // There are no prior lookup results for the variable itself, because it
822   // is unnamed.
823   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
824                                Decomp.getLSquareLoc());
825   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
826 
827   // Build the variable that holds the non-decomposed object.
828   bool AddToScope = true;
829   NamedDecl *New =
830       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
831                               MultiTemplateParamsArg(), AddToScope, Bindings);
832   CurContext->addHiddenDecl(New);
833 
834   if (isInOpenMPDeclareTargetContext())
835     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
836 
837   return New;
838 }
839 
840 static bool checkSimpleDecomposition(
841     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
842     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
843     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
844   if ((int64_t)Bindings.size() != NumElems) {
845     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
846         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
847         << (NumElems < Bindings.size());
848     return true;
849   }
850 
851   unsigned I = 0;
852   for (auto *B : Bindings) {
853     SourceLocation Loc = B->getLocation();
854     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
855     if (E.isInvalid())
856       return true;
857     E = GetInit(Loc, E.get(), I++);
858     if (E.isInvalid())
859       return true;
860     B->setBinding(ElemType, E.get());
861   }
862 
863   return false;
864 }
865 
866 static bool checkArrayLikeDecomposition(Sema &S,
867                                         ArrayRef<BindingDecl *> Bindings,
868                                         ValueDecl *Src, QualType DecompType,
869                                         const llvm::APSInt &NumElems,
870                                         QualType ElemType) {
871   return checkSimpleDecomposition(
872       S, Bindings, Src, DecompType, NumElems, ElemType,
873       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
874         ExprResult E = S.ActOnIntegerConstant(Loc, I);
875         if (E.isInvalid())
876           return ExprError();
877         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
878       });
879 }
880 
881 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
882                                     ValueDecl *Src, QualType DecompType,
883                                     const ConstantArrayType *CAT) {
884   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
885                                      llvm::APSInt(CAT->getSize()),
886                                      CAT->getElementType());
887 }
888 
889 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
890                                      ValueDecl *Src, QualType DecompType,
891                                      const VectorType *VT) {
892   return checkArrayLikeDecomposition(
893       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
894       S.Context.getQualifiedType(VT->getElementType(),
895                                  DecompType.getQualifiers()));
896 }
897 
898 static bool checkComplexDecomposition(Sema &S,
899                                       ArrayRef<BindingDecl *> Bindings,
900                                       ValueDecl *Src, QualType DecompType,
901                                       const ComplexType *CT) {
902   return checkSimpleDecomposition(
903       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
904       S.Context.getQualifiedType(CT->getElementType(),
905                                  DecompType.getQualifiers()),
906       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
907         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
908       });
909 }
910 
911 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
912                                      TemplateArgumentListInfo &Args) {
913   SmallString<128> SS;
914   llvm::raw_svector_ostream OS(SS);
915   bool First = true;
916   for (auto &Arg : Args.arguments()) {
917     if (!First)
918       OS << ", ";
919     Arg.getArgument().print(PrintingPolicy, OS);
920     First = false;
921   }
922   return OS.str();
923 }
924 
925 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
926                                      SourceLocation Loc, StringRef Trait,
927                                      TemplateArgumentListInfo &Args,
928                                      unsigned DiagID) {
929   auto DiagnoseMissing = [&] {
930     if (DiagID)
931       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
932                                                Args);
933     return true;
934   };
935 
936   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
937   NamespaceDecl *Std = S.getStdNamespace();
938   if (!Std)
939     return DiagnoseMissing();
940 
941   // Look up the trait itself, within namespace std. We can diagnose various
942   // problems with this lookup even if we've been asked to not diagnose a
943   // missing specialization, because this can only fail if the user has been
944   // declaring their own names in namespace std or we don't support the
945   // standard library implementation in use.
946   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
947                       Loc, Sema::LookupOrdinaryName);
948   if (!S.LookupQualifiedName(Result, Std))
949     return DiagnoseMissing();
950   if (Result.isAmbiguous())
951     return true;
952 
953   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
954   if (!TraitTD) {
955     Result.suppressDiagnostics();
956     NamedDecl *Found = *Result.begin();
957     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
958     S.Diag(Found->getLocation(), diag::note_declared_at);
959     return true;
960   }
961 
962   // Build the template-id.
963   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
964   if (TraitTy.isNull())
965     return true;
966   if (!S.isCompleteType(Loc, TraitTy)) {
967     if (DiagID)
968       S.RequireCompleteType(
969           Loc, TraitTy, DiagID,
970           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
971     return true;
972   }
973 
974   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
975   assert(RD && "specialization of class template is not a class?");
976 
977   // Look up the member of the trait type.
978   S.LookupQualifiedName(TraitMemberLookup, RD);
979   return TraitMemberLookup.isAmbiguous();
980 }
981 
982 static TemplateArgumentLoc
983 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
984                                    uint64_t I) {
985   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
986   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
987 }
988 
989 static TemplateArgumentLoc
990 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
991   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
992 }
993 
994 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
995 
996 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
997                                llvm::APSInt &Size) {
998   EnterExpressionEvaluationContext ContextRAII(
999       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1000 
1001   DeclarationName Value = S.PP.getIdentifierInfo("value");
1002   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1003 
1004   // Form template argument list for tuple_size<T>.
1005   TemplateArgumentListInfo Args(Loc, Loc);
1006   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1007 
1008   // If there's no tuple_size specialization, it's not tuple-like.
1009   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1010     return IsTupleLike::NotTupleLike;
1011 
1012   // If we get this far, we've committed to the tuple interpretation, but
1013   // we can still fail if there actually isn't a usable ::value.
1014 
1015   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1016     LookupResult &R;
1017     TemplateArgumentListInfo &Args;
1018     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1019         : R(R), Args(Args) {}
1020     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1021       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1022           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1023     }
1024   } Diagnoser(R, Args);
1025 
1026   if (R.empty()) {
1027     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1028     return IsTupleLike::Error;
1029   }
1030 
1031   ExprResult E =
1032       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1033   if (E.isInvalid())
1034     return IsTupleLike::Error;
1035 
1036   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1037   if (E.isInvalid())
1038     return IsTupleLike::Error;
1039 
1040   return IsTupleLike::TupleLike;
1041 }
1042 
1043 /// \return std::tuple_element<I, T>::type.
1044 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1045                                         unsigned I, QualType T) {
1046   // Form template argument list for tuple_element<I, T>.
1047   TemplateArgumentListInfo Args(Loc, Loc);
1048   Args.addArgument(
1049       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1050   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1051 
1052   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1053   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1054   if (lookupStdTypeTraitMember(
1055           S, R, Loc, "tuple_element", Args,
1056           diag::err_decomp_decl_std_tuple_element_not_specialized))
1057     return QualType();
1058 
1059   auto *TD = R.getAsSingle<TypeDecl>();
1060   if (!TD) {
1061     R.suppressDiagnostics();
1062     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1063       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1064     if (!R.empty())
1065       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1066     return QualType();
1067   }
1068 
1069   return S.Context.getTypeDeclType(TD);
1070 }
1071 
1072 namespace {
1073 struct BindingDiagnosticTrap {
1074   Sema &S;
1075   DiagnosticErrorTrap Trap;
1076   BindingDecl *BD;
1077 
1078   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1079       : S(S), Trap(S.Diags), BD(BD) {}
1080   ~BindingDiagnosticTrap() {
1081     if (Trap.hasErrorOccurred())
1082       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1083   }
1084 };
1085 }
1086 
1087 static bool checkTupleLikeDecomposition(Sema &S,
1088                                         ArrayRef<BindingDecl *> Bindings,
1089                                         VarDecl *Src, QualType DecompType,
1090                                         const llvm::APSInt &TupleSize) {
1091   if ((int64_t)Bindings.size() != TupleSize) {
1092     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1093         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1094         << (TupleSize < Bindings.size());
1095     return true;
1096   }
1097 
1098   if (Bindings.empty())
1099     return false;
1100 
1101   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1102 
1103   // [dcl.decomp]p3:
1104   //   The unqualified-id get is looked up in the scope of E by class member
1105   //   access lookup
1106   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1107   bool UseMemberGet = false;
1108   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1109     if (auto *RD = DecompType->getAsCXXRecordDecl())
1110       S.LookupQualifiedName(MemberGet, RD);
1111     if (MemberGet.isAmbiguous())
1112       return true;
1113     UseMemberGet = !MemberGet.empty();
1114     S.FilterAcceptableTemplateNames(MemberGet);
1115   }
1116 
1117   unsigned I = 0;
1118   for (auto *B : Bindings) {
1119     BindingDiagnosticTrap Trap(S, B);
1120     SourceLocation Loc = B->getLocation();
1121 
1122     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1123     if (E.isInvalid())
1124       return true;
1125 
1126     //   e is an lvalue if the type of the entity is an lvalue reference and
1127     //   an xvalue otherwise
1128     if (!Src->getType()->isLValueReferenceType())
1129       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1130                                    E.get(), nullptr, VK_XValue);
1131 
1132     TemplateArgumentListInfo Args(Loc, Loc);
1133     Args.addArgument(
1134         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1135 
1136     if (UseMemberGet) {
1137       //   if [lookup of member get] finds at least one declaration, the
1138       //   initializer is e.get<i-1>().
1139       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1140                                      CXXScopeSpec(), SourceLocation(), nullptr,
1141                                      MemberGet, &Args, nullptr);
1142       if (E.isInvalid())
1143         return true;
1144 
1145       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1146     } else {
1147       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1148       //   in the associated namespaces.
1149       Expr *Get = UnresolvedLookupExpr::Create(
1150           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1151           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1152           UnresolvedSetIterator(), UnresolvedSetIterator());
1153 
1154       Expr *Arg = E.get();
1155       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1156     }
1157     if (E.isInvalid())
1158       return true;
1159     Expr *Init = E.get();
1160 
1161     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1162     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1163     if (T.isNull())
1164       return true;
1165 
1166     //   each vi is a variable of type "reference to T" initialized with the
1167     //   initializer, where the reference is an lvalue reference if the
1168     //   initializer is an lvalue and an rvalue reference otherwise
1169     QualType RefType =
1170         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1171     if (RefType.isNull())
1172       return true;
1173     auto *RefVD = VarDecl::Create(
1174         S.Context, Src->getDeclContext(), Loc, Loc,
1175         B->getDeclName().getAsIdentifierInfo(), RefType,
1176         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1177     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1178     RefVD->setTSCSpec(Src->getTSCSpec());
1179     RefVD->setImplicit();
1180     if (Src->isInlineSpecified())
1181       RefVD->setInlineSpecified();
1182     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1183 
1184     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1185     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1186     InitializationSequence Seq(S, Entity, Kind, Init);
1187     E = Seq.Perform(S, Entity, Kind, Init);
1188     if (E.isInvalid())
1189       return true;
1190     E = S.ActOnFinishFullExpr(E.get(), Loc);
1191     if (E.isInvalid())
1192       return true;
1193     RefVD->setInit(E.get());
1194     RefVD->checkInitIsICE();
1195 
1196     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1197                                    DeclarationNameInfo(B->getDeclName(), Loc),
1198                                    RefVD);
1199     if (E.isInvalid())
1200       return true;
1201 
1202     B->setBinding(T, E.get());
1203     I++;
1204   }
1205 
1206   return false;
1207 }
1208 
1209 /// Find the base class to decompose in a built-in decomposition of a class type.
1210 /// This base class search is, unfortunately, not quite like any other that we
1211 /// perform anywhere else in C++.
1212 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1213                                                       SourceLocation Loc,
1214                                                       const CXXRecordDecl *RD,
1215                                                       CXXCastPath &BasePath) {
1216   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1217                           CXXBasePath &Path) {
1218     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1219   };
1220 
1221   const CXXRecordDecl *ClassWithFields = nullptr;
1222   if (RD->hasDirectFields())
1223     // [dcl.decomp]p4:
1224     //   Otherwise, all of E's non-static data members shall be public direct
1225     //   members of E ...
1226     ClassWithFields = RD;
1227   else {
1228     //   ... or of ...
1229     CXXBasePaths Paths;
1230     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1231     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1232       // If no classes have fields, just decompose RD itself. (This will work
1233       // if and only if zero bindings were provided.)
1234       return RD;
1235     }
1236 
1237     CXXBasePath *BestPath = nullptr;
1238     for (auto &P : Paths) {
1239       if (!BestPath)
1240         BestPath = &P;
1241       else if (!S.Context.hasSameType(P.back().Base->getType(),
1242                                       BestPath->back().Base->getType())) {
1243         //   ... the same ...
1244         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1245           << false << RD << BestPath->back().Base->getType()
1246           << P.back().Base->getType();
1247         return nullptr;
1248       } else if (P.Access < BestPath->Access) {
1249         BestPath = &P;
1250       }
1251     }
1252 
1253     //   ... unambiguous ...
1254     QualType BaseType = BestPath->back().Base->getType();
1255     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1256       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1257         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1258       return nullptr;
1259     }
1260 
1261     //   ... public base class of E.
1262     if (BestPath->Access != AS_public) {
1263       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1264         << RD << BaseType;
1265       for (auto &BS : *BestPath) {
1266         if (BS.Base->getAccessSpecifier() != AS_public) {
1267           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1268             << (BS.Base->getAccessSpecifier() == AS_protected)
1269             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1270           break;
1271         }
1272       }
1273       return nullptr;
1274     }
1275 
1276     ClassWithFields = BaseType->getAsCXXRecordDecl();
1277     S.BuildBasePathArray(Paths, BasePath);
1278   }
1279 
1280   // The above search did not check whether the selected class itself has base
1281   // classes with fields, so check that now.
1282   CXXBasePaths Paths;
1283   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1284     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1285       << (ClassWithFields == RD) << RD << ClassWithFields
1286       << Paths.front().back().Base->getType();
1287     return nullptr;
1288   }
1289 
1290   return ClassWithFields;
1291 }
1292 
1293 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1294                                      ValueDecl *Src, QualType DecompType,
1295                                      const CXXRecordDecl *RD) {
1296   CXXCastPath BasePath;
1297   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1298   if (!RD)
1299     return true;
1300   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1301                                                  DecompType.getQualifiers());
1302 
1303   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1304     unsigned NumFields =
1305         std::count_if(RD->field_begin(), RD->field_end(),
1306                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1307     assert(Bindings.size() != NumFields);
1308     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1309         << DecompType << (unsigned)Bindings.size() << NumFields
1310         << (NumFields < Bindings.size());
1311     return true;
1312   };
1313 
1314   //   all of E's non-static data members shall be public [...] members,
1315   //   E shall not have an anonymous union member, ...
1316   unsigned I = 0;
1317   for (auto *FD : RD->fields()) {
1318     if (FD->isUnnamedBitfield())
1319       continue;
1320 
1321     if (FD->isAnonymousStructOrUnion()) {
1322       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1323         << DecompType << FD->getType()->isUnionType();
1324       S.Diag(FD->getLocation(), diag::note_declared_at);
1325       return true;
1326     }
1327 
1328     // We have a real field to bind.
1329     if (I >= Bindings.size())
1330       return DiagnoseBadNumberOfBindings();
1331     auto *B = Bindings[I++];
1332 
1333     SourceLocation Loc = B->getLocation();
1334     if (FD->getAccess() != AS_public) {
1335       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1336 
1337       // Determine whether the access specifier was explicit.
1338       bool Implicit = true;
1339       for (const auto *D : RD->decls()) {
1340         if (declaresSameEntity(D, FD))
1341           break;
1342         if (isa<AccessSpecDecl>(D)) {
1343           Implicit = false;
1344           break;
1345         }
1346       }
1347 
1348       S.Diag(FD->getLocation(), diag::note_access_natural)
1349         << (FD->getAccess() == AS_protected) << Implicit;
1350       return true;
1351     }
1352 
1353     // Initialize the binding to Src.FD.
1354     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1355     if (E.isInvalid())
1356       return true;
1357     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1358                             VK_LValue, &BasePath);
1359     if (E.isInvalid())
1360       return true;
1361     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1362                                   CXXScopeSpec(), FD,
1363                                   DeclAccessPair::make(FD, FD->getAccess()),
1364                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1365     if (E.isInvalid())
1366       return true;
1367 
1368     // If the type of the member is T, the referenced type is cv T, where cv is
1369     // the cv-qualification of the decomposition expression.
1370     //
1371     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1372     // 'const' to the type of the field.
1373     Qualifiers Q = DecompType.getQualifiers();
1374     if (FD->isMutable())
1375       Q.removeConst();
1376     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1377   }
1378 
1379   if (I != Bindings.size())
1380     return DiagnoseBadNumberOfBindings();
1381 
1382   return false;
1383 }
1384 
1385 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1386   QualType DecompType = DD->getType();
1387 
1388   // If the type of the decomposition is dependent, then so is the type of
1389   // each binding.
1390   if (DecompType->isDependentType()) {
1391     for (auto *B : DD->bindings())
1392       B->setType(Context.DependentTy);
1393     return;
1394   }
1395 
1396   DecompType = DecompType.getNonReferenceType();
1397   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1398 
1399   // C++1z [dcl.decomp]/2:
1400   //   If E is an array type [...]
1401   // As an extension, we also support decomposition of built-in complex and
1402   // vector types.
1403   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1404     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1405       DD->setInvalidDecl();
1406     return;
1407   }
1408   if (auto *VT = DecompType->getAs<VectorType>()) {
1409     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1410       DD->setInvalidDecl();
1411     return;
1412   }
1413   if (auto *CT = DecompType->getAs<ComplexType>()) {
1414     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1415       DD->setInvalidDecl();
1416     return;
1417   }
1418 
1419   // C++1z [dcl.decomp]/3:
1420   //   if the expression std::tuple_size<E>::value is a well-formed integral
1421   //   constant expression, [...]
1422   llvm::APSInt TupleSize(32);
1423   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1424   case IsTupleLike::Error:
1425     DD->setInvalidDecl();
1426     return;
1427 
1428   case IsTupleLike::TupleLike:
1429     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1430       DD->setInvalidDecl();
1431     return;
1432 
1433   case IsTupleLike::NotTupleLike:
1434     break;
1435   }
1436 
1437   // C++1z [dcl.dcl]/8:
1438   //   [E shall be of array or non-union class type]
1439   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1440   if (!RD || RD->isUnion()) {
1441     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1442         << DD << !RD << DecompType;
1443     DD->setInvalidDecl();
1444     return;
1445   }
1446 
1447   // C++1z [dcl.decomp]/4:
1448   //   all of E's non-static data members shall be [...] direct members of
1449   //   E or of the same unambiguous public base class of E, ...
1450   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1451     DD->setInvalidDecl();
1452 }
1453 
1454 /// \brief Merge the exception specifications of two variable declarations.
1455 ///
1456 /// This is called when there's a redeclaration of a VarDecl. The function
1457 /// checks if the redeclaration might have an exception specification and
1458 /// validates compatibility and merges the specs if necessary.
1459 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1460   // Shortcut if exceptions are disabled.
1461   if (!getLangOpts().CXXExceptions)
1462     return;
1463 
1464   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1465          "Should only be called if types are otherwise the same.");
1466 
1467   QualType NewType = New->getType();
1468   QualType OldType = Old->getType();
1469 
1470   // We're only interested in pointers and references to functions, as well
1471   // as pointers to member functions.
1472   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1473     NewType = R->getPointeeType();
1474     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1475   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1476     NewType = P->getPointeeType();
1477     OldType = OldType->getAs<PointerType>()->getPointeeType();
1478   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1479     NewType = M->getPointeeType();
1480     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1481   }
1482 
1483   if (!NewType->isFunctionProtoType())
1484     return;
1485 
1486   // There's lots of special cases for functions. For function pointers, system
1487   // libraries are hopefully not as broken so that we don't need these
1488   // workarounds.
1489   if (CheckEquivalentExceptionSpec(
1490         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1491         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1492     New->setInvalidDecl();
1493   }
1494 }
1495 
1496 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1497 /// function declaration are well-formed according to C++
1498 /// [dcl.fct.default].
1499 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1500   unsigned NumParams = FD->getNumParams();
1501   unsigned p;
1502 
1503   // Find first parameter with a default argument
1504   for (p = 0; p < NumParams; ++p) {
1505     ParmVarDecl *Param = FD->getParamDecl(p);
1506     if (Param->hasDefaultArg())
1507       break;
1508   }
1509 
1510   // C++11 [dcl.fct.default]p4:
1511   //   In a given function declaration, each parameter subsequent to a parameter
1512   //   with a default argument shall have a default argument supplied in this or
1513   //   a previous declaration or shall be a function parameter pack. A default
1514   //   argument shall not be redefined by a later declaration (not even to the
1515   //   same value).
1516   unsigned LastMissingDefaultArg = 0;
1517   for (; p < NumParams; ++p) {
1518     ParmVarDecl *Param = FD->getParamDecl(p);
1519     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1520       if (Param->isInvalidDecl())
1521         /* We already complained about this parameter. */;
1522       else if (Param->getIdentifier())
1523         Diag(Param->getLocation(),
1524              diag::err_param_default_argument_missing_name)
1525           << Param->getIdentifier();
1526       else
1527         Diag(Param->getLocation(),
1528              diag::err_param_default_argument_missing);
1529 
1530       LastMissingDefaultArg = p;
1531     }
1532   }
1533 
1534   if (LastMissingDefaultArg > 0) {
1535     // Some default arguments were missing. Clear out all of the
1536     // default arguments up to (and including) the last missing
1537     // default argument, so that we leave the function parameters
1538     // in a semantically valid state.
1539     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1540       ParmVarDecl *Param = FD->getParamDecl(p);
1541       if (Param->hasDefaultArg()) {
1542         Param->setDefaultArg(nullptr);
1543       }
1544     }
1545   }
1546 }
1547 
1548 // CheckConstexprParameterTypes - Check whether a function's parameter types
1549 // are all literal types. If so, return true. If not, produce a suitable
1550 // diagnostic and return false.
1551 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1552                                          const FunctionDecl *FD) {
1553   unsigned ArgIndex = 0;
1554   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1555   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1556                                               e = FT->param_type_end();
1557        i != e; ++i, ++ArgIndex) {
1558     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1559     SourceLocation ParamLoc = PD->getLocation();
1560     if (!(*i)->isDependentType() &&
1561         SemaRef.RequireLiteralType(ParamLoc, *i,
1562                                    diag::err_constexpr_non_literal_param,
1563                                    ArgIndex+1, PD->getSourceRange(),
1564                                    isa<CXXConstructorDecl>(FD)))
1565       return false;
1566   }
1567   return true;
1568 }
1569 
1570 /// \brief Get diagnostic %select index for tag kind for
1571 /// record diagnostic message.
1572 /// WARNING: Indexes apply to particular diagnostics only!
1573 ///
1574 /// \returns diagnostic %select index.
1575 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1576   switch (Tag) {
1577   case TTK_Struct: return 0;
1578   case TTK_Interface: return 1;
1579   case TTK_Class:  return 2;
1580   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1581   }
1582 }
1583 
1584 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1585 // the requirements of a constexpr function definition or a constexpr
1586 // constructor definition. If so, return true. If not, produce appropriate
1587 // diagnostics and return false.
1588 //
1589 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1590 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1591   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1592   if (MD && MD->isInstance()) {
1593     // C++11 [dcl.constexpr]p4:
1594     //  The definition of a constexpr constructor shall satisfy the following
1595     //  constraints:
1596     //  - the class shall not have any virtual base classes;
1597     const CXXRecordDecl *RD = MD->getParent();
1598     if (RD->getNumVBases()) {
1599       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1600         << isa<CXXConstructorDecl>(NewFD)
1601         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1602       for (const auto &I : RD->vbases())
1603         Diag(I.getLocStart(),
1604              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1605       return false;
1606     }
1607   }
1608 
1609   if (!isa<CXXConstructorDecl>(NewFD)) {
1610     // C++11 [dcl.constexpr]p3:
1611     //  The definition of a constexpr function shall satisfy the following
1612     //  constraints:
1613     // - it shall not be virtual;
1614     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1615     if (Method && Method->isVirtual()) {
1616       Method = Method->getCanonicalDecl();
1617       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1618 
1619       // If it's not obvious why this function is virtual, find an overridden
1620       // function which uses the 'virtual' keyword.
1621       const CXXMethodDecl *WrittenVirtual = Method;
1622       while (!WrittenVirtual->isVirtualAsWritten())
1623         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1624       if (WrittenVirtual != Method)
1625         Diag(WrittenVirtual->getLocation(),
1626              diag::note_overridden_virtual_function);
1627       return false;
1628     }
1629 
1630     // - its return type shall be a literal type;
1631     QualType RT = NewFD->getReturnType();
1632     if (!RT->isDependentType() &&
1633         RequireLiteralType(NewFD->getLocation(), RT,
1634                            diag::err_constexpr_non_literal_return))
1635       return false;
1636   }
1637 
1638   // - each of its parameter types shall be a literal type;
1639   if (!CheckConstexprParameterTypes(*this, NewFD))
1640     return false;
1641 
1642   return true;
1643 }
1644 
1645 /// Check the given declaration statement is legal within a constexpr function
1646 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1647 ///
1648 /// \return true if the body is OK (maybe only as an extension), false if we
1649 ///         have diagnosed a problem.
1650 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1651                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1652   // C++11 [dcl.constexpr]p3 and p4:
1653   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1654   //  contain only
1655   for (const auto *DclIt : DS->decls()) {
1656     switch (DclIt->getKind()) {
1657     case Decl::StaticAssert:
1658     case Decl::Using:
1659     case Decl::UsingShadow:
1660     case Decl::UsingDirective:
1661     case Decl::UnresolvedUsingTypename:
1662     case Decl::UnresolvedUsingValue:
1663       //   - static_assert-declarations
1664       //   - using-declarations,
1665       //   - using-directives,
1666       continue;
1667 
1668     case Decl::Typedef:
1669     case Decl::TypeAlias: {
1670       //   - typedef declarations and alias-declarations that do not define
1671       //     classes or enumerations,
1672       const auto *TN = cast<TypedefNameDecl>(DclIt);
1673       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1674         // Don't allow variably-modified types in constexpr functions.
1675         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1676         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1677           << TL.getSourceRange() << TL.getType()
1678           << isa<CXXConstructorDecl>(Dcl);
1679         return false;
1680       }
1681       continue;
1682     }
1683 
1684     case Decl::Enum:
1685     case Decl::CXXRecord:
1686       // C++1y allows types to be defined, not just declared.
1687       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1688         SemaRef.Diag(DS->getLocStart(),
1689                      SemaRef.getLangOpts().CPlusPlus14
1690                        ? diag::warn_cxx11_compat_constexpr_type_definition
1691                        : diag::ext_constexpr_type_definition)
1692           << isa<CXXConstructorDecl>(Dcl);
1693       continue;
1694 
1695     case Decl::EnumConstant:
1696     case Decl::IndirectField:
1697     case Decl::ParmVar:
1698       // These can only appear with other declarations which are banned in
1699       // C++11 and permitted in C++1y, so ignore them.
1700       continue;
1701 
1702     case Decl::Var:
1703     case Decl::Decomposition: {
1704       // C++1y [dcl.constexpr]p3 allows anything except:
1705       //   a definition of a variable of non-literal type or of static or
1706       //   thread storage duration or for which no initialization is performed.
1707       const auto *VD = cast<VarDecl>(DclIt);
1708       if (VD->isThisDeclarationADefinition()) {
1709         if (VD->isStaticLocal()) {
1710           SemaRef.Diag(VD->getLocation(),
1711                        diag::err_constexpr_local_var_static)
1712             << isa<CXXConstructorDecl>(Dcl)
1713             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1714           return false;
1715         }
1716         if (!VD->getType()->isDependentType() &&
1717             SemaRef.RequireLiteralType(
1718               VD->getLocation(), VD->getType(),
1719               diag::err_constexpr_local_var_non_literal_type,
1720               isa<CXXConstructorDecl>(Dcl)))
1721           return false;
1722         if (!VD->getType()->isDependentType() &&
1723             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1724           SemaRef.Diag(VD->getLocation(),
1725                        diag::err_constexpr_local_var_no_init)
1726             << isa<CXXConstructorDecl>(Dcl);
1727           return false;
1728         }
1729       }
1730       SemaRef.Diag(VD->getLocation(),
1731                    SemaRef.getLangOpts().CPlusPlus14
1732                     ? diag::warn_cxx11_compat_constexpr_local_var
1733                     : diag::ext_constexpr_local_var)
1734         << isa<CXXConstructorDecl>(Dcl);
1735       continue;
1736     }
1737 
1738     case Decl::NamespaceAlias:
1739     case Decl::Function:
1740       // These are disallowed in C++11 and permitted in C++1y. Allow them
1741       // everywhere as an extension.
1742       if (!Cxx1yLoc.isValid())
1743         Cxx1yLoc = DS->getLocStart();
1744       continue;
1745 
1746     default:
1747       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1748         << isa<CXXConstructorDecl>(Dcl);
1749       return false;
1750     }
1751   }
1752 
1753   return true;
1754 }
1755 
1756 /// Check that the given field is initialized within a constexpr constructor.
1757 ///
1758 /// \param Dcl The constexpr constructor being checked.
1759 /// \param Field The field being checked. This may be a member of an anonymous
1760 ///        struct or union nested within the class being checked.
1761 /// \param Inits All declarations, including anonymous struct/union members and
1762 ///        indirect members, for which any initialization was provided.
1763 /// \param Diagnosed Set to true if an error is produced.
1764 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1765                                           const FunctionDecl *Dcl,
1766                                           FieldDecl *Field,
1767                                           llvm::SmallSet<Decl*, 16> &Inits,
1768                                           bool &Diagnosed) {
1769   if (Field->isInvalidDecl())
1770     return;
1771 
1772   if (Field->isUnnamedBitfield())
1773     return;
1774 
1775   // Anonymous unions with no variant members and empty anonymous structs do not
1776   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1777   // indirect fields don't need initializing.
1778   if (Field->isAnonymousStructOrUnion() &&
1779       (Field->getType()->isUnionType()
1780            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1781            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1782     return;
1783 
1784   if (!Inits.count(Field)) {
1785     if (!Diagnosed) {
1786       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1787       Diagnosed = true;
1788     }
1789     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1790   } else if (Field->isAnonymousStructOrUnion()) {
1791     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1792     for (auto *I : RD->fields())
1793       // If an anonymous union contains an anonymous struct of which any member
1794       // is initialized, all members must be initialized.
1795       if (!RD->isUnion() || Inits.count(I))
1796         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1797   }
1798 }
1799 
1800 /// Check the provided statement is allowed in a constexpr function
1801 /// definition.
1802 static bool
1803 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1804                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1805                            SourceLocation &Cxx1yLoc) {
1806   // - its function-body shall be [...] a compound-statement that contains only
1807   switch (S->getStmtClass()) {
1808   case Stmt::NullStmtClass:
1809     //   - null statements,
1810     return true;
1811 
1812   case Stmt::DeclStmtClass:
1813     //   - static_assert-declarations
1814     //   - using-declarations,
1815     //   - using-directives,
1816     //   - typedef declarations and alias-declarations that do not define
1817     //     classes or enumerations,
1818     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1819       return false;
1820     return true;
1821 
1822   case Stmt::ReturnStmtClass:
1823     //   - and exactly one return statement;
1824     if (isa<CXXConstructorDecl>(Dcl)) {
1825       // C++1y allows return statements in constexpr constructors.
1826       if (!Cxx1yLoc.isValid())
1827         Cxx1yLoc = S->getLocStart();
1828       return true;
1829     }
1830 
1831     ReturnStmts.push_back(S->getLocStart());
1832     return true;
1833 
1834   case Stmt::CompoundStmtClass: {
1835     // C++1y allows compound-statements.
1836     if (!Cxx1yLoc.isValid())
1837       Cxx1yLoc = S->getLocStart();
1838 
1839     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1840     for (auto *BodyIt : CompStmt->body()) {
1841       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1842                                       Cxx1yLoc))
1843         return false;
1844     }
1845     return true;
1846   }
1847 
1848   case Stmt::AttributedStmtClass:
1849     if (!Cxx1yLoc.isValid())
1850       Cxx1yLoc = S->getLocStart();
1851     return true;
1852 
1853   case Stmt::IfStmtClass: {
1854     // C++1y allows if-statements.
1855     if (!Cxx1yLoc.isValid())
1856       Cxx1yLoc = S->getLocStart();
1857 
1858     IfStmt *If = cast<IfStmt>(S);
1859     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1860                                     Cxx1yLoc))
1861       return false;
1862     if (If->getElse() &&
1863         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1864                                     Cxx1yLoc))
1865       return false;
1866     return true;
1867   }
1868 
1869   case Stmt::WhileStmtClass:
1870   case Stmt::DoStmtClass:
1871   case Stmt::ForStmtClass:
1872   case Stmt::CXXForRangeStmtClass:
1873   case Stmt::ContinueStmtClass:
1874     // C++1y allows all of these. We don't allow them as extensions in C++11,
1875     // because they don't make sense without variable mutation.
1876     if (!SemaRef.getLangOpts().CPlusPlus14)
1877       break;
1878     if (!Cxx1yLoc.isValid())
1879       Cxx1yLoc = S->getLocStart();
1880     for (Stmt *SubStmt : S->children())
1881       if (SubStmt &&
1882           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1883                                       Cxx1yLoc))
1884         return false;
1885     return true;
1886 
1887   case Stmt::SwitchStmtClass:
1888   case Stmt::CaseStmtClass:
1889   case Stmt::DefaultStmtClass:
1890   case Stmt::BreakStmtClass:
1891     // C++1y allows switch-statements, and since they don't need variable
1892     // mutation, we can reasonably allow them in C++11 as an extension.
1893     if (!Cxx1yLoc.isValid())
1894       Cxx1yLoc = S->getLocStart();
1895     for (Stmt *SubStmt : S->children())
1896       if (SubStmt &&
1897           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1898                                       Cxx1yLoc))
1899         return false;
1900     return true;
1901 
1902   default:
1903     if (!isa<Expr>(S))
1904       break;
1905 
1906     // C++1y allows expression-statements.
1907     if (!Cxx1yLoc.isValid())
1908       Cxx1yLoc = S->getLocStart();
1909     return true;
1910   }
1911 
1912   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1913     << isa<CXXConstructorDecl>(Dcl);
1914   return false;
1915 }
1916 
1917 /// Check the body for the given constexpr function declaration only contains
1918 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1919 ///
1920 /// \return true if the body is OK, false if we have diagnosed a problem.
1921 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1922   if (isa<CXXTryStmt>(Body)) {
1923     // C++11 [dcl.constexpr]p3:
1924     //  The definition of a constexpr function shall satisfy the following
1925     //  constraints: [...]
1926     // - its function-body shall be = delete, = default, or a
1927     //   compound-statement
1928     //
1929     // C++11 [dcl.constexpr]p4:
1930     //  In the definition of a constexpr constructor, [...]
1931     // - its function-body shall not be a function-try-block;
1932     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1933       << isa<CXXConstructorDecl>(Dcl);
1934     return false;
1935   }
1936 
1937   SmallVector<SourceLocation, 4> ReturnStmts;
1938 
1939   // - its function-body shall be [...] a compound-statement that contains only
1940   //   [... list of cases ...]
1941   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1942   SourceLocation Cxx1yLoc;
1943   for (auto *BodyIt : CompBody->body()) {
1944     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1945       return false;
1946   }
1947 
1948   if (Cxx1yLoc.isValid())
1949     Diag(Cxx1yLoc,
1950          getLangOpts().CPlusPlus14
1951            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1952            : diag::ext_constexpr_body_invalid_stmt)
1953       << isa<CXXConstructorDecl>(Dcl);
1954 
1955   if (const CXXConstructorDecl *Constructor
1956         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1957     const CXXRecordDecl *RD = Constructor->getParent();
1958     // DR1359:
1959     // - every non-variant non-static data member and base class sub-object
1960     //   shall be initialized;
1961     // DR1460:
1962     // - if the class is a union having variant members, exactly one of them
1963     //   shall be initialized;
1964     if (RD->isUnion()) {
1965       if (Constructor->getNumCtorInitializers() == 0 &&
1966           RD->hasVariantMembers()) {
1967         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1968         return false;
1969       }
1970     } else if (!Constructor->isDependentContext() &&
1971                !Constructor->isDelegatingConstructor()) {
1972       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1973 
1974       // Skip detailed checking if we have enough initializers, and we would
1975       // allow at most one initializer per member.
1976       bool AnyAnonStructUnionMembers = false;
1977       unsigned Fields = 0;
1978       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1979            E = RD->field_end(); I != E; ++I, ++Fields) {
1980         if (I->isAnonymousStructOrUnion()) {
1981           AnyAnonStructUnionMembers = true;
1982           break;
1983         }
1984       }
1985       // DR1460:
1986       // - if the class is a union-like class, but is not a union, for each of
1987       //   its anonymous union members having variant members, exactly one of
1988       //   them shall be initialized;
1989       if (AnyAnonStructUnionMembers ||
1990           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1991         // Check initialization of non-static data members. Base classes are
1992         // always initialized so do not need to be checked. Dependent bases
1993         // might not have initializers in the member initializer list.
1994         llvm::SmallSet<Decl*, 16> Inits;
1995         for (const auto *I: Constructor->inits()) {
1996           if (FieldDecl *FD = I->getMember())
1997             Inits.insert(FD);
1998           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1999             Inits.insert(ID->chain_begin(), ID->chain_end());
2000         }
2001 
2002         bool Diagnosed = false;
2003         for (auto *I : RD->fields())
2004           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2005         if (Diagnosed)
2006           return false;
2007       }
2008     }
2009   } else {
2010     if (ReturnStmts.empty()) {
2011       // C++1y doesn't require constexpr functions to contain a 'return'
2012       // statement. We still do, unless the return type might be void, because
2013       // otherwise if there's no return statement, the function cannot
2014       // be used in a core constant expression.
2015       bool OK = getLangOpts().CPlusPlus14 &&
2016                 (Dcl->getReturnType()->isVoidType() ||
2017                  Dcl->getReturnType()->isDependentType());
2018       Diag(Dcl->getLocation(),
2019            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2020               : diag::err_constexpr_body_no_return);
2021       if (!OK)
2022         return false;
2023     } else if (ReturnStmts.size() > 1) {
2024       Diag(ReturnStmts.back(),
2025            getLangOpts().CPlusPlus14
2026              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2027              : diag::ext_constexpr_body_multiple_return);
2028       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2029         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2030     }
2031   }
2032 
2033   // C++11 [dcl.constexpr]p5:
2034   //   if no function argument values exist such that the function invocation
2035   //   substitution would produce a constant expression, the program is
2036   //   ill-formed; no diagnostic required.
2037   // C++11 [dcl.constexpr]p3:
2038   //   - every constructor call and implicit conversion used in initializing the
2039   //     return value shall be one of those allowed in a constant expression.
2040   // C++11 [dcl.constexpr]p4:
2041   //   - every constructor involved in initializing non-static data members and
2042   //     base class sub-objects shall be a constexpr constructor.
2043   SmallVector<PartialDiagnosticAt, 8> Diags;
2044   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2045     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2046       << isa<CXXConstructorDecl>(Dcl);
2047     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2048       Diag(Diags[I].first, Diags[I].second);
2049     // Don't return false here: we allow this for compatibility in
2050     // system headers.
2051   }
2052 
2053   return true;
2054 }
2055 
2056 /// isCurrentClassName - Determine whether the identifier II is the
2057 /// name of the class type currently being defined. In the case of
2058 /// nested classes, this will only return true if II is the name of
2059 /// the innermost class.
2060 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2061                               const CXXScopeSpec *SS) {
2062   assert(getLangOpts().CPlusPlus && "No class names in C!");
2063 
2064   CXXRecordDecl *CurDecl;
2065   if (SS && SS->isSet() && !SS->isInvalid()) {
2066     DeclContext *DC = computeDeclContext(*SS, true);
2067     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2068   } else
2069     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2070 
2071   if (CurDecl && CurDecl->getIdentifier())
2072     return &II == CurDecl->getIdentifier();
2073   return false;
2074 }
2075 
2076 /// \brief Determine whether the identifier II is a typo for the name of
2077 /// the class type currently being defined. If so, update it to the identifier
2078 /// that should have been used.
2079 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2080   assert(getLangOpts().CPlusPlus && "No class names in C!");
2081 
2082   if (!getLangOpts().SpellChecking)
2083     return false;
2084 
2085   CXXRecordDecl *CurDecl;
2086   if (SS && SS->isSet() && !SS->isInvalid()) {
2087     DeclContext *DC = computeDeclContext(*SS, true);
2088     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2089   } else
2090     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2091 
2092   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2093       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2094           < II->getLength()) {
2095     II = CurDecl->getIdentifier();
2096     return true;
2097   }
2098 
2099   return false;
2100 }
2101 
2102 /// \brief Determine whether the given class is a base class of the given
2103 /// class, including looking at dependent bases.
2104 static bool findCircularInheritance(const CXXRecordDecl *Class,
2105                                     const CXXRecordDecl *Current) {
2106   SmallVector<const CXXRecordDecl*, 8> Queue;
2107 
2108   Class = Class->getCanonicalDecl();
2109   while (true) {
2110     for (const auto &I : Current->bases()) {
2111       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2112       if (!Base)
2113         continue;
2114 
2115       Base = Base->getDefinition();
2116       if (!Base)
2117         continue;
2118 
2119       if (Base->getCanonicalDecl() == Class)
2120         return true;
2121 
2122       Queue.push_back(Base);
2123     }
2124 
2125     if (Queue.empty())
2126       return false;
2127 
2128     Current = Queue.pop_back_val();
2129   }
2130 
2131   return false;
2132 }
2133 
2134 /// \brief Check the validity of a C++ base class specifier.
2135 ///
2136 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2137 /// and returns NULL otherwise.
2138 CXXBaseSpecifier *
2139 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2140                          SourceRange SpecifierRange,
2141                          bool Virtual, AccessSpecifier Access,
2142                          TypeSourceInfo *TInfo,
2143                          SourceLocation EllipsisLoc) {
2144   QualType BaseType = TInfo->getType();
2145 
2146   // C++ [class.union]p1:
2147   //   A union shall not have base classes.
2148   if (Class->isUnion()) {
2149     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2150       << SpecifierRange;
2151     return nullptr;
2152   }
2153 
2154   if (EllipsisLoc.isValid() &&
2155       !TInfo->getType()->containsUnexpandedParameterPack()) {
2156     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2157       << TInfo->getTypeLoc().getSourceRange();
2158     EllipsisLoc = SourceLocation();
2159   }
2160 
2161   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2162 
2163   if (BaseType->isDependentType()) {
2164     // Make sure that we don't have circular inheritance among our dependent
2165     // bases. For non-dependent bases, the check for completeness below handles
2166     // this.
2167     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2168       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2169           ((BaseDecl = BaseDecl->getDefinition()) &&
2170            findCircularInheritance(Class, BaseDecl))) {
2171         Diag(BaseLoc, diag::err_circular_inheritance)
2172           << BaseType << Context.getTypeDeclType(Class);
2173 
2174         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2175           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2176             << BaseType;
2177 
2178         return nullptr;
2179       }
2180     }
2181 
2182     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2183                                           Class->getTagKind() == TTK_Class,
2184                                           Access, TInfo, EllipsisLoc);
2185   }
2186 
2187   // Base specifiers must be record types.
2188   if (!BaseType->isRecordType()) {
2189     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2190     return nullptr;
2191   }
2192 
2193   // C++ [class.union]p1:
2194   //   A union shall not be used as a base class.
2195   if (BaseType->isUnionType()) {
2196     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2197     return nullptr;
2198   }
2199 
2200   // For the MS ABI, propagate DLL attributes to base class templates.
2201   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2202     if (Attr *ClassAttr = getDLLAttr(Class)) {
2203       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2204               BaseType->getAsCXXRecordDecl())) {
2205         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2206                                             BaseLoc);
2207       }
2208     }
2209   }
2210 
2211   // C++ [class.derived]p2:
2212   //   The class-name in a base-specifier shall not be an incompletely
2213   //   defined class.
2214   if (RequireCompleteType(BaseLoc, BaseType,
2215                           diag::err_incomplete_base_class, SpecifierRange)) {
2216     Class->setInvalidDecl();
2217     return nullptr;
2218   }
2219 
2220   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2221   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2222   assert(BaseDecl && "Record type has no declaration");
2223   BaseDecl = BaseDecl->getDefinition();
2224   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2225   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2226   assert(CXXBaseDecl && "Base type is not a C++ type");
2227 
2228   // A class which contains a flexible array member is not suitable for use as a
2229   // base class:
2230   //   - If the layout determines that a base comes before another base,
2231   //     the flexible array member would index into the subsequent base.
2232   //   - If the layout determines that base comes before the derived class,
2233   //     the flexible array member would index into the derived class.
2234   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2235     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2236       << CXXBaseDecl->getDeclName();
2237     return nullptr;
2238   }
2239 
2240   // C++ [class]p3:
2241   //   If a class is marked final and it appears as a base-type-specifier in
2242   //   base-clause, the program is ill-formed.
2243   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2244     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2245       << CXXBaseDecl->getDeclName()
2246       << FA->isSpelledAsSealed();
2247     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2248         << CXXBaseDecl->getDeclName() << FA->getRange();
2249     return nullptr;
2250   }
2251 
2252   if (BaseDecl->isInvalidDecl())
2253     Class->setInvalidDecl();
2254 
2255   // Create the base specifier.
2256   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2257                                         Class->getTagKind() == TTK_Class,
2258                                         Access, TInfo, EllipsisLoc);
2259 }
2260 
2261 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2262 /// one entry in the base class list of a class specifier, for
2263 /// example:
2264 ///    class foo : public bar, virtual private baz {
2265 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2266 BaseResult
2267 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2268                          ParsedAttributes &Attributes,
2269                          bool Virtual, AccessSpecifier Access,
2270                          ParsedType basetype, SourceLocation BaseLoc,
2271                          SourceLocation EllipsisLoc) {
2272   if (!classdecl)
2273     return true;
2274 
2275   AdjustDeclIfTemplate(classdecl);
2276   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2277   if (!Class)
2278     return true;
2279 
2280   // We haven't yet attached the base specifiers.
2281   Class->setIsParsingBaseSpecifiers();
2282 
2283   // We do not support any C++11 attributes on base-specifiers yet.
2284   // Diagnose any attributes we see.
2285   if (!Attributes.empty()) {
2286     for (AttributeList *Attr = Attributes.getList(); Attr;
2287          Attr = Attr->getNext()) {
2288       if (Attr->isInvalid() ||
2289           Attr->getKind() == AttributeList::IgnoredAttribute)
2290         continue;
2291       Diag(Attr->getLoc(),
2292            Attr->getKind() == AttributeList::UnknownAttribute
2293              ? diag::warn_unknown_attribute_ignored
2294              : diag::err_base_specifier_attribute)
2295         << Attr->getName();
2296     }
2297   }
2298 
2299   TypeSourceInfo *TInfo = nullptr;
2300   GetTypeFromParser(basetype, &TInfo);
2301 
2302   if (EllipsisLoc.isInvalid() &&
2303       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2304                                       UPPC_BaseType))
2305     return true;
2306 
2307   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2308                                                       Virtual, Access, TInfo,
2309                                                       EllipsisLoc))
2310     return BaseSpec;
2311   else
2312     Class->setInvalidDecl();
2313 
2314   return true;
2315 }
2316 
2317 /// Use small set to collect indirect bases.  As this is only used
2318 /// locally, there's no need to abstract the small size parameter.
2319 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2320 
2321 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2322 static void
2323 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2324                   const QualType &Type)
2325 {
2326   // Even though the incoming type is a base, it might not be
2327   // a class -- it could be a template parm, for instance.
2328   if (auto Rec = Type->getAs<RecordType>()) {
2329     auto Decl = Rec->getAsCXXRecordDecl();
2330 
2331     // Iterate over its bases.
2332     for (const auto &BaseSpec : Decl->bases()) {
2333       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2334         .getUnqualifiedType();
2335       if (Set.insert(Base).second)
2336         // If we've not already seen it, recurse.
2337         NoteIndirectBases(Context, Set, Base);
2338     }
2339   }
2340 }
2341 
2342 /// \brief Performs the actual work of attaching the given base class
2343 /// specifiers to a C++ class.
2344 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2345                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2346  if (Bases.empty())
2347     return false;
2348 
2349   // Used to keep track of which base types we have already seen, so
2350   // that we can properly diagnose redundant direct base types. Note
2351   // that the key is always the unqualified canonical type of the base
2352   // class.
2353   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2354 
2355   // Used to track indirect bases so we can see if a direct base is
2356   // ambiguous.
2357   IndirectBaseSet IndirectBaseTypes;
2358 
2359   // Copy non-redundant base specifiers into permanent storage.
2360   unsigned NumGoodBases = 0;
2361   bool Invalid = false;
2362   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2363     QualType NewBaseType
2364       = Context.getCanonicalType(Bases[idx]->getType());
2365     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2366 
2367     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2368     if (KnownBase) {
2369       // C++ [class.mi]p3:
2370       //   A class shall not be specified as a direct base class of a
2371       //   derived class more than once.
2372       Diag(Bases[idx]->getLocStart(),
2373            diag::err_duplicate_base_class)
2374         << KnownBase->getType()
2375         << Bases[idx]->getSourceRange();
2376 
2377       // Delete the duplicate base class specifier; we're going to
2378       // overwrite its pointer later.
2379       Context.Deallocate(Bases[idx]);
2380 
2381       Invalid = true;
2382     } else {
2383       // Okay, add this new base class.
2384       KnownBase = Bases[idx];
2385       Bases[NumGoodBases++] = Bases[idx];
2386 
2387       // Note this base's direct & indirect bases, if there could be ambiguity.
2388       if (Bases.size() > 1)
2389         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2390 
2391       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2392         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2393         if (Class->isInterface() &&
2394               (!RD->isInterfaceLike() ||
2395                KnownBase->getAccessSpecifier() != AS_public)) {
2396           // The Microsoft extension __interface does not permit bases that
2397           // are not themselves public interfaces.
2398           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2399             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2400             << RD->getSourceRange();
2401           Invalid = true;
2402         }
2403         if (RD->hasAttr<WeakAttr>())
2404           Class->addAttr(WeakAttr::CreateImplicit(Context));
2405       }
2406     }
2407   }
2408 
2409   // Attach the remaining base class specifiers to the derived class.
2410   Class->setBases(Bases.data(), NumGoodBases);
2411 
2412   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2413     // Check whether this direct base is inaccessible due to ambiguity.
2414     QualType BaseType = Bases[idx]->getType();
2415     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2416       .getUnqualifiedType();
2417 
2418     if (IndirectBaseTypes.count(CanonicalBase)) {
2419       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2420                          /*DetectVirtual=*/true);
2421       bool found
2422         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2423       assert(found);
2424       (void)found;
2425 
2426       if (Paths.isAmbiguous(CanonicalBase))
2427         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2428           << BaseType << getAmbiguousPathsDisplayString(Paths)
2429           << Bases[idx]->getSourceRange();
2430       else
2431         assert(Bases[idx]->isVirtual());
2432     }
2433 
2434     // Delete the base class specifier, since its data has been copied
2435     // into the CXXRecordDecl.
2436     Context.Deallocate(Bases[idx]);
2437   }
2438 
2439   return Invalid;
2440 }
2441 
2442 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2443 /// class, after checking whether there are any duplicate base
2444 /// classes.
2445 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2446                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2447   if (!ClassDecl || Bases.empty())
2448     return;
2449 
2450   AdjustDeclIfTemplate(ClassDecl);
2451   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2452 }
2453 
2454 /// \brief Determine whether the type \p Derived is a C++ class that is
2455 /// derived from the type \p Base.
2456 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2457   if (!getLangOpts().CPlusPlus)
2458     return false;
2459 
2460   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2461   if (!DerivedRD)
2462     return false;
2463 
2464   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2465   if (!BaseRD)
2466     return false;
2467 
2468   // If either the base or the derived type is invalid, don't try to
2469   // check whether one is derived from the other.
2470   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2471     return false;
2472 
2473   // FIXME: In a modules build, do we need the entire path to be visible for us
2474   // to be able to use the inheritance relationship?
2475   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2476     return false;
2477 
2478   return DerivedRD->isDerivedFrom(BaseRD);
2479 }
2480 
2481 /// \brief Determine whether the type \p Derived is a C++ class that is
2482 /// derived from the type \p Base.
2483 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2484                          CXXBasePaths &Paths) {
2485   if (!getLangOpts().CPlusPlus)
2486     return false;
2487 
2488   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2489   if (!DerivedRD)
2490     return false;
2491 
2492   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2493   if (!BaseRD)
2494     return false;
2495 
2496   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2497     return false;
2498 
2499   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2500 }
2501 
2502 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2503                               CXXCastPath &BasePathArray) {
2504   assert(BasePathArray.empty() && "Base path array must be empty!");
2505   assert(Paths.isRecordingPaths() && "Must record paths!");
2506 
2507   const CXXBasePath &Path = Paths.front();
2508 
2509   // We first go backward and check if we have a virtual base.
2510   // FIXME: It would be better if CXXBasePath had the base specifier for
2511   // the nearest virtual base.
2512   unsigned Start = 0;
2513   for (unsigned I = Path.size(); I != 0; --I) {
2514     if (Path[I - 1].Base->isVirtual()) {
2515       Start = I - 1;
2516       break;
2517     }
2518   }
2519 
2520   // Now add all bases.
2521   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2522     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2523 }
2524 
2525 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2526 /// conversion (where Derived and Base are class types) is
2527 /// well-formed, meaning that the conversion is unambiguous (and
2528 /// that all of the base classes are accessible). Returns true
2529 /// and emits a diagnostic if the code is ill-formed, returns false
2530 /// otherwise. Loc is the location where this routine should point to
2531 /// if there is an error, and Range is the source range to highlight
2532 /// if there is an error.
2533 ///
2534 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2535 /// diagnostic for the respective type of error will be suppressed, but the
2536 /// check for ill-formed code will still be performed.
2537 bool
2538 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2539                                    unsigned InaccessibleBaseID,
2540                                    unsigned AmbigiousBaseConvID,
2541                                    SourceLocation Loc, SourceRange Range,
2542                                    DeclarationName Name,
2543                                    CXXCastPath *BasePath,
2544                                    bool IgnoreAccess) {
2545   // First, determine whether the path from Derived to Base is
2546   // ambiguous. This is slightly more expensive than checking whether
2547   // the Derived to Base conversion exists, because here we need to
2548   // explore multiple paths to determine if there is an ambiguity.
2549   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2550                      /*DetectVirtual=*/false);
2551   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2552   assert(DerivationOkay &&
2553          "Can only be used with a derived-to-base conversion");
2554   (void)DerivationOkay;
2555 
2556   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2557     if (!IgnoreAccess) {
2558       // Check that the base class can be accessed.
2559       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2560                                    InaccessibleBaseID)) {
2561         case AR_inaccessible:
2562           return true;
2563         case AR_accessible:
2564         case AR_dependent:
2565         case AR_delayed:
2566           break;
2567       }
2568     }
2569 
2570     // Build a base path if necessary.
2571     if (BasePath)
2572       BuildBasePathArray(Paths, *BasePath);
2573     return false;
2574   }
2575 
2576   if (AmbigiousBaseConvID) {
2577     // We know that the derived-to-base conversion is ambiguous, and
2578     // we're going to produce a diagnostic. Perform the derived-to-base
2579     // search just one more time to compute all of the possible paths so
2580     // that we can print them out. This is more expensive than any of
2581     // the previous derived-to-base checks we've done, but at this point
2582     // performance isn't as much of an issue.
2583     Paths.clear();
2584     Paths.setRecordingPaths(true);
2585     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2586     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2587     (void)StillOkay;
2588 
2589     // Build up a textual representation of the ambiguous paths, e.g.,
2590     // D -> B -> A, that will be used to illustrate the ambiguous
2591     // conversions in the diagnostic. We only print one of the paths
2592     // to each base class subobject.
2593     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2594 
2595     Diag(Loc, AmbigiousBaseConvID)
2596     << Derived << Base << PathDisplayStr << Range << Name;
2597   }
2598   return true;
2599 }
2600 
2601 bool
2602 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2603                                    SourceLocation Loc, SourceRange Range,
2604                                    CXXCastPath *BasePath,
2605                                    bool IgnoreAccess) {
2606   return CheckDerivedToBaseConversion(
2607       Derived, Base, diag::err_upcast_to_inaccessible_base,
2608       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2609       BasePath, IgnoreAccess);
2610 }
2611 
2612 
2613 /// @brief Builds a string representing ambiguous paths from a
2614 /// specific derived class to different subobjects of the same base
2615 /// class.
2616 ///
2617 /// This function builds a string that can be used in error messages
2618 /// to show the different paths that one can take through the
2619 /// inheritance hierarchy to go from the derived class to different
2620 /// subobjects of a base class. The result looks something like this:
2621 /// @code
2622 /// struct D -> struct B -> struct A
2623 /// struct D -> struct C -> struct A
2624 /// @endcode
2625 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2626   std::string PathDisplayStr;
2627   std::set<unsigned> DisplayedPaths;
2628   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2629        Path != Paths.end(); ++Path) {
2630     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2631       // We haven't displayed a path to this particular base
2632       // class subobject yet.
2633       PathDisplayStr += "\n    ";
2634       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2635       for (CXXBasePath::const_iterator Element = Path->begin();
2636            Element != Path->end(); ++Element)
2637         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2638     }
2639   }
2640 
2641   return PathDisplayStr;
2642 }
2643 
2644 //===----------------------------------------------------------------------===//
2645 // C++ class member Handling
2646 //===----------------------------------------------------------------------===//
2647 
2648 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2649 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2650                                 SourceLocation ASLoc,
2651                                 SourceLocation ColonLoc,
2652                                 AttributeList *Attrs) {
2653   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2654   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2655                                                   ASLoc, ColonLoc);
2656   CurContext->addHiddenDecl(ASDecl);
2657   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2658 }
2659 
2660 /// CheckOverrideControl - Check C++11 override control semantics.
2661 void Sema::CheckOverrideControl(NamedDecl *D) {
2662   if (D->isInvalidDecl())
2663     return;
2664 
2665   // We only care about "override" and "final" declarations.
2666   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2667     return;
2668 
2669   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2670 
2671   // We can't check dependent instance methods.
2672   if (MD && MD->isInstance() &&
2673       (MD->getParent()->hasAnyDependentBases() ||
2674        MD->getType()->isDependentType()))
2675     return;
2676 
2677   if (MD && !MD->isVirtual()) {
2678     // If we have a non-virtual method, check if if hides a virtual method.
2679     // (In that case, it's most likely the method has the wrong type.)
2680     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2681     FindHiddenVirtualMethods(MD, OverloadedMethods);
2682 
2683     if (!OverloadedMethods.empty()) {
2684       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2685         Diag(OA->getLocation(),
2686              diag::override_keyword_hides_virtual_member_function)
2687           << "override" << (OverloadedMethods.size() > 1);
2688       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2689         Diag(FA->getLocation(),
2690              diag::override_keyword_hides_virtual_member_function)
2691           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2692           << (OverloadedMethods.size() > 1);
2693       }
2694       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2695       MD->setInvalidDecl();
2696       return;
2697     }
2698     // Fall through into the general case diagnostic.
2699     // FIXME: We might want to attempt typo correction here.
2700   }
2701 
2702   if (!MD || !MD->isVirtual()) {
2703     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2704       Diag(OA->getLocation(),
2705            diag::override_keyword_only_allowed_on_virtual_member_functions)
2706         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2707       D->dropAttr<OverrideAttr>();
2708     }
2709     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2710       Diag(FA->getLocation(),
2711            diag::override_keyword_only_allowed_on_virtual_member_functions)
2712         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2713         << FixItHint::CreateRemoval(FA->getLocation());
2714       D->dropAttr<FinalAttr>();
2715     }
2716     return;
2717   }
2718 
2719   // C++11 [class.virtual]p5:
2720   //   If a function is marked with the virt-specifier override and
2721   //   does not override a member function of a base class, the program is
2722   //   ill-formed.
2723   bool HasOverriddenMethods =
2724     MD->begin_overridden_methods() != MD->end_overridden_methods();
2725   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2726     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2727       << MD->getDeclName();
2728 }
2729 
2730 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2731   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2732     return;
2733   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2734   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2735     return;
2736 
2737   SourceLocation Loc = MD->getLocation();
2738   SourceLocation SpellingLoc = Loc;
2739   if (getSourceManager().isMacroArgExpansion(Loc))
2740     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2741   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2742   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2743       return;
2744 
2745   if (MD->size_overridden_methods() > 0) {
2746     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2747                           ? diag::warn_destructor_marked_not_override_overriding
2748                           : diag::warn_function_marked_not_override_overriding;
2749     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2750     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2751     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2752   }
2753 }
2754 
2755 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2756 /// function overrides a virtual member function marked 'final', according to
2757 /// C++11 [class.virtual]p4.
2758 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2759                                                   const CXXMethodDecl *Old) {
2760   FinalAttr *FA = Old->getAttr<FinalAttr>();
2761   if (!FA)
2762     return false;
2763 
2764   Diag(New->getLocation(), diag::err_final_function_overridden)
2765     << New->getDeclName()
2766     << FA->isSpelledAsSealed();
2767   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2768   return true;
2769 }
2770 
2771 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2772   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2773   // FIXME: Destruction of ObjC lifetime types has side-effects.
2774   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2775     return !RD->isCompleteDefinition() ||
2776            !RD->hasTrivialDefaultConstructor() ||
2777            !RD->hasTrivialDestructor();
2778   return false;
2779 }
2780 
2781 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2782   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2783     if (it->isDeclspecPropertyAttribute())
2784       return it;
2785   return nullptr;
2786 }
2787 
2788 // Check if there is a field shadowing.
2789 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2790                                       DeclarationName FieldName,
2791                                       const CXXRecordDecl *RD) {
2792   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2793     return;
2794 
2795   // To record a shadowed field in a base
2796   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2797   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2798                            CXXBasePath &Path) {
2799     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2800     // Record an ambiguous path directly
2801     if (Bases.find(Base) != Bases.end())
2802       return true;
2803     for (const auto Field : Base->lookup(FieldName)) {
2804       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2805           Field->getAccess() != AS_private) {
2806         assert(Field->getAccess() != AS_none);
2807         assert(Bases.find(Base) == Bases.end());
2808         Bases[Base] = Field;
2809         return true;
2810       }
2811     }
2812     return false;
2813   };
2814 
2815   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2816                      /*DetectVirtual=*/true);
2817   if (!RD->lookupInBases(FieldShadowed, Paths))
2818     return;
2819 
2820   for (const auto &P : Paths) {
2821     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2822     auto It = Bases.find(Base);
2823     // Skip duplicated bases
2824     if (It == Bases.end())
2825       continue;
2826     auto BaseField = It->second;
2827     assert(BaseField->getAccess() != AS_private);
2828     if (AS_none !=
2829         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2830       Diag(Loc, diag::warn_shadow_field)
2831         << FieldName.getAsString() << RD->getName() << Base->getName();
2832       Diag(BaseField->getLocation(), diag::note_shadow_field);
2833       Bases.erase(It);
2834     }
2835   }
2836 }
2837 
2838 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2839 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2840 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2841 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2842 /// present (but parsing it has been deferred).
2843 NamedDecl *
2844 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2845                                MultiTemplateParamsArg TemplateParameterLists,
2846                                Expr *BW, const VirtSpecifiers &VS,
2847                                InClassInitStyle InitStyle) {
2848   const DeclSpec &DS = D.getDeclSpec();
2849   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2850   DeclarationName Name = NameInfo.getName();
2851   SourceLocation Loc = NameInfo.getLoc();
2852 
2853   // For anonymous bitfields, the location should point to the type.
2854   if (Loc.isInvalid())
2855     Loc = D.getLocStart();
2856 
2857   Expr *BitWidth = static_cast<Expr*>(BW);
2858 
2859   assert(isa<CXXRecordDecl>(CurContext));
2860   assert(!DS.isFriendSpecified());
2861 
2862   bool isFunc = D.isDeclarationOfFunction();
2863   AttributeList *MSPropertyAttr =
2864       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2865 
2866   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2867     // The Microsoft extension __interface only permits public member functions
2868     // and prohibits constructors, destructors, operators, non-public member
2869     // functions, static methods and data members.
2870     unsigned InvalidDecl;
2871     bool ShowDeclName = true;
2872     if (!isFunc &&
2873         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2874       InvalidDecl = 0;
2875     else if (!isFunc)
2876       InvalidDecl = 1;
2877     else if (AS != AS_public)
2878       InvalidDecl = 2;
2879     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2880       InvalidDecl = 3;
2881     else switch (Name.getNameKind()) {
2882       case DeclarationName::CXXConstructorName:
2883         InvalidDecl = 4;
2884         ShowDeclName = false;
2885         break;
2886 
2887       case DeclarationName::CXXDestructorName:
2888         InvalidDecl = 5;
2889         ShowDeclName = false;
2890         break;
2891 
2892       case DeclarationName::CXXOperatorName:
2893       case DeclarationName::CXXConversionFunctionName:
2894         InvalidDecl = 6;
2895         break;
2896 
2897       default:
2898         InvalidDecl = 0;
2899         break;
2900     }
2901 
2902     if (InvalidDecl) {
2903       if (ShowDeclName)
2904         Diag(Loc, diag::err_invalid_member_in_interface)
2905           << (InvalidDecl-1) << Name;
2906       else
2907         Diag(Loc, diag::err_invalid_member_in_interface)
2908           << (InvalidDecl-1) << "";
2909       return nullptr;
2910     }
2911   }
2912 
2913   // C++ 9.2p6: A member shall not be declared to have automatic storage
2914   // duration (auto, register) or with the extern storage-class-specifier.
2915   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2916   // data members and cannot be applied to names declared const or static,
2917   // and cannot be applied to reference members.
2918   switch (DS.getStorageClassSpec()) {
2919   case DeclSpec::SCS_unspecified:
2920   case DeclSpec::SCS_typedef:
2921   case DeclSpec::SCS_static:
2922     break;
2923   case DeclSpec::SCS_mutable:
2924     if (isFunc) {
2925       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2926 
2927       // FIXME: It would be nicer if the keyword was ignored only for this
2928       // declarator. Otherwise we could get follow-up errors.
2929       D.getMutableDeclSpec().ClearStorageClassSpecs();
2930     }
2931     break;
2932   default:
2933     Diag(DS.getStorageClassSpecLoc(),
2934          diag::err_storageclass_invalid_for_member);
2935     D.getMutableDeclSpec().ClearStorageClassSpecs();
2936     break;
2937   }
2938 
2939   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2940                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2941                       !isFunc);
2942 
2943   if (DS.isConstexprSpecified() && isInstField) {
2944     SemaDiagnosticBuilder B =
2945         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2946     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2947     if (InitStyle == ICIS_NoInit) {
2948       B << 0 << 0;
2949       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2950         B << FixItHint::CreateRemoval(ConstexprLoc);
2951       else {
2952         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2953         D.getMutableDeclSpec().ClearConstexprSpec();
2954         const char *PrevSpec;
2955         unsigned DiagID;
2956         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2957             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2958         (void)Failed;
2959         assert(!Failed && "Making a constexpr member const shouldn't fail");
2960       }
2961     } else {
2962       B << 1;
2963       const char *PrevSpec;
2964       unsigned DiagID;
2965       if (D.getMutableDeclSpec().SetStorageClassSpec(
2966           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2967           Context.getPrintingPolicy())) {
2968         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2969                "This is the only DeclSpec that should fail to be applied");
2970         B << 1;
2971       } else {
2972         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2973         isInstField = false;
2974       }
2975     }
2976   }
2977 
2978   NamedDecl *Member;
2979   if (isInstField) {
2980     CXXScopeSpec &SS = D.getCXXScopeSpec();
2981 
2982     // Data members must have identifiers for names.
2983     if (!Name.isIdentifier()) {
2984       Diag(Loc, diag::err_bad_variable_name)
2985         << Name;
2986       return nullptr;
2987     }
2988 
2989     IdentifierInfo *II = Name.getAsIdentifierInfo();
2990 
2991     // Member field could not be with "template" keyword.
2992     // So TemplateParameterLists should be empty in this case.
2993     if (TemplateParameterLists.size()) {
2994       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2995       if (TemplateParams->size()) {
2996         // There is no such thing as a member field template.
2997         Diag(D.getIdentifierLoc(), diag::err_template_member)
2998             << II
2999             << SourceRange(TemplateParams->getTemplateLoc(),
3000                 TemplateParams->getRAngleLoc());
3001       } else {
3002         // There is an extraneous 'template<>' for this member.
3003         Diag(TemplateParams->getTemplateLoc(),
3004             diag::err_template_member_noparams)
3005             << II
3006             << SourceRange(TemplateParams->getTemplateLoc(),
3007                 TemplateParams->getRAngleLoc());
3008       }
3009       return nullptr;
3010     }
3011 
3012     if (SS.isSet() && !SS.isInvalid()) {
3013       // The user provided a superfluous scope specifier inside a class
3014       // definition:
3015       //
3016       // class X {
3017       //   int X::member;
3018       // };
3019       if (DeclContext *DC = computeDeclContext(SS, false))
3020         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
3021       else
3022         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3023           << Name << SS.getRange();
3024 
3025       SS.clear();
3026     }
3027 
3028     if (MSPropertyAttr) {
3029       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3030                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3031       if (!Member)
3032         return nullptr;
3033       isInstField = false;
3034     } else {
3035       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3036                                 BitWidth, InitStyle, AS);
3037       if (!Member)
3038         return nullptr;
3039     }
3040 
3041     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3042   } else {
3043     Member = HandleDeclarator(S, D, TemplateParameterLists);
3044     if (!Member)
3045       return nullptr;
3046 
3047     // Non-instance-fields can't have a bitfield.
3048     if (BitWidth) {
3049       if (Member->isInvalidDecl()) {
3050         // don't emit another diagnostic.
3051       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3052         // C++ 9.6p3: A bit-field shall not be a static member.
3053         // "static member 'A' cannot be a bit-field"
3054         Diag(Loc, diag::err_static_not_bitfield)
3055           << Name << BitWidth->getSourceRange();
3056       } else if (isa<TypedefDecl>(Member)) {
3057         // "typedef member 'x' cannot be a bit-field"
3058         Diag(Loc, diag::err_typedef_not_bitfield)
3059           << Name << BitWidth->getSourceRange();
3060       } else {
3061         // A function typedef ("typedef int f(); f a;").
3062         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3063         Diag(Loc, diag::err_not_integral_type_bitfield)
3064           << Name << cast<ValueDecl>(Member)->getType()
3065           << BitWidth->getSourceRange();
3066       }
3067 
3068       BitWidth = nullptr;
3069       Member->setInvalidDecl();
3070     }
3071 
3072     Member->setAccess(AS);
3073 
3074     // If we have declared a member function template or static data member
3075     // template, set the access of the templated declaration as well.
3076     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3077       FunTmpl->getTemplatedDecl()->setAccess(AS);
3078     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3079       VarTmpl->getTemplatedDecl()->setAccess(AS);
3080   }
3081 
3082   if (VS.isOverrideSpecified())
3083     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3084   if (VS.isFinalSpecified())
3085     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3086                                             VS.isFinalSpelledSealed()));
3087 
3088   if (VS.getLastLocation().isValid()) {
3089     // Update the end location of a method that has a virt-specifiers.
3090     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3091       MD->setRangeEnd(VS.getLastLocation());
3092   }
3093 
3094   CheckOverrideControl(Member);
3095 
3096   assert((Name || isInstField) && "No identifier for non-field ?");
3097 
3098   if (isInstField) {
3099     FieldDecl *FD = cast<FieldDecl>(Member);
3100     FieldCollector->Add(FD);
3101 
3102     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3103       // Remember all explicit private FieldDecls that have a name, no side
3104       // effects and are not part of a dependent type declaration.
3105       if (!FD->isImplicit() && FD->getDeclName() &&
3106           FD->getAccess() == AS_private &&
3107           !FD->hasAttr<UnusedAttr>() &&
3108           !FD->getParent()->isDependentContext() &&
3109           !InitializationHasSideEffects(*FD))
3110         UnusedPrivateFields.insert(FD);
3111     }
3112   }
3113 
3114   return Member;
3115 }
3116 
3117 namespace {
3118   class UninitializedFieldVisitor
3119       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3120     Sema &S;
3121     // List of Decls to generate a warning on.  Also remove Decls that become
3122     // initialized.
3123     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3124     // List of base classes of the record.  Classes are removed after their
3125     // initializers.
3126     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3127     // Vector of decls to be removed from the Decl set prior to visiting the
3128     // nodes.  These Decls may have been initialized in the prior initializer.
3129     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3130     // If non-null, add a note to the warning pointing back to the constructor.
3131     const CXXConstructorDecl *Constructor;
3132     // Variables to hold state when processing an initializer list.  When
3133     // InitList is true, special case initialization of FieldDecls matching
3134     // InitListFieldDecl.
3135     bool InitList;
3136     FieldDecl *InitListFieldDecl;
3137     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3138 
3139   public:
3140     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3141     UninitializedFieldVisitor(Sema &S,
3142                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3143                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3144       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3145         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3146 
3147     // Returns true if the use of ME is not an uninitialized use.
3148     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3149                                          bool CheckReferenceOnly) {
3150       llvm::SmallVector<FieldDecl*, 4> Fields;
3151       bool ReferenceField = false;
3152       while (ME) {
3153         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3154         if (!FD)
3155           return false;
3156         Fields.push_back(FD);
3157         if (FD->getType()->isReferenceType())
3158           ReferenceField = true;
3159         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3160       }
3161 
3162       // Binding a reference to an unintialized field is not an
3163       // uninitialized use.
3164       if (CheckReferenceOnly && !ReferenceField)
3165         return true;
3166 
3167       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3168       // Discard the first field since it is the field decl that is being
3169       // initialized.
3170       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3171         UsedFieldIndex.push_back((*I)->getFieldIndex());
3172       }
3173 
3174       for (auto UsedIter = UsedFieldIndex.begin(),
3175                 UsedEnd = UsedFieldIndex.end(),
3176                 OrigIter = InitFieldIndex.begin(),
3177                 OrigEnd = InitFieldIndex.end();
3178            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3179         if (*UsedIter < *OrigIter)
3180           return true;
3181         if (*UsedIter > *OrigIter)
3182           break;
3183       }
3184 
3185       return false;
3186     }
3187 
3188     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3189                           bool AddressOf) {
3190       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3191         return;
3192 
3193       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3194       // or union.
3195       MemberExpr *FieldME = ME;
3196 
3197       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3198 
3199       Expr *Base = ME;
3200       while (MemberExpr *SubME =
3201                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3202 
3203         if (isa<VarDecl>(SubME->getMemberDecl()))
3204           return;
3205 
3206         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3207           if (!FD->isAnonymousStructOrUnion())
3208             FieldME = SubME;
3209 
3210         if (!FieldME->getType().isPODType(S.Context))
3211           AllPODFields = false;
3212 
3213         Base = SubME->getBase();
3214       }
3215 
3216       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3217         return;
3218 
3219       if (AddressOf && AllPODFields)
3220         return;
3221 
3222       ValueDecl* FoundVD = FieldME->getMemberDecl();
3223 
3224       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3225         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3226           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3227         }
3228 
3229         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3230           QualType T = BaseCast->getType();
3231           if (T->isPointerType() &&
3232               BaseClasses.count(T->getPointeeType())) {
3233             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3234                 << T->getPointeeType() << FoundVD;
3235           }
3236         }
3237       }
3238 
3239       if (!Decls.count(FoundVD))
3240         return;
3241 
3242       const bool IsReference = FoundVD->getType()->isReferenceType();
3243 
3244       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3245         // Special checking for initializer lists.
3246         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3247           return;
3248         }
3249       } else {
3250         // Prevent double warnings on use of unbounded references.
3251         if (CheckReferenceOnly && !IsReference)
3252           return;
3253       }
3254 
3255       unsigned diag = IsReference
3256           ? diag::warn_reference_field_is_uninit
3257           : diag::warn_field_is_uninit;
3258       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3259       if (Constructor)
3260         S.Diag(Constructor->getLocation(),
3261                diag::note_uninit_in_this_constructor)
3262           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3263 
3264     }
3265 
3266     void HandleValue(Expr *E, bool AddressOf) {
3267       E = E->IgnoreParens();
3268 
3269       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3270         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3271                          AddressOf /*AddressOf*/);
3272         return;
3273       }
3274 
3275       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3276         Visit(CO->getCond());
3277         HandleValue(CO->getTrueExpr(), AddressOf);
3278         HandleValue(CO->getFalseExpr(), AddressOf);
3279         return;
3280       }
3281 
3282       if (BinaryConditionalOperator *BCO =
3283               dyn_cast<BinaryConditionalOperator>(E)) {
3284         Visit(BCO->getCond());
3285         HandleValue(BCO->getFalseExpr(), AddressOf);
3286         return;
3287       }
3288 
3289       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3290         HandleValue(OVE->getSourceExpr(), AddressOf);
3291         return;
3292       }
3293 
3294       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3295         switch (BO->getOpcode()) {
3296         default:
3297           break;
3298         case(BO_PtrMemD):
3299         case(BO_PtrMemI):
3300           HandleValue(BO->getLHS(), AddressOf);
3301           Visit(BO->getRHS());
3302           return;
3303         case(BO_Comma):
3304           Visit(BO->getLHS());
3305           HandleValue(BO->getRHS(), AddressOf);
3306           return;
3307         }
3308       }
3309 
3310       Visit(E);
3311     }
3312 
3313     void CheckInitListExpr(InitListExpr *ILE) {
3314       InitFieldIndex.push_back(0);
3315       for (auto Child : ILE->children()) {
3316         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3317           CheckInitListExpr(SubList);
3318         } else {
3319           Visit(Child);
3320         }
3321         ++InitFieldIndex.back();
3322       }
3323       InitFieldIndex.pop_back();
3324     }
3325 
3326     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3327                           FieldDecl *Field, const Type *BaseClass) {
3328       // Remove Decls that may have been initialized in the previous
3329       // initializer.
3330       for (ValueDecl* VD : DeclsToRemove)
3331         Decls.erase(VD);
3332       DeclsToRemove.clear();
3333 
3334       Constructor = FieldConstructor;
3335       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3336 
3337       if (ILE && Field) {
3338         InitList = true;
3339         InitListFieldDecl = Field;
3340         InitFieldIndex.clear();
3341         CheckInitListExpr(ILE);
3342       } else {
3343         InitList = false;
3344         Visit(E);
3345       }
3346 
3347       if (Field)
3348         Decls.erase(Field);
3349       if (BaseClass)
3350         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3351     }
3352 
3353     void VisitMemberExpr(MemberExpr *ME) {
3354       // All uses of unbounded reference fields will warn.
3355       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3356     }
3357 
3358     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3359       if (E->getCastKind() == CK_LValueToRValue) {
3360         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3361         return;
3362       }
3363 
3364       Inherited::VisitImplicitCastExpr(E);
3365     }
3366 
3367     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3368       if (E->getConstructor()->isCopyConstructor()) {
3369         Expr *ArgExpr = E->getArg(0);
3370         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3371           if (ILE->getNumInits() == 1)
3372             ArgExpr = ILE->getInit(0);
3373         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3374           if (ICE->getCastKind() == CK_NoOp)
3375             ArgExpr = ICE->getSubExpr();
3376         HandleValue(ArgExpr, false /*AddressOf*/);
3377         return;
3378       }
3379       Inherited::VisitCXXConstructExpr(E);
3380     }
3381 
3382     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3383       Expr *Callee = E->getCallee();
3384       if (isa<MemberExpr>(Callee)) {
3385         HandleValue(Callee, false /*AddressOf*/);
3386         for (auto Arg : E->arguments())
3387           Visit(Arg);
3388         return;
3389       }
3390 
3391       Inherited::VisitCXXMemberCallExpr(E);
3392     }
3393 
3394     void VisitCallExpr(CallExpr *E) {
3395       // Treat std::move as a use.
3396       if (E->isCallToStdMove()) {
3397         HandleValue(E->getArg(0), /*AddressOf=*/false);
3398         return;
3399       }
3400 
3401       Inherited::VisitCallExpr(E);
3402     }
3403 
3404     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3405       Expr *Callee = E->getCallee();
3406 
3407       if (isa<UnresolvedLookupExpr>(Callee))
3408         return Inherited::VisitCXXOperatorCallExpr(E);
3409 
3410       Visit(Callee);
3411       for (auto Arg : E->arguments())
3412         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3413     }
3414 
3415     void VisitBinaryOperator(BinaryOperator *E) {
3416       // If a field assignment is detected, remove the field from the
3417       // uninitiailized field set.
3418       if (E->getOpcode() == BO_Assign)
3419         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3420           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3421             if (!FD->getType()->isReferenceType())
3422               DeclsToRemove.push_back(FD);
3423 
3424       if (E->isCompoundAssignmentOp()) {
3425         HandleValue(E->getLHS(), false /*AddressOf*/);
3426         Visit(E->getRHS());
3427         return;
3428       }
3429 
3430       Inherited::VisitBinaryOperator(E);
3431     }
3432 
3433     void VisitUnaryOperator(UnaryOperator *E) {
3434       if (E->isIncrementDecrementOp()) {
3435         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3436         return;
3437       }
3438       if (E->getOpcode() == UO_AddrOf) {
3439         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3440           HandleValue(ME->getBase(), true /*AddressOf*/);
3441           return;
3442         }
3443       }
3444 
3445       Inherited::VisitUnaryOperator(E);
3446     }
3447   };
3448 
3449   // Diagnose value-uses of fields to initialize themselves, e.g.
3450   //   foo(foo)
3451   // where foo is not also a parameter to the constructor.
3452   // Also diagnose across field uninitialized use such as
3453   //   x(y), y(x)
3454   // TODO: implement -Wuninitialized and fold this into that framework.
3455   static void DiagnoseUninitializedFields(
3456       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3457 
3458     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3459                                            Constructor->getLocation())) {
3460       return;
3461     }
3462 
3463     if (Constructor->isInvalidDecl())
3464       return;
3465 
3466     const CXXRecordDecl *RD = Constructor->getParent();
3467 
3468     if (RD->getDescribedClassTemplate())
3469       return;
3470 
3471     // Holds fields that are uninitialized.
3472     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3473 
3474     // At the beginning, all fields are uninitialized.
3475     for (auto *I : RD->decls()) {
3476       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3477         UninitializedFields.insert(FD);
3478       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3479         UninitializedFields.insert(IFD->getAnonField());
3480       }
3481     }
3482 
3483     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3484     for (auto I : RD->bases())
3485       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3486 
3487     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3488       return;
3489 
3490     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3491                                                    UninitializedFields,
3492                                                    UninitializedBaseClasses);
3493 
3494     for (const auto *FieldInit : Constructor->inits()) {
3495       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3496         break;
3497 
3498       Expr *InitExpr = FieldInit->getInit();
3499       if (!InitExpr)
3500         continue;
3501 
3502       if (CXXDefaultInitExpr *Default =
3503               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3504         InitExpr = Default->getExpr();
3505         if (!InitExpr)
3506           continue;
3507         // In class initializers will point to the constructor.
3508         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3509                                               FieldInit->getAnyMember(),
3510                                               FieldInit->getBaseClass());
3511       } else {
3512         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3513                                               FieldInit->getAnyMember(),
3514                                               FieldInit->getBaseClass());
3515       }
3516     }
3517   }
3518 } // namespace
3519 
3520 /// \brief Enter a new C++ default initializer scope. After calling this, the
3521 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3522 /// parsing or instantiating the initializer failed.
3523 void Sema::ActOnStartCXXInClassMemberInitializer() {
3524   // Create a synthetic function scope to represent the call to the constructor
3525   // that notionally surrounds a use of this initializer.
3526   PushFunctionScope();
3527 }
3528 
3529 /// \brief This is invoked after parsing an in-class initializer for a
3530 /// non-static C++ class member, and after instantiating an in-class initializer
3531 /// in a class template. Such actions are deferred until the class is complete.
3532 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3533                                                   SourceLocation InitLoc,
3534                                                   Expr *InitExpr) {
3535   // Pop the notional constructor scope we created earlier.
3536   PopFunctionScopeInfo(nullptr, D);
3537 
3538   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3539   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3540          "must set init style when field is created");
3541 
3542   if (!InitExpr) {
3543     D->setInvalidDecl();
3544     if (FD)
3545       FD->removeInClassInitializer();
3546     return;
3547   }
3548 
3549   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3550     FD->setInvalidDecl();
3551     FD->removeInClassInitializer();
3552     return;
3553   }
3554 
3555   ExprResult Init = InitExpr;
3556   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3557     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3558     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3559         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3560         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3561     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3562     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3563     if (Init.isInvalid()) {
3564       FD->setInvalidDecl();
3565       return;
3566     }
3567   }
3568 
3569   // C++11 [class.base.init]p7:
3570   //   The initialization of each base and member constitutes a
3571   //   full-expression.
3572   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3573   if (Init.isInvalid()) {
3574     FD->setInvalidDecl();
3575     return;
3576   }
3577 
3578   InitExpr = Init.get();
3579 
3580   FD->setInClassInitializer(InitExpr);
3581 }
3582 
3583 /// \brief Find the direct and/or virtual base specifiers that
3584 /// correspond to the given base type, for use in base initialization
3585 /// within a constructor.
3586 static bool FindBaseInitializer(Sema &SemaRef,
3587                                 CXXRecordDecl *ClassDecl,
3588                                 QualType BaseType,
3589                                 const CXXBaseSpecifier *&DirectBaseSpec,
3590                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3591   // First, check for a direct base class.
3592   DirectBaseSpec = nullptr;
3593   for (const auto &Base : ClassDecl->bases()) {
3594     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3595       // We found a direct base of this type. That's what we're
3596       // initializing.
3597       DirectBaseSpec = &Base;
3598       break;
3599     }
3600   }
3601 
3602   // Check for a virtual base class.
3603   // FIXME: We might be able to short-circuit this if we know in advance that
3604   // there are no virtual bases.
3605   VirtualBaseSpec = nullptr;
3606   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3607     // We haven't found a base yet; search the class hierarchy for a
3608     // virtual base class.
3609     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3610                        /*DetectVirtual=*/false);
3611     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3612                               SemaRef.Context.getTypeDeclType(ClassDecl),
3613                               BaseType, Paths)) {
3614       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3615            Path != Paths.end(); ++Path) {
3616         if (Path->back().Base->isVirtual()) {
3617           VirtualBaseSpec = Path->back().Base;
3618           break;
3619         }
3620       }
3621     }
3622   }
3623 
3624   return DirectBaseSpec || VirtualBaseSpec;
3625 }
3626 
3627 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3628 MemInitResult
3629 Sema::ActOnMemInitializer(Decl *ConstructorD,
3630                           Scope *S,
3631                           CXXScopeSpec &SS,
3632                           IdentifierInfo *MemberOrBase,
3633                           ParsedType TemplateTypeTy,
3634                           const DeclSpec &DS,
3635                           SourceLocation IdLoc,
3636                           Expr *InitList,
3637                           SourceLocation EllipsisLoc) {
3638   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3639                              DS, IdLoc, InitList,
3640                              EllipsisLoc);
3641 }
3642 
3643 /// \brief Handle a C++ member initializer using parentheses syntax.
3644 MemInitResult
3645 Sema::ActOnMemInitializer(Decl *ConstructorD,
3646                           Scope *S,
3647                           CXXScopeSpec &SS,
3648                           IdentifierInfo *MemberOrBase,
3649                           ParsedType TemplateTypeTy,
3650                           const DeclSpec &DS,
3651                           SourceLocation IdLoc,
3652                           SourceLocation LParenLoc,
3653                           ArrayRef<Expr *> Args,
3654                           SourceLocation RParenLoc,
3655                           SourceLocation EllipsisLoc) {
3656   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3657                                            Args, RParenLoc);
3658   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3659                              DS, IdLoc, List, EllipsisLoc);
3660 }
3661 
3662 namespace {
3663 
3664 // Callback to only accept typo corrections that can be a valid C++ member
3665 // intializer: either a non-static field member or a base class.
3666 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3667 public:
3668   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3669       : ClassDecl(ClassDecl) {}
3670 
3671   bool ValidateCandidate(const TypoCorrection &candidate) override {
3672     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3673       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3674         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3675       return isa<TypeDecl>(ND);
3676     }
3677     return false;
3678   }
3679 
3680 private:
3681   CXXRecordDecl *ClassDecl;
3682 };
3683 
3684 }
3685 
3686 /// \brief Handle a C++ member initializer.
3687 MemInitResult
3688 Sema::BuildMemInitializer(Decl *ConstructorD,
3689                           Scope *S,
3690                           CXXScopeSpec &SS,
3691                           IdentifierInfo *MemberOrBase,
3692                           ParsedType TemplateTypeTy,
3693                           const DeclSpec &DS,
3694                           SourceLocation IdLoc,
3695                           Expr *Init,
3696                           SourceLocation EllipsisLoc) {
3697   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3698   if (!Res.isUsable())
3699     return true;
3700   Init = Res.get();
3701 
3702   if (!ConstructorD)
3703     return true;
3704 
3705   AdjustDeclIfTemplate(ConstructorD);
3706 
3707   CXXConstructorDecl *Constructor
3708     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3709   if (!Constructor) {
3710     // The user wrote a constructor initializer on a function that is
3711     // not a C++ constructor. Ignore the error for now, because we may
3712     // have more member initializers coming; we'll diagnose it just
3713     // once in ActOnMemInitializers.
3714     return true;
3715   }
3716 
3717   CXXRecordDecl *ClassDecl = Constructor->getParent();
3718 
3719   // C++ [class.base.init]p2:
3720   //   Names in a mem-initializer-id are looked up in the scope of the
3721   //   constructor's class and, if not found in that scope, are looked
3722   //   up in the scope containing the constructor's definition.
3723   //   [Note: if the constructor's class contains a member with the
3724   //   same name as a direct or virtual base class of the class, a
3725   //   mem-initializer-id naming the member or base class and composed
3726   //   of a single identifier refers to the class member. A
3727   //   mem-initializer-id for the hidden base class may be specified
3728   //   using a qualified name. ]
3729   if (!SS.getScopeRep() && !TemplateTypeTy) {
3730     // Look for a member, first.
3731     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3732     if (!Result.empty()) {
3733       ValueDecl *Member;
3734       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3735           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3736         if (EllipsisLoc.isValid())
3737           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3738             << MemberOrBase
3739             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3740 
3741         return BuildMemberInitializer(Member, Init, IdLoc);
3742       }
3743     }
3744   }
3745   // It didn't name a member, so see if it names a class.
3746   QualType BaseType;
3747   TypeSourceInfo *TInfo = nullptr;
3748 
3749   if (TemplateTypeTy) {
3750     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3751   } else if (DS.getTypeSpecType() == TST_decltype) {
3752     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3753   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3754     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3755     return true;
3756   } else {
3757     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3758     LookupParsedName(R, S, &SS);
3759 
3760     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3761     if (!TyD) {
3762       if (R.isAmbiguous()) return true;
3763 
3764       // We don't want access-control diagnostics here.
3765       R.suppressDiagnostics();
3766 
3767       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3768         bool NotUnknownSpecialization = false;
3769         DeclContext *DC = computeDeclContext(SS, false);
3770         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3771           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3772 
3773         if (!NotUnknownSpecialization) {
3774           // When the scope specifier can refer to a member of an unknown
3775           // specialization, we take it as a type name.
3776           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3777                                        SS.getWithLocInContext(Context),
3778                                        *MemberOrBase, IdLoc);
3779           if (BaseType.isNull())
3780             return true;
3781 
3782           TInfo = Context.CreateTypeSourceInfo(BaseType);
3783           DependentNameTypeLoc TL =
3784               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3785           if (!TL.isNull()) {
3786             TL.setNameLoc(IdLoc);
3787             TL.setElaboratedKeywordLoc(SourceLocation());
3788             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3789           }
3790 
3791           R.clear();
3792           R.setLookupName(MemberOrBase);
3793         }
3794       }
3795 
3796       // If no results were found, try to correct typos.
3797       TypoCorrection Corr;
3798       if (R.empty() && BaseType.isNull() &&
3799           (Corr = CorrectTypo(
3800                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3801                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3802                CTK_ErrorRecovery, ClassDecl))) {
3803         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3804           // We have found a non-static data member with a similar
3805           // name to what was typed; complain and initialize that
3806           // member.
3807           diagnoseTypo(Corr,
3808                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3809                          << MemberOrBase << true);
3810           return BuildMemberInitializer(Member, Init, IdLoc);
3811         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3812           const CXXBaseSpecifier *DirectBaseSpec;
3813           const CXXBaseSpecifier *VirtualBaseSpec;
3814           if (FindBaseInitializer(*this, ClassDecl,
3815                                   Context.getTypeDeclType(Type),
3816                                   DirectBaseSpec, VirtualBaseSpec)) {
3817             // We have found a direct or virtual base class with a
3818             // similar name to what was typed; complain and initialize
3819             // that base class.
3820             diagnoseTypo(Corr,
3821                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3822                            << MemberOrBase << false,
3823                          PDiag() /*Suppress note, we provide our own.*/);
3824 
3825             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3826                                                               : VirtualBaseSpec;
3827             Diag(BaseSpec->getLocStart(),
3828                  diag::note_base_class_specified_here)
3829               << BaseSpec->getType()
3830               << BaseSpec->getSourceRange();
3831 
3832             TyD = Type;
3833           }
3834         }
3835       }
3836 
3837       if (!TyD && BaseType.isNull()) {
3838         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3839           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3840         return true;
3841       }
3842     }
3843 
3844     if (BaseType.isNull()) {
3845       BaseType = Context.getTypeDeclType(TyD);
3846       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3847       if (SS.isSet()) {
3848         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3849                                              BaseType);
3850         TInfo = Context.CreateTypeSourceInfo(BaseType);
3851         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3852         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3853         TL.setElaboratedKeywordLoc(SourceLocation());
3854         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3855       }
3856     }
3857   }
3858 
3859   if (!TInfo)
3860     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3861 
3862   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3863 }
3864 
3865 /// Checks a member initializer expression for cases where reference (or
3866 /// pointer) members are bound to by-value parameters (or their addresses).
3867 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3868                                                Expr *Init,
3869                                                SourceLocation IdLoc) {
3870   QualType MemberTy = Member->getType();
3871 
3872   // We only handle pointers and references currently.
3873   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3874   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3875     return;
3876 
3877   const bool IsPointer = MemberTy->isPointerType();
3878   if (IsPointer) {
3879     if (const UnaryOperator *Op
3880           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3881       // The only case we're worried about with pointers requires taking the
3882       // address.
3883       if (Op->getOpcode() != UO_AddrOf)
3884         return;
3885 
3886       Init = Op->getSubExpr();
3887     } else {
3888       // We only handle address-of expression initializers for pointers.
3889       return;
3890     }
3891   }
3892 
3893   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3894     // We only warn when referring to a non-reference parameter declaration.
3895     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3896     if (!Parameter || Parameter->getType()->isReferenceType())
3897       return;
3898 
3899     S.Diag(Init->getExprLoc(),
3900            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3901                      : diag::warn_bind_ref_member_to_parameter)
3902       << Member << Parameter << Init->getSourceRange();
3903   } else {
3904     // Other initializers are fine.
3905     return;
3906   }
3907 
3908   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3909     << (unsigned)IsPointer;
3910 }
3911 
3912 MemInitResult
3913 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3914                              SourceLocation IdLoc) {
3915   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3916   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3917   assert((DirectMember || IndirectMember) &&
3918          "Member must be a FieldDecl or IndirectFieldDecl");
3919 
3920   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3921     return true;
3922 
3923   if (Member->isInvalidDecl())
3924     return true;
3925 
3926   MultiExprArg Args;
3927   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3928     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3929   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3930     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3931   } else {
3932     // Template instantiation doesn't reconstruct ParenListExprs for us.
3933     Args = Init;
3934   }
3935 
3936   SourceRange InitRange = Init->getSourceRange();
3937 
3938   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3939     // Can't check initialization for a member of dependent type or when
3940     // any of the arguments are type-dependent expressions.
3941     DiscardCleanupsInEvaluationContext();
3942   } else {
3943     bool InitList = false;
3944     if (isa<InitListExpr>(Init)) {
3945       InitList = true;
3946       Args = Init;
3947     }
3948 
3949     // Initialize the member.
3950     InitializedEntity MemberEntity =
3951       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3952                    : InitializedEntity::InitializeMember(IndirectMember,
3953                                                          nullptr);
3954     InitializationKind Kind =
3955       InitList ? InitializationKind::CreateDirectList(IdLoc)
3956                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3957                                                   InitRange.getEnd());
3958 
3959     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3960     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3961                                             nullptr);
3962     if (MemberInit.isInvalid())
3963       return true;
3964 
3965     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3966 
3967     // C++11 [class.base.init]p7:
3968     //   The initialization of each base and member constitutes a
3969     //   full-expression.
3970     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3971     if (MemberInit.isInvalid())
3972       return true;
3973 
3974     Init = MemberInit.get();
3975   }
3976 
3977   if (DirectMember) {
3978     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3979                                             InitRange.getBegin(), Init,
3980                                             InitRange.getEnd());
3981   } else {
3982     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3983                                             InitRange.getBegin(), Init,
3984                                             InitRange.getEnd());
3985   }
3986 }
3987 
3988 MemInitResult
3989 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3990                                  CXXRecordDecl *ClassDecl) {
3991   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3992   if (!LangOpts.CPlusPlus11)
3993     return Diag(NameLoc, diag::err_delegating_ctor)
3994       << TInfo->getTypeLoc().getLocalSourceRange();
3995   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3996 
3997   bool InitList = true;
3998   MultiExprArg Args = Init;
3999   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4000     InitList = false;
4001     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4002   }
4003 
4004   SourceRange InitRange = Init->getSourceRange();
4005   // Initialize the object.
4006   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4007                                      QualType(ClassDecl->getTypeForDecl(), 0));
4008   InitializationKind Kind =
4009     InitList ? InitializationKind::CreateDirectList(NameLoc)
4010              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4011                                                 InitRange.getEnd());
4012   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4013   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4014                                               Args, nullptr);
4015   if (DelegationInit.isInvalid())
4016     return true;
4017 
4018   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4019          "Delegating constructor with no target?");
4020 
4021   // C++11 [class.base.init]p7:
4022   //   The initialization of each base and member constitutes a
4023   //   full-expression.
4024   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4025                                        InitRange.getBegin());
4026   if (DelegationInit.isInvalid())
4027     return true;
4028 
4029   // If we are in a dependent context, template instantiation will
4030   // perform this type-checking again. Just save the arguments that we
4031   // received in a ParenListExpr.
4032   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4033   // of the information that we have about the base
4034   // initializer. However, deconstructing the ASTs is a dicey process,
4035   // and this approach is far more likely to get the corner cases right.
4036   if (CurContext->isDependentContext())
4037     DelegationInit = Init;
4038 
4039   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4040                                           DelegationInit.getAs<Expr>(),
4041                                           InitRange.getEnd());
4042 }
4043 
4044 MemInitResult
4045 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4046                            Expr *Init, CXXRecordDecl *ClassDecl,
4047                            SourceLocation EllipsisLoc) {
4048   SourceLocation BaseLoc
4049     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4050 
4051   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4052     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4053              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4054 
4055   // C++ [class.base.init]p2:
4056   //   [...] Unless the mem-initializer-id names a nonstatic data
4057   //   member of the constructor's class or a direct or virtual base
4058   //   of that class, the mem-initializer is ill-formed. A
4059   //   mem-initializer-list can initialize a base class using any
4060   //   name that denotes that base class type.
4061   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4062 
4063   SourceRange InitRange = Init->getSourceRange();
4064   if (EllipsisLoc.isValid()) {
4065     // This is a pack expansion.
4066     if (!BaseType->containsUnexpandedParameterPack())  {
4067       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4068         << SourceRange(BaseLoc, InitRange.getEnd());
4069 
4070       EllipsisLoc = SourceLocation();
4071     }
4072   } else {
4073     // Check for any unexpanded parameter packs.
4074     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4075       return true;
4076 
4077     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4078       return true;
4079   }
4080 
4081   // Check for direct and virtual base classes.
4082   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4083   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4084   if (!Dependent) {
4085     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4086                                        BaseType))
4087       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4088 
4089     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4090                         VirtualBaseSpec);
4091 
4092     // C++ [base.class.init]p2:
4093     // Unless the mem-initializer-id names a nonstatic data member of the
4094     // constructor's class or a direct or virtual base of that class, the
4095     // mem-initializer is ill-formed.
4096     if (!DirectBaseSpec && !VirtualBaseSpec) {
4097       // If the class has any dependent bases, then it's possible that
4098       // one of those types will resolve to the same type as
4099       // BaseType. Therefore, just treat this as a dependent base
4100       // class initialization.  FIXME: Should we try to check the
4101       // initialization anyway? It seems odd.
4102       if (ClassDecl->hasAnyDependentBases())
4103         Dependent = true;
4104       else
4105         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4106           << BaseType << Context.getTypeDeclType(ClassDecl)
4107           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4108     }
4109   }
4110 
4111   if (Dependent) {
4112     DiscardCleanupsInEvaluationContext();
4113 
4114     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4115                                             /*IsVirtual=*/false,
4116                                             InitRange.getBegin(), Init,
4117                                             InitRange.getEnd(), EllipsisLoc);
4118   }
4119 
4120   // C++ [base.class.init]p2:
4121   //   If a mem-initializer-id is ambiguous because it designates both
4122   //   a direct non-virtual base class and an inherited virtual base
4123   //   class, the mem-initializer is ill-formed.
4124   if (DirectBaseSpec && VirtualBaseSpec)
4125     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4126       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4127 
4128   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4129   if (!BaseSpec)
4130     BaseSpec = VirtualBaseSpec;
4131 
4132   // Initialize the base.
4133   bool InitList = true;
4134   MultiExprArg Args = Init;
4135   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4136     InitList = false;
4137     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4138   }
4139 
4140   InitializedEntity BaseEntity =
4141     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4142   InitializationKind Kind =
4143     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4144              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4145                                                 InitRange.getEnd());
4146   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4147   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4148   if (BaseInit.isInvalid())
4149     return true;
4150 
4151   // C++11 [class.base.init]p7:
4152   //   The initialization of each base and member constitutes a
4153   //   full-expression.
4154   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4155   if (BaseInit.isInvalid())
4156     return true;
4157 
4158   // If we are in a dependent context, template instantiation will
4159   // perform this type-checking again. Just save the arguments that we
4160   // received in a ParenListExpr.
4161   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4162   // of the information that we have about the base
4163   // initializer. However, deconstructing the ASTs is a dicey process,
4164   // and this approach is far more likely to get the corner cases right.
4165   if (CurContext->isDependentContext())
4166     BaseInit = Init;
4167 
4168   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4169                                           BaseSpec->isVirtual(),
4170                                           InitRange.getBegin(),
4171                                           BaseInit.getAs<Expr>(),
4172                                           InitRange.getEnd(), EllipsisLoc);
4173 }
4174 
4175 // Create a static_cast\<T&&>(expr).
4176 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4177   if (T.isNull()) T = E->getType();
4178   QualType TargetType = SemaRef.BuildReferenceType(
4179       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4180   SourceLocation ExprLoc = E->getLocStart();
4181   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4182       TargetType, ExprLoc);
4183 
4184   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4185                                    SourceRange(ExprLoc, ExprLoc),
4186                                    E->getSourceRange()).get();
4187 }
4188 
4189 /// ImplicitInitializerKind - How an implicit base or member initializer should
4190 /// initialize its base or member.
4191 enum ImplicitInitializerKind {
4192   IIK_Default,
4193   IIK_Copy,
4194   IIK_Move,
4195   IIK_Inherit
4196 };
4197 
4198 static bool
4199 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4200                              ImplicitInitializerKind ImplicitInitKind,
4201                              CXXBaseSpecifier *BaseSpec,
4202                              bool IsInheritedVirtualBase,
4203                              CXXCtorInitializer *&CXXBaseInit) {
4204   InitializedEntity InitEntity
4205     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4206                                         IsInheritedVirtualBase);
4207 
4208   ExprResult BaseInit;
4209 
4210   switch (ImplicitInitKind) {
4211   case IIK_Inherit:
4212   case IIK_Default: {
4213     InitializationKind InitKind
4214       = InitializationKind::CreateDefault(Constructor->getLocation());
4215     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4216     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4217     break;
4218   }
4219 
4220   case IIK_Move:
4221   case IIK_Copy: {
4222     bool Moving = ImplicitInitKind == IIK_Move;
4223     ParmVarDecl *Param = Constructor->getParamDecl(0);
4224     QualType ParamType = Param->getType().getNonReferenceType();
4225 
4226     Expr *CopyCtorArg =
4227       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4228                           SourceLocation(), Param, false,
4229                           Constructor->getLocation(), ParamType,
4230                           VK_LValue, nullptr);
4231 
4232     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4233 
4234     // Cast to the base class to avoid ambiguities.
4235     QualType ArgTy =
4236       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4237                                        ParamType.getQualifiers());
4238 
4239     if (Moving) {
4240       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4241     }
4242 
4243     CXXCastPath BasePath;
4244     BasePath.push_back(BaseSpec);
4245     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4246                                             CK_UncheckedDerivedToBase,
4247                                             Moving ? VK_XValue : VK_LValue,
4248                                             &BasePath).get();
4249 
4250     InitializationKind InitKind
4251       = InitializationKind::CreateDirect(Constructor->getLocation(),
4252                                          SourceLocation(), SourceLocation());
4253     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4254     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4255     break;
4256   }
4257   }
4258 
4259   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4260   if (BaseInit.isInvalid())
4261     return true;
4262 
4263   CXXBaseInit =
4264     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4265                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4266                                                         SourceLocation()),
4267                                              BaseSpec->isVirtual(),
4268                                              SourceLocation(),
4269                                              BaseInit.getAs<Expr>(),
4270                                              SourceLocation(),
4271                                              SourceLocation());
4272 
4273   return false;
4274 }
4275 
4276 static bool RefersToRValueRef(Expr *MemRef) {
4277   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4278   return Referenced->getType()->isRValueReferenceType();
4279 }
4280 
4281 static bool
4282 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4283                                ImplicitInitializerKind ImplicitInitKind,
4284                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4285                                CXXCtorInitializer *&CXXMemberInit) {
4286   if (Field->isInvalidDecl())
4287     return true;
4288 
4289   SourceLocation Loc = Constructor->getLocation();
4290 
4291   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4292     bool Moving = ImplicitInitKind == IIK_Move;
4293     ParmVarDecl *Param = Constructor->getParamDecl(0);
4294     QualType ParamType = Param->getType().getNonReferenceType();
4295 
4296     // Suppress copying zero-width bitfields.
4297     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4298       return false;
4299 
4300     Expr *MemberExprBase =
4301       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4302                           SourceLocation(), Param, false,
4303                           Loc, ParamType, VK_LValue, nullptr);
4304 
4305     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4306 
4307     if (Moving) {
4308       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4309     }
4310 
4311     // Build a reference to this field within the parameter.
4312     CXXScopeSpec SS;
4313     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4314                               Sema::LookupMemberName);
4315     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4316                                   : cast<ValueDecl>(Field), AS_public);
4317     MemberLookup.resolveKind();
4318     ExprResult CtorArg
4319       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4320                                          ParamType, Loc,
4321                                          /*IsArrow=*/false,
4322                                          SS,
4323                                          /*TemplateKWLoc=*/SourceLocation(),
4324                                          /*FirstQualifierInScope=*/nullptr,
4325                                          MemberLookup,
4326                                          /*TemplateArgs=*/nullptr,
4327                                          /*S*/nullptr);
4328     if (CtorArg.isInvalid())
4329       return true;
4330 
4331     // C++11 [class.copy]p15:
4332     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4333     //     with static_cast<T&&>(x.m);
4334     if (RefersToRValueRef(CtorArg.get())) {
4335       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4336     }
4337 
4338     InitializedEntity Entity =
4339         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4340                                                        /*Implicit*/ true)
4341                  : InitializedEntity::InitializeMember(Field, nullptr,
4342                                                        /*Implicit*/ true);
4343 
4344     // Direct-initialize to use the copy constructor.
4345     InitializationKind InitKind =
4346       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4347 
4348     Expr *CtorArgE = CtorArg.getAs<Expr>();
4349     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4350     ExprResult MemberInit =
4351         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4352     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4353     if (MemberInit.isInvalid())
4354       return true;
4355 
4356     if (Indirect)
4357       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4358           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4359     else
4360       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4361           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4362     return false;
4363   }
4364 
4365   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4366          "Unhandled implicit init kind!");
4367 
4368   QualType FieldBaseElementType =
4369     SemaRef.Context.getBaseElementType(Field->getType());
4370 
4371   if (FieldBaseElementType->isRecordType()) {
4372     InitializedEntity InitEntity =
4373         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4374                                                        /*Implicit*/ true)
4375                  : InitializedEntity::InitializeMember(Field, nullptr,
4376                                                        /*Implicit*/ true);
4377     InitializationKind InitKind =
4378       InitializationKind::CreateDefault(Loc);
4379 
4380     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4381     ExprResult MemberInit =
4382       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4383 
4384     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4385     if (MemberInit.isInvalid())
4386       return true;
4387 
4388     if (Indirect)
4389       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4390                                                                Indirect, Loc,
4391                                                                Loc,
4392                                                                MemberInit.get(),
4393                                                                Loc);
4394     else
4395       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4396                                                                Field, Loc, Loc,
4397                                                                MemberInit.get(),
4398                                                                Loc);
4399     return false;
4400   }
4401 
4402   if (!Field->getParent()->isUnion()) {
4403     if (FieldBaseElementType->isReferenceType()) {
4404       SemaRef.Diag(Constructor->getLocation(),
4405                    diag::err_uninitialized_member_in_ctor)
4406       << (int)Constructor->isImplicit()
4407       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4408       << 0 << Field->getDeclName();
4409       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4410       return true;
4411     }
4412 
4413     if (FieldBaseElementType.isConstQualified()) {
4414       SemaRef.Diag(Constructor->getLocation(),
4415                    diag::err_uninitialized_member_in_ctor)
4416       << (int)Constructor->isImplicit()
4417       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4418       << 1 << Field->getDeclName();
4419       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4420       return true;
4421     }
4422   }
4423 
4424   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4425     // ARC and Weak:
4426     //   Default-initialize Objective-C pointers to NULL.
4427     CXXMemberInit
4428       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4429                                                  Loc, Loc,
4430                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4431                                                  Loc);
4432     return false;
4433   }
4434 
4435   // Nothing to initialize.
4436   CXXMemberInit = nullptr;
4437   return false;
4438 }
4439 
4440 namespace {
4441 struct BaseAndFieldInfo {
4442   Sema &S;
4443   CXXConstructorDecl *Ctor;
4444   bool AnyErrorsInInits;
4445   ImplicitInitializerKind IIK;
4446   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4447   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4448   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4449 
4450   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4451     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4452     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4453     if (Ctor->getInheritedConstructor())
4454       IIK = IIK_Inherit;
4455     else if (Generated && Ctor->isCopyConstructor())
4456       IIK = IIK_Copy;
4457     else if (Generated && Ctor->isMoveConstructor())
4458       IIK = IIK_Move;
4459     else
4460       IIK = IIK_Default;
4461   }
4462 
4463   bool isImplicitCopyOrMove() const {
4464     switch (IIK) {
4465     case IIK_Copy:
4466     case IIK_Move:
4467       return true;
4468 
4469     case IIK_Default:
4470     case IIK_Inherit:
4471       return false;
4472     }
4473 
4474     llvm_unreachable("Invalid ImplicitInitializerKind!");
4475   }
4476 
4477   bool addFieldInitializer(CXXCtorInitializer *Init) {
4478     AllToInit.push_back(Init);
4479 
4480     // Check whether this initializer makes the field "used".
4481     if (Init->getInit()->HasSideEffects(S.Context))
4482       S.UnusedPrivateFields.remove(Init->getAnyMember());
4483 
4484     return false;
4485   }
4486 
4487   bool isInactiveUnionMember(FieldDecl *Field) {
4488     RecordDecl *Record = Field->getParent();
4489     if (!Record->isUnion())
4490       return false;
4491 
4492     if (FieldDecl *Active =
4493             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4494       return Active != Field->getCanonicalDecl();
4495 
4496     // In an implicit copy or move constructor, ignore any in-class initializer.
4497     if (isImplicitCopyOrMove())
4498       return true;
4499 
4500     // If there's no explicit initialization, the field is active only if it
4501     // has an in-class initializer...
4502     if (Field->hasInClassInitializer())
4503       return false;
4504     // ... or it's an anonymous struct or union whose class has an in-class
4505     // initializer.
4506     if (!Field->isAnonymousStructOrUnion())
4507       return true;
4508     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4509     return !FieldRD->hasInClassInitializer();
4510   }
4511 
4512   /// \brief Determine whether the given field is, or is within, a union member
4513   /// that is inactive (because there was an initializer given for a different
4514   /// member of the union, or because the union was not initialized at all).
4515   bool isWithinInactiveUnionMember(FieldDecl *Field,
4516                                    IndirectFieldDecl *Indirect) {
4517     if (!Indirect)
4518       return isInactiveUnionMember(Field);
4519 
4520     for (auto *C : Indirect->chain()) {
4521       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4522       if (Field && isInactiveUnionMember(Field))
4523         return true;
4524     }
4525     return false;
4526   }
4527 };
4528 }
4529 
4530 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4531 /// array type.
4532 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4533   if (T->isIncompleteArrayType())
4534     return true;
4535 
4536   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4537     if (!ArrayT->getSize())
4538       return true;
4539 
4540     T = ArrayT->getElementType();
4541   }
4542 
4543   return false;
4544 }
4545 
4546 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4547                                     FieldDecl *Field,
4548                                     IndirectFieldDecl *Indirect = nullptr) {
4549   if (Field->isInvalidDecl())
4550     return false;
4551 
4552   // Overwhelmingly common case: we have a direct initializer for this field.
4553   if (CXXCtorInitializer *Init =
4554           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4555     return Info.addFieldInitializer(Init);
4556 
4557   // C++11 [class.base.init]p8:
4558   //   if the entity is a non-static data member that has a
4559   //   brace-or-equal-initializer and either
4560   //   -- the constructor's class is a union and no other variant member of that
4561   //      union is designated by a mem-initializer-id or
4562   //   -- the constructor's class is not a union, and, if the entity is a member
4563   //      of an anonymous union, no other member of that union is designated by
4564   //      a mem-initializer-id,
4565   //   the entity is initialized as specified in [dcl.init].
4566   //
4567   // We also apply the same rules to handle anonymous structs within anonymous
4568   // unions.
4569   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4570     return false;
4571 
4572   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4573     ExprResult DIE =
4574         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4575     if (DIE.isInvalid())
4576       return true;
4577     CXXCtorInitializer *Init;
4578     if (Indirect)
4579       Init = new (SemaRef.Context)
4580           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4581                              SourceLocation(), DIE.get(), SourceLocation());
4582     else
4583       Init = new (SemaRef.Context)
4584           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4585                              SourceLocation(), DIE.get(), SourceLocation());
4586     return Info.addFieldInitializer(Init);
4587   }
4588 
4589   // Don't initialize incomplete or zero-length arrays.
4590   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4591     return false;
4592 
4593   // Don't try to build an implicit initializer if there were semantic
4594   // errors in any of the initializers (and therefore we might be
4595   // missing some that the user actually wrote).
4596   if (Info.AnyErrorsInInits)
4597     return false;
4598 
4599   CXXCtorInitializer *Init = nullptr;
4600   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4601                                      Indirect, Init))
4602     return true;
4603 
4604   if (!Init)
4605     return false;
4606 
4607   return Info.addFieldInitializer(Init);
4608 }
4609 
4610 bool
4611 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4612                                CXXCtorInitializer *Initializer) {
4613   assert(Initializer->isDelegatingInitializer());
4614   Constructor->setNumCtorInitializers(1);
4615   CXXCtorInitializer **initializer =
4616     new (Context) CXXCtorInitializer*[1];
4617   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4618   Constructor->setCtorInitializers(initializer);
4619 
4620   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4621     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4622     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4623   }
4624 
4625   DelegatingCtorDecls.push_back(Constructor);
4626 
4627   DiagnoseUninitializedFields(*this, Constructor);
4628 
4629   return false;
4630 }
4631 
4632 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4633                                ArrayRef<CXXCtorInitializer *> Initializers) {
4634   if (Constructor->isDependentContext()) {
4635     // Just store the initializers as written, they will be checked during
4636     // instantiation.
4637     if (!Initializers.empty()) {
4638       Constructor->setNumCtorInitializers(Initializers.size());
4639       CXXCtorInitializer **baseOrMemberInitializers =
4640         new (Context) CXXCtorInitializer*[Initializers.size()];
4641       memcpy(baseOrMemberInitializers, Initializers.data(),
4642              Initializers.size() * sizeof(CXXCtorInitializer*));
4643       Constructor->setCtorInitializers(baseOrMemberInitializers);
4644     }
4645 
4646     // Let template instantiation know whether we had errors.
4647     if (AnyErrors)
4648       Constructor->setInvalidDecl();
4649 
4650     return false;
4651   }
4652 
4653   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4654 
4655   // We need to build the initializer AST according to order of construction
4656   // and not what user specified in the Initializers list.
4657   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4658   if (!ClassDecl)
4659     return true;
4660 
4661   bool HadError = false;
4662 
4663   for (unsigned i = 0; i < Initializers.size(); i++) {
4664     CXXCtorInitializer *Member = Initializers[i];
4665 
4666     if (Member->isBaseInitializer())
4667       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4668     else {
4669       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4670 
4671       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4672         for (auto *C : F->chain()) {
4673           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4674           if (FD && FD->getParent()->isUnion())
4675             Info.ActiveUnionMember.insert(std::make_pair(
4676                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4677         }
4678       } else if (FieldDecl *FD = Member->getMember()) {
4679         if (FD->getParent()->isUnion())
4680           Info.ActiveUnionMember.insert(std::make_pair(
4681               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4682       }
4683     }
4684   }
4685 
4686   // Keep track of the direct virtual bases.
4687   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4688   for (auto &I : ClassDecl->bases()) {
4689     if (I.isVirtual())
4690       DirectVBases.insert(&I);
4691   }
4692 
4693   // Push virtual bases before others.
4694   for (auto &VBase : ClassDecl->vbases()) {
4695     if (CXXCtorInitializer *Value
4696         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4697       // [class.base.init]p7, per DR257:
4698       //   A mem-initializer where the mem-initializer-id names a virtual base
4699       //   class is ignored during execution of a constructor of any class that
4700       //   is not the most derived class.
4701       if (ClassDecl->isAbstract()) {
4702         // FIXME: Provide a fixit to remove the base specifier. This requires
4703         // tracking the location of the associated comma for a base specifier.
4704         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4705           << VBase.getType() << ClassDecl;
4706         DiagnoseAbstractType(ClassDecl);
4707       }
4708 
4709       Info.AllToInit.push_back(Value);
4710     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4711       // [class.base.init]p8, per DR257:
4712       //   If a given [...] base class is not named by a mem-initializer-id
4713       //   [...] and the entity is not a virtual base class of an abstract
4714       //   class, then [...] the entity is default-initialized.
4715       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4716       CXXCtorInitializer *CXXBaseInit;
4717       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4718                                        &VBase, IsInheritedVirtualBase,
4719                                        CXXBaseInit)) {
4720         HadError = true;
4721         continue;
4722       }
4723 
4724       Info.AllToInit.push_back(CXXBaseInit);
4725     }
4726   }
4727 
4728   // Non-virtual bases.
4729   for (auto &Base : ClassDecl->bases()) {
4730     // Virtuals are in the virtual base list and already constructed.
4731     if (Base.isVirtual())
4732       continue;
4733 
4734     if (CXXCtorInitializer *Value
4735           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4736       Info.AllToInit.push_back(Value);
4737     } else if (!AnyErrors) {
4738       CXXCtorInitializer *CXXBaseInit;
4739       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4740                                        &Base, /*IsInheritedVirtualBase=*/false,
4741                                        CXXBaseInit)) {
4742         HadError = true;
4743         continue;
4744       }
4745 
4746       Info.AllToInit.push_back(CXXBaseInit);
4747     }
4748   }
4749 
4750   // Fields.
4751   for (auto *Mem : ClassDecl->decls()) {
4752     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4753       // C++ [class.bit]p2:
4754       //   A declaration for a bit-field that omits the identifier declares an
4755       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4756       //   initialized.
4757       if (F->isUnnamedBitfield())
4758         continue;
4759 
4760       // If we're not generating the implicit copy/move constructor, then we'll
4761       // handle anonymous struct/union fields based on their individual
4762       // indirect fields.
4763       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4764         continue;
4765 
4766       if (CollectFieldInitializer(*this, Info, F))
4767         HadError = true;
4768       continue;
4769     }
4770 
4771     // Beyond this point, we only consider default initialization.
4772     if (Info.isImplicitCopyOrMove())
4773       continue;
4774 
4775     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4776       if (F->getType()->isIncompleteArrayType()) {
4777         assert(ClassDecl->hasFlexibleArrayMember() &&
4778                "Incomplete array type is not valid");
4779         continue;
4780       }
4781 
4782       // Initialize each field of an anonymous struct individually.
4783       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4784         HadError = true;
4785 
4786       continue;
4787     }
4788   }
4789 
4790   unsigned NumInitializers = Info.AllToInit.size();
4791   if (NumInitializers > 0) {
4792     Constructor->setNumCtorInitializers(NumInitializers);
4793     CXXCtorInitializer **baseOrMemberInitializers =
4794       new (Context) CXXCtorInitializer*[NumInitializers];
4795     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4796            NumInitializers * sizeof(CXXCtorInitializer*));
4797     Constructor->setCtorInitializers(baseOrMemberInitializers);
4798 
4799     // Constructors implicitly reference the base and member
4800     // destructors.
4801     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4802                                            Constructor->getParent());
4803   }
4804 
4805   return HadError;
4806 }
4807 
4808 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4809   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4810     const RecordDecl *RD = RT->getDecl();
4811     if (RD->isAnonymousStructOrUnion()) {
4812       for (auto *Field : RD->fields())
4813         PopulateKeysForFields(Field, IdealInits);
4814       return;
4815     }
4816   }
4817   IdealInits.push_back(Field->getCanonicalDecl());
4818 }
4819 
4820 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4821   return Context.getCanonicalType(BaseType).getTypePtr();
4822 }
4823 
4824 static const void *GetKeyForMember(ASTContext &Context,
4825                                    CXXCtorInitializer *Member) {
4826   if (!Member->isAnyMemberInitializer())
4827     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4828 
4829   return Member->getAnyMember()->getCanonicalDecl();
4830 }
4831 
4832 static void DiagnoseBaseOrMemInitializerOrder(
4833     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4834     ArrayRef<CXXCtorInitializer *> Inits) {
4835   if (Constructor->getDeclContext()->isDependentContext())
4836     return;
4837 
4838   // Don't check initializers order unless the warning is enabled at the
4839   // location of at least one initializer.
4840   bool ShouldCheckOrder = false;
4841   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4842     CXXCtorInitializer *Init = Inits[InitIndex];
4843     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4844                                  Init->getSourceLocation())) {
4845       ShouldCheckOrder = true;
4846       break;
4847     }
4848   }
4849   if (!ShouldCheckOrder)
4850     return;
4851 
4852   // Build the list of bases and members in the order that they'll
4853   // actually be initialized.  The explicit initializers should be in
4854   // this same order but may be missing things.
4855   SmallVector<const void*, 32> IdealInitKeys;
4856 
4857   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4858 
4859   // 1. Virtual bases.
4860   for (const auto &VBase : ClassDecl->vbases())
4861     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4862 
4863   // 2. Non-virtual bases.
4864   for (const auto &Base : ClassDecl->bases()) {
4865     if (Base.isVirtual())
4866       continue;
4867     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4868   }
4869 
4870   // 3. Direct fields.
4871   for (auto *Field : ClassDecl->fields()) {
4872     if (Field->isUnnamedBitfield())
4873       continue;
4874 
4875     PopulateKeysForFields(Field, IdealInitKeys);
4876   }
4877 
4878   unsigned NumIdealInits = IdealInitKeys.size();
4879   unsigned IdealIndex = 0;
4880 
4881   CXXCtorInitializer *PrevInit = nullptr;
4882   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4883     CXXCtorInitializer *Init = Inits[InitIndex];
4884     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4885 
4886     // Scan forward to try to find this initializer in the idealized
4887     // initializers list.
4888     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4889       if (InitKey == IdealInitKeys[IdealIndex])
4890         break;
4891 
4892     // If we didn't find this initializer, it must be because we
4893     // scanned past it on a previous iteration.  That can only
4894     // happen if we're out of order;  emit a warning.
4895     if (IdealIndex == NumIdealInits && PrevInit) {
4896       Sema::SemaDiagnosticBuilder D =
4897         SemaRef.Diag(PrevInit->getSourceLocation(),
4898                      diag::warn_initializer_out_of_order);
4899 
4900       if (PrevInit->isAnyMemberInitializer())
4901         D << 0 << PrevInit->getAnyMember()->getDeclName();
4902       else
4903         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4904 
4905       if (Init->isAnyMemberInitializer())
4906         D << 0 << Init->getAnyMember()->getDeclName();
4907       else
4908         D << 1 << Init->getTypeSourceInfo()->getType();
4909 
4910       // Move back to the initializer's location in the ideal list.
4911       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4912         if (InitKey == IdealInitKeys[IdealIndex])
4913           break;
4914 
4915       assert(IdealIndex < NumIdealInits &&
4916              "initializer not found in initializer list");
4917     }
4918 
4919     PrevInit = Init;
4920   }
4921 }
4922 
4923 namespace {
4924 bool CheckRedundantInit(Sema &S,
4925                         CXXCtorInitializer *Init,
4926                         CXXCtorInitializer *&PrevInit) {
4927   if (!PrevInit) {
4928     PrevInit = Init;
4929     return false;
4930   }
4931 
4932   if (FieldDecl *Field = Init->getAnyMember())
4933     S.Diag(Init->getSourceLocation(),
4934            diag::err_multiple_mem_initialization)
4935       << Field->getDeclName()
4936       << Init->getSourceRange();
4937   else {
4938     const Type *BaseClass = Init->getBaseClass();
4939     assert(BaseClass && "neither field nor base");
4940     S.Diag(Init->getSourceLocation(),
4941            diag::err_multiple_base_initialization)
4942       << QualType(BaseClass, 0)
4943       << Init->getSourceRange();
4944   }
4945   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4946     << 0 << PrevInit->getSourceRange();
4947 
4948   return true;
4949 }
4950 
4951 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4952 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4953 
4954 bool CheckRedundantUnionInit(Sema &S,
4955                              CXXCtorInitializer *Init,
4956                              RedundantUnionMap &Unions) {
4957   FieldDecl *Field = Init->getAnyMember();
4958   RecordDecl *Parent = Field->getParent();
4959   NamedDecl *Child = Field;
4960 
4961   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4962     if (Parent->isUnion()) {
4963       UnionEntry &En = Unions[Parent];
4964       if (En.first && En.first != Child) {
4965         S.Diag(Init->getSourceLocation(),
4966                diag::err_multiple_mem_union_initialization)
4967           << Field->getDeclName()
4968           << Init->getSourceRange();
4969         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4970           << 0 << En.second->getSourceRange();
4971         return true;
4972       }
4973       if (!En.first) {
4974         En.first = Child;
4975         En.second = Init;
4976       }
4977       if (!Parent->isAnonymousStructOrUnion())
4978         return false;
4979     }
4980 
4981     Child = Parent;
4982     Parent = cast<RecordDecl>(Parent->getDeclContext());
4983   }
4984 
4985   return false;
4986 }
4987 }
4988 
4989 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4990 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4991                                 SourceLocation ColonLoc,
4992                                 ArrayRef<CXXCtorInitializer*> MemInits,
4993                                 bool AnyErrors) {
4994   if (!ConstructorDecl)
4995     return;
4996 
4997   AdjustDeclIfTemplate(ConstructorDecl);
4998 
4999   CXXConstructorDecl *Constructor
5000     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5001 
5002   if (!Constructor) {
5003     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5004     return;
5005   }
5006 
5007   // Mapping for the duplicate initializers check.
5008   // For member initializers, this is keyed with a FieldDecl*.
5009   // For base initializers, this is keyed with a Type*.
5010   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5011 
5012   // Mapping for the inconsistent anonymous-union initializers check.
5013   RedundantUnionMap MemberUnions;
5014 
5015   bool HadError = false;
5016   for (unsigned i = 0; i < MemInits.size(); i++) {
5017     CXXCtorInitializer *Init = MemInits[i];
5018 
5019     // Set the source order index.
5020     Init->setSourceOrder(i);
5021 
5022     if (Init->isAnyMemberInitializer()) {
5023       const void *Key = GetKeyForMember(Context, Init);
5024       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5025           CheckRedundantUnionInit(*this, Init, MemberUnions))
5026         HadError = true;
5027     } else if (Init->isBaseInitializer()) {
5028       const void *Key = GetKeyForMember(Context, Init);
5029       if (CheckRedundantInit(*this, Init, Members[Key]))
5030         HadError = true;
5031     } else {
5032       assert(Init->isDelegatingInitializer());
5033       // This must be the only initializer
5034       if (MemInits.size() != 1) {
5035         Diag(Init->getSourceLocation(),
5036              diag::err_delegating_initializer_alone)
5037           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5038         // We will treat this as being the only initializer.
5039       }
5040       SetDelegatingInitializer(Constructor, MemInits[i]);
5041       // Return immediately as the initializer is set.
5042       return;
5043     }
5044   }
5045 
5046   if (HadError)
5047     return;
5048 
5049   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5050 
5051   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5052 
5053   DiagnoseUninitializedFields(*this, Constructor);
5054 }
5055 
5056 void
5057 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5058                                              CXXRecordDecl *ClassDecl) {
5059   // Ignore dependent contexts. Also ignore unions, since their members never
5060   // have destructors implicitly called.
5061   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5062     return;
5063 
5064   // FIXME: all the access-control diagnostics are positioned on the
5065   // field/base declaration.  That's probably good; that said, the
5066   // user might reasonably want to know why the destructor is being
5067   // emitted, and we currently don't say.
5068 
5069   // Non-static data members.
5070   for (auto *Field : ClassDecl->fields()) {
5071     if (Field->isInvalidDecl())
5072       continue;
5073 
5074     // Don't destroy incomplete or zero-length arrays.
5075     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5076       continue;
5077 
5078     QualType FieldType = Context.getBaseElementType(Field->getType());
5079 
5080     const RecordType* RT = FieldType->getAs<RecordType>();
5081     if (!RT)
5082       continue;
5083 
5084     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5085     if (FieldClassDecl->isInvalidDecl())
5086       continue;
5087     if (FieldClassDecl->hasIrrelevantDestructor())
5088       continue;
5089     // The destructor for an implicit anonymous union member is never invoked.
5090     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5091       continue;
5092 
5093     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5094     assert(Dtor && "No dtor found for FieldClassDecl!");
5095     CheckDestructorAccess(Field->getLocation(), Dtor,
5096                           PDiag(diag::err_access_dtor_field)
5097                             << Field->getDeclName()
5098                             << FieldType);
5099 
5100     MarkFunctionReferenced(Location, Dtor);
5101     DiagnoseUseOfDecl(Dtor, Location);
5102   }
5103 
5104   // We only potentially invoke the destructors of potentially constructed
5105   // subobjects.
5106   bool VisitVirtualBases = !ClassDecl->isAbstract();
5107 
5108   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5109 
5110   // Bases.
5111   for (const auto &Base : ClassDecl->bases()) {
5112     // Bases are always records in a well-formed non-dependent class.
5113     const RecordType *RT = Base.getType()->getAs<RecordType>();
5114 
5115     // Remember direct virtual bases.
5116     if (Base.isVirtual()) {
5117       if (!VisitVirtualBases)
5118         continue;
5119       DirectVirtualBases.insert(RT);
5120     }
5121 
5122     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5123     // If our base class is invalid, we probably can't get its dtor anyway.
5124     if (BaseClassDecl->isInvalidDecl())
5125       continue;
5126     if (BaseClassDecl->hasIrrelevantDestructor())
5127       continue;
5128 
5129     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5130     assert(Dtor && "No dtor found for BaseClassDecl!");
5131 
5132     // FIXME: caret should be on the start of the class name
5133     CheckDestructorAccess(Base.getLocStart(), Dtor,
5134                           PDiag(diag::err_access_dtor_base)
5135                             << Base.getType()
5136                             << Base.getSourceRange(),
5137                           Context.getTypeDeclType(ClassDecl));
5138 
5139     MarkFunctionReferenced(Location, Dtor);
5140     DiagnoseUseOfDecl(Dtor, Location);
5141   }
5142 
5143   if (!VisitVirtualBases)
5144     return;
5145 
5146   // Virtual bases.
5147   for (const auto &VBase : ClassDecl->vbases()) {
5148     // Bases are always records in a well-formed non-dependent class.
5149     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5150 
5151     // Ignore direct virtual bases.
5152     if (DirectVirtualBases.count(RT))
5153       continue;
5154 
5155     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5156     // If our base class is invalid, we probably can't get its dtor anyway.
5157     if (BaseClassDecl->isInvalidDecl())
5158       continue;
5159     if (BaseClassDecl->hasIrrelevantDestructor())
5160       continue;
5161 
5162     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5163     assert(Dtor && "No dtor found for BaseClassDecl!");
5164     if (CheckDestructorAccess(
5165             ClassDecl->getLocation(), Dtor,
5166             PDiag(diag::err_access_dtor_vbase)
5167                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5168             Context.getTypeDeclType(ClassDecl)) ==
5169         AR_accessible) {
5170       CheckDerivedToBaseConversion(
5171           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5172           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5173           SourceRange(), DeclarationName(), nullptr);
5174     }
5175 
5176     MarkFunctionReferenced(Location, Dtor);
5177     DiagnoseUseOfDecl(Dtor, Location);
5178   }
5179 }
5180 
5181 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5182   if (!CDtorDecl)
5183     return;
5184 
5185   if (CXXConstructorDecl *Constructor
5186       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5187     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5188     DiagnoseUninitializedFields(*this, Constructor);
5189   }
5190 }
5191 
5192 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5193   if (!getLangOpts().CPlusPlus)
5194     return false;
5195 
5196   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5197   if (!RD)
5198     return false;
5199 
5200   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5201   // class template specialization here, but doing so breaks a lot of code.
5202 
5203   // We can't answer whether something is abstract until it has a
5204   // definition. If it's currently being defined, we'll walk back
5205   // over all the declarations when we have a full definition.
5206   const CXXRecordDecl *Def = RD->getDefinition();
5207   if (!Def || Def->isBeingDefined())
5208     return false;
5209 
5210   return RD->isAbstract();
5211 }
5212 
5213 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5214                                   TypeDiagnoser &Diagnoser) {
5215   if (!isAbstractType(Loc, T))
5216     return false;
5217 
5218   T = Context.getBaseElementType(T);
5219   Diagnoser.diagnose(*this, Loc, T);
5220   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5221   return true;
5222 }
5223 
5224 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5225   // Check if we've already emitted the list of pure virtual functions
5226   // for this class.
5227   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5228     return;
5229 
5230   // If the diagnostic is suppressed, don't emit the notes. We're only
5231   // going to emit them once, so try to attach them to a diagnostic we're
5232   // actually going to show.
5233   if (Diags.isLastDiagnosticIgnored())
5234     return;
5235 
5236   CXXFinalOverriderMap FinalOverriders;
5237   RD->getFinalOverriders(FinalOverriders);
5238 
5239   // Keep a set of seen pure methods so we won't diagnose the same method
5240   // more than once.
5241   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5242 
5243   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5244                                    MEnd = FinalOverriders.end();
5245        M != MEnd;
5246        ++M) {
5247     for (OverridingMethods::iterator SO = M->second.begin(),
5248                                   SOEnd = M->second.end();
5249          SO != SOEnd; ++SO) {
5250       // C++ [class.abstract]p4:
5251       //   A class is abstract if it contains or inherits at least one
5252       //   pure virtual function for which the final overrider is pure
5253       //   virtual.
5254 
5255       //
5256       if (SO->second.size() != 1)
5257         continue;
5258 
5259       if (!SO->second.front().Method->isPure())
5260         continue;
5261 
5262       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5263         continue;
5264 
5265       Diag(SO->second.front().Method->getLocation(),
5266            diag::note_pure_virtual_function)
5267         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5268     }
5269   }
5270 
5271   if (!PureVirtualClassDiagSet)
5272     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5273   PureVirtualClassDiagSet->insert(RD);
5274 }
5275 
5276 namespace {
5277 struct AbstractUsageInfo {
5278   Sema &S;
5279   CXXRecordDecl *Record;
5280   CanQualType AbstractType;
5281   bool Invalid;
5282 
5283   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5284     : S(S), Record(Record),
5285       AbstractType(S.Context.getCanonicalType(
5286                    S.Context.getTypeDeclType(Record))),
5287       Invalid(false) {}
5288 
5289   void DiagnoseAbstractType() {
5290     if (Invalid) return;
5291     S.DiagnoseAbstractType(Record);
5292     Invalid = true;
5293   }
5294 
5295   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5296 };
5297 
5298 struct CheckAbstractUsage {
5299   AbstractUsageInfo &Info;
5300   const NamedDecl *Ctx;
5301 
5302   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5303     : Info(Info), Ctx(Ctx) {}
5304 
5305   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5306     switch (TL.getTypeLocClass()) {
5307 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5308 #define TYPELOC(CLASS, PARENT) \
5309     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5310 #include "clang/AST/TypeLocNodes.def"
5311     }
5312   }
5313 
5314   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5315     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5316     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5317       if (!TL.getParam(I))
5318         continue;
5319 
5320       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5321       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5322     }
5323   }
5324 
5325   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5326     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5327   }
5328 
5329   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5330     // Visit the type parameters from a permissive context.
5331     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5332       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5333       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5334         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5335           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5336       // TODO: other template argument types?
5337     }
5338   }
5339 
5340   // Visit pointee types from a permissive context.
5341 #define CheckPolymorphic(Type) \
5342   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5343     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5344   }
5345   CheckPolymorphic(PointerTypeLoc)
5346   CheckPolymorphic(ReferenceTypeLoc)
5347   CheckPolymorphic(MemberPointerTypeLoc)
5348   CheckPolymorphic(BlockPointerTypeLoc)
5349   CheckPolymorphic(AtomicTypeLoc)
5350 
5351   /// Handle all the types we haven't given a more specific
5352   /// implementation for above.
5353   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5354     // Every other kind of type that we haven't called out already
5355     // that has an inner type is either (1) sugar or (2) contains that
5356     // inner type in some way as a subobject.
5357     if (TypeLoc Next = TL.getNextTypeLoc())
5358       return Visit(Next, Sel);
5359 
5360     // If there's no inner type and we're in a permissive context,
5361     // don't diagnose.
5362     if (Sel == Sema::AbstractNone) return;
5363 
5364     // Check whether the type matches the abstract type.
5365     QualType T = TL.getType();
5366     if (T->isArrayType()) {
5367       Sel = Sema::AbstractArrayType;
5368       T = Info.S.Context.getBaseElementType(T);
5369     }
5370     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5371     if (CT != Info.AbstractType) return;
5372 
5373     // It matched; do some magic.
5374     if (Sel == Sema::AbstractArrayType) {
5375       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5376         << T << TL.getSourceRange();
5377     } else {
5378       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5379         << Sel << T << TL.getSourceRange();
5380     }
5381     Info.DiagnoseAbstractType();
5382   }
5383 };
5384 
5385 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5386                                   Sema::AbstractDiagSelID Sel) {
5387   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5388 }
5389 
5390 }
5391 
5392 /// Check for invalid uses of an abstract type in a method declaration.
5393 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5394                                     CXXMethodDecl *MD) {
5395   // No need to do the check on definitions, which require that
5396   // the return/param types be complete.
5397   if (MD->doesThisDeclarationHaveABody())
5398     return;
5399 
5400   // For safety's sake, just ignore it if we don't have type source
5401   // information.  This should never happen for non-implicit methods,
5402   // but...
5403   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5404     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5405 }
5406 
5407 /// Check for invalid uses of an abstract type within a class definition.
5408 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5409                                     CXXRecordDecl *RD) {
5410   for (auto *D : RD->decls()) {
5411     if (D->isImplicit()) continue;
5412 
5413     // Methods and method templates.
5414     if (isa<CXXMethodDecl>(D)) {
5415       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5416     } else if (isa<FunctionTemplateDecl>(D)) {
5417       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5418       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5419 
5420     // Fields and static variables.
5421     } else if (isa<FieldDecl>(D)) {
5422       FieldDecl *FD = cast<FieldDecl>(D);
5423       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5424         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5425     } else if (isa<VarDecl>(D)) {
5426       VarDecl *VD = cast<VarDecl>(D);
5427       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5428         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5429 
5430     // Nested classes and class templates.
5431     } else if (isa<CXXRecordDecl>(D)) {
5432       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5433     } else if (isa<ClassTemplateDecl>(D)) {
5434       CheckAbstractClassUsage(Info,
5435                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5436     }
5437   }
5438 }
5439 
5440 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5441   Attr *ClassAttr = getDLLAttr(Class);
5442   if (!ClassAttr)
5443     return;
5444 
5445   assert(ClassAttr->getKind() == attr::DLLExport);
5446 
5447   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5448 
5449   if (TSK == TSK_ExplicitInstantiationDeclaration)
5450     // Don't go any further if this is just an explicit instantiation
5451     // declaration.
5452     return;
5453 
5454   for (Decl *Member : Class->decls()) {
5455     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5456     if (!MD)
5457       continue;
5458 
5459     if (Member->getAttr<DLLExportAttr>()) {
5460       if (MD->isUserProvided()) {
5461         // Instantiate non-default class member functions ...
5462 
5463         // .. except for certain kinds of template specializations.
5464         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5465           continue;
5466 
5467         S.MarkFunctionReferenced(Class->getLocation(), MD);
5468 
5469         // The function will be passed to the consumer when its definition is
5470         // encountered.
5471       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5472                  MD->isCopyAssignmentOperator() ||
5473                  MD->isMoveAssignmentOperator()) {
5474         // Synthesize and instantiate non-trivial implicit methods, explicitly
5475         // defaulted methods, and the copy and move assignment operators. The
5476         // latter are exported even if they are trivial, because the address of
5477         // an operator can be taken and should compare equal across libraries.
5478         DiagnosticErrorTrap Trap(S.Diags);
5479         S.MarkFunctionReferenced(Class->getLocation(), MD);
5480         if (Trap.hasErrorOccurred()) {
5481           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5482               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5483           break;
5484         }
5485 
5486         // There is no later point when we will see the definition of this
5487         // function, so pass it to the consumer now.
5488         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5489       }
5490     }
5491   }
5492 }
5493 
5494 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5495                                                         CXXRecordDecl *Class) {
5496   // Only the MS ABI has default constructor closures, so we don't need to do
5497   // this semantic checking anywhere else.
5498   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5499     return;
5500 
5501   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5502   for (Decl *Member : Class->decls()) {
5503     // Look for exported default constructors.
5504     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5505     if (!CD || !CD->isDefaultConstructor())
5506       continue;
5507     auto *Attr = CD->getAttr<DLLExportAttr>();
5508     if (!Attr)
5509       continue;
5510 
5511     // If the class is non-dependent, mark the default arguments as ODR-used so
5512     // that we can properly codegen the constructor closure.
5513     if (!Class->isDependentContext()) {
5514       for (ParmVarDecl *PD : CD->parameters()) {
5515         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5516         S.DiscardCleanupsInEvaluationContext();
5517       }
5518     }
5519 
5520     if (LastExportedDefaultCtor) {
5521       S.Diag(LastExportedDefaultCtor->getLocation(),
5522              diag::err_attribute_dll_ambiguous_default_ctor)
5523           << Class;
5524       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5525           << CD->getDeclName();
5526       return;
5527     }
5528     LastExportedDefaultCtor = CD;
5529   }
5530 }
5531 
5532 /// \brief Check class-level dllimport/dllexport attribute.
5533 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5534   Attr *ClassAttr = getDLLAttr(Class);
5535 
5536   // MSVC inherits DLL attributes to partial class template specializations.
5537   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5538     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5539       if (Attr *TemplateAttr =
5540               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5541         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5542         A->setInherited(true);
5543         ClassAttr = A;
5544       }
5545     }
5546   }
5547 
5548   if (!ClassAttr)
5549     return;
5550 
5551   if (!Class->isExternallyVisible()) {
5552     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5553         << Class << ClassAttr;
5554     return;
5555   }
5556 
5557   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5558       !ClassAttr->isInherited()) {
5559     // Diagnose dll attributes on members of class with dll attribute.
5560     for (Decl *Member : Class->decls()) {
5561       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5562         continue;
5563       InheritableAttr *MemberAttr = getDLLAttr(Member);
5564       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5565         continue;
5566 
5567       Diag(MemberAttr->getLocation(),
5568              diag::err_attribute_dll_member_of_dll_class)
5569           << MemberAttr << ClassAttr;
5570       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5571       Member->setInvalidDecl();
5572     }
5573   }
5574 
5575   if (Class->getDescribedClassTemplate())
5576     // Don't inherit dll attribute until the template is instantiated.
5577     return;
5578 
5579   // The class is either imported or exported.
5580   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5581 
5582   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5583 
5584   // Ignore explicit dllexport on explicit class template instantiation declarations.
5585   if (ClassExported && !ClassAttr->isInherited() &&
5586       TSK == TSK_ExplicitInstantiationDeclaration) {
5587     Class->dropAttr<DLLExportAttr>();
5588     return;
5589   }
5590 
5591   // Force declaration of implicit members so they can inherit the attribute.
5592   ForceDeclarationOfImplicitMembers(Class);
5593 
5594   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5595   // seem to be true in practice?
5596 
5597   for (Decl *Member : Class->decls()) {
5598     VarDecl *VD = dyn_cast<VarDecl>(Member);
5599     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5600 
5601     // Only methods and static fields inherit the attributes.
5602     if (!VD && !MD)
5603       continue;
5604 
5605     if (MD) {
5606       // Don't process deleted methods.
5607       if (MD->isDeleted())
5608         continue;
5609 
5610       if (MD->isInlined()) {
5611         // MinGW does not import or export inline methods.
5612         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5613             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5614           continue;
5615 
5616         // MSVC versions before 2015 don't export the move assignment operators
5617         // and move constructor, so don't attempt to import/export them if
5618         // we have a definition.
5619         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5620         if ((MD->isMoveAssignmentOperator() ||
5621              (Ctor && Ctor->isMoveConstructor())) &&
5622             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5623           continue;
5624 
5625         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5626         // operator is exported anyway.
5627         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5628             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5629           continue;
5630       }
5631     }
5632 
5633     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5634       continue;
5635 
5636     if (!getDLLAttr(Member)) {
5637       auto *NewAttr =
5638           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5639       NewAttr->setInherited(true);
5640       Member->addAttr(NewAttr);
5641     }
5642   }
5643 
5644   if (ClassExported)
5645     DelayedDllExportClasses.push_back(Class);
5646 }
5647 
5648 /// \brief Perform propagation of DLL attributes from a derived class to a
5649 /// templated base class for MS compatibility.
5650 void Sema::propagateDLLAttrToBaseClassTemplate(
5651     CXXRecordDecl *Class, Attr *ClassAttr,
5652     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5653   if (getDLLAttr(
5654           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5655     // If the base class template has a DLL attribute, don't try to change it.
5656     return;
5657   }
5658 
5659   auto TSK = BaseTemplateSpec->getSpecializationKind();
5660   if (!getDLLAttr(BaseTemplateSpec) &&
5661       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5662        TSK == TSK_ImplicitInstantiation)) {
5663     // The template hasn't been instantiated yet (or it has, but only as an
5664     // explicit instantiation declaration or implicit instantiation, which means
5665     // we haven't codegenned any members yet), so propagate the attribute.
5666     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5667     NewAttr->setInherited(true);
5668     BaseTemplateSpec->addAttr(NewAttr);
5669 
5670     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5671     // needs to be run again to work see the new attribute. Otherwise this will
5672     // get run whenever the template is instantiated.
5673     if (TSK != TSK_Undeclared)
5674       checkClassLevelDLLAttribute(BaseTemplateSpec);
5675 
5676     return;
5677   }
5678 
5679   if (getDLLAttr(BaseTemplateSpec)) {
5680     // The template has already been specialized or instantiated with an
5681     // attribute, explicitly or through propagation. We should not try to change
5682     // it.
5683     return;
5684   }
5685 
5686   // The template was previously instantiated or explicitly specialized without
5687   // a dll attribute, It's too late for us to add an attribute, so warn that
5688   // this is unsupported.
5689   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5690       << BaseTemplateSpec->isExplicitSpecialization();
5691   Diag(ClassAttr->getLocation(), diag::note_attribute);
5692   if (BaseTemplateSpec->isExplicitSpecialization()) {
5693     Diag(BaseTemplateSpec->getLocation(),
5694            diag::note_template_class_explicit_specialization_was_here)
5695         << BaseTemplateSpec;
5696   } else {
5697     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5698            diag::note_template_class_instantiation_was_here)
5699         << BaseTemplateSpec;
5700   }
5701 }
5702 
5703 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5704                                         SourceLocation DefaultLoc) {
5705   switch (S.getSpecialMember(MD)) {
5706   case Sema::CXXDefaultConstructor:
5707     S.DefineImplicitDefaultConstructor(DefaultLoc,
5708                                        cast<CXXConstructorDecl>(MD));
5709     break;
5710   case Sema::CXXCopyConstructor:
5711     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5712     break;
5713   case Sema::CXXCopyAssignment:
5714     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5715     break;
5716   case Sema::CXXDestructor:
5717     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5718     break;
5719   case Sema::CXXMoveConstructor:
5720     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5721     break;
5722   case Sema::CXXMoveAssignment:
5723     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5724     break;
5725   case Sema::CXXInvalid:
5726     llvm_unreachable("Invalid special member.");
5727   }
5728 }
5729 
5730 /// Determine whether a type is permitted to be passed or returned in
5731 /// registers, per C++ [class.temporary]p3.
5732 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) {
5733   if (D->isDependentType() || D->isInvalidDecl())
5734     return false;
5735 
5736   // Per C++ [class.temporary]p3, the relevant condition is:
5737   //   each copy constructor, move constructor, and destructor of X is
5738   //   either trivial or deleted, and X has at least one non-deleted copy
5739   //   or move constructor
5740   bool HasNonDeletedCopyOrMove = false;
5741 
5742   if (D->needsImplicitCopyConstructor() &&
5743       !D->defaultedCopyConstructorIsDeleted()) {
5744     if (!D->hasTrivialCopyConstructor())
5745       return false;
5746     HasNonDeletedCopyOrMove = true;
5747   }
5748 
5749   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5750       !D->defaultedMoveConstructorIsDeleted()) {
5751     if (!D->hasTrivialMoveConstructor())
5752       return false;
5753     HasNonDeletedCopyOrMove = true;
5754   }
5755 
5756   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5757       !D->hasTrivialDestructor())
5758     return false;
5759 
5760   for (const CXXMethodDecl *MD : D->methods()) {
5761     if (MD->isDeleted())
5762       continue;
5763 
5764     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5765     if (CD && CD->isCopyOrMoveConstructor())
5766       HasNonDeletedCopyOrMove = true;
5767     else if (!isa<CXXDestructorDecl>(MD))
5768       continue;
5769 
5770     if (!MD->isTrivial())
5771       return false;
5772   }
5773 
5774   return HasNonDeletedCopyOrMove;
5775 }
5776 
5777 /// \brief Perform semantic checks on a class definition that has been
5778 /// completing, introducing implicitly-declared members, checking for
5779 /// abstract types, etc.
5780 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5781   if (!Record)
5782     return;
5783 
5784   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5785     AbstractUsageInfo Info(*this, Record);
5786     CheckAbstractClassUsage(Info, Record);
5787   }
5788 
5789   // If this is not an aggregate type and has no user-declared constructor,
5790   // complain about any non-static data members of reference or const scalar
5791   // type, since they will never get initializers.
5792   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5793       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5794       !Record->isLambda()) {
5795     bool Complained = false;
5796     for (const auto *F : Record->fields()) {
5797       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5798         continue;
5799 
5800       if (F->getType()->isReferenceType() ||
5801           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5802         if (!Complained) {
5803           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5804             << Record->getTagKind() << Record;
5805           Complained = true;
5806         }
5807 
5808         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5809           << F->getType()->isReferenceType()
5810           << F->getDeclName();
5811       }
5812     }
5813   }
5814 
5815   if (Record->getIdentifier()) {
5816     // C++ [class.mem]p13:
5817     //   If T is the name of a class, then each of the following shall have a
5818     //   name different from T:
5819     //     - every member of every anonymous union that is a member of class T.
5820     //
5821     // C++ [class.mem]p14:
5822     //   In addition, if class T has a user-declared constructor (12.1), every
5823     //   non-static data member of class T shall have a name different from T.
5824     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5825     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5826          ++I) {
5827       NamedDecl *D = *I;
5828       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5829           isa<IndirectFieldDecl>(D)) {
5830         Diag(D->getLocation(), diag::err_member_name_of_class)
5831           << D->getDeclName();
5832         break;
5833       }
5834     }
5835   }
5836 
5837   // Warn if the class has virtual methods but non-virtual public destructor.
5838   if (Record->isPolymorphic() && !Record->isDependentType()) {
5839     CXXDestructorDecl *dtor = Record->getDestructor();
5840     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5841         !Record->hasAttr<FinalAttr>())
5842       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5843            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5844   }
5845 
5846   if (Record->isAbstract()) {
5847     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5848       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5849         << FA->isSpelledAsSealed();
5850       DiagnoseAbstractType(Record);
5851     }
5852   }
5853 
5854   bool HasMethodWithOverrideControl = false,
5855        HasOverridingMethodWithoutOverrideControl = false;
5856   if (!Record->isDependentType()) {
5857     for (auto *M : Record->methods()) {
5858       // See if a method overloads virtual methods in a base
5859       // class without overriding any.
5860       if (!M->isStatic())
5861         DiagnoseHiddenVirtualMethods(M);
5862       if (M->hasAttr<OverrideAttr>())
5863         HasMethodWithOverrideControl = true;
5864       else if (M->size_overridden_methods() > 0)
5865         HasOverridingMethodWithoutOverrideControl = true;
5866       // Check whether the explicitly-defaulted special members are valid.
5867       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5868         CheckExplicitlyDefaultedSpecialMember(M);
5869 
5870       // For an explicitly defaulted or deleted special member, we defer
5871       // determining triviality until the class is complete. That time is now!
5872       CXXSpecialMember CSM = getSpecialMember(M);
5873       if (!M->isImplicit() && !M->isUserProvided()) {
5874         if (CSM != CXXInvalid) {
5875           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5876 
5877           // Inform the class that we've finished declaring this member.
5878           Record->finishedDefaultedOrDeletedMember(M);
5879         }
5880       }
5881 
5882       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5883           M->hasAttr<DLLExportAttr>()) {
5884         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5885             M->isTrivial() &&
5886             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5887              CSM == CXXDestructor))
5888           M->dropAttr<DLLExportAttr>();
5889 
5890         if (M->hasAttr<DLLExportAttr>()) {
5891           DefineImplicitSpecialMember(*this, M, M->getLocation());
5892           ActOnFinishInlineFunctionDef(M);
5893         }
5894       }
5895     }
5896   }
5897 
5898   if (HasMethodWithOverrideControl &&
5899       HasOverridingMethodWithoutOverrideControl) {
5900     // At least one method has the 'override' control declared.
5901     // Diagnose all other overridden methods which do not have 'override' specified on them.
5902     for (auto *M : Record->methods())
5903       DiagnoseAbsenceOfOverrideControl(M);
5904   }
5905 
5906   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5907   // whether this class uses any C++ features that are implemented
5908   // completely differently in MSVC, and if so, emit a diagnostic.
5909   // That diagnostic defaults to an error, but we allow projects to
5910   // map it down to a warning (or ignore it).  It's a fairly common
5911   // practice among users of the ms_struct pragma to mass-annotate
5912   // headers, sweeping up a bunch of types that the project doesn't
5913   // really rely on MSVC-compatible layout for.  We must therefore
5914   // support "ms_struct except for C++ stuff" as a secondary ABI.
5915   if (Record->isMsStruct(Context) &&
5916       (Record->isPolymorphic() || Record->getNumBases())) {
5917     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5918   }
5919 
5920   checkClassLevelDLLAttribute(Record);
5921 
5922   Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record));
5923 }
5924 
5925 /// Look up the special member function that would be called by a special
5926 /// member function for a subobject of class type.
5927 ///
5928 /// \param Class The class type of the subobject.
5929 /// \param CSM The kind of special member function.
5930 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5931 /// \param ConstRHS True if this is a copy operation with a const object
5932 ///        on its RHS, that is, if the argument to the outer special member
5933 ///        function is 'const' and this is not a field marked 'mutable'.
5934 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
5935     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5936     unsigned FieldQuals, bool ConstRHS) {
5937   unsigned LHSQuals = 0;
5938   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5939     LHSQuals = FieldQuals;
5940 
5941   unsigned RHSQuals = FieldQuals;
5942   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5943     RHSQuals = 0;
5944   else if (ConstRHS)
5945     RHSQuals |= Qualifiers::Const;
5946 
5947   return S.LookupSpecialMember(Class, CSM,
5948                                RHSQuals & Qualifiers::Const,
5949                                RHSQuals & Qualifiers::Volatile,
5950                                false,
5951                                LHSQuals & Qualifiers::Const,
5952                                LHSQuals & Qualifiers::Volatile);
5953 }
5954 
5955 class Sema::InheritedConstructorInfo {
5956   Sema &S;
5957   SourceLocation UseLoc;
5958 
5959   /// A mapping from the base classes through which the constructor was
5960   /// inherited to the using shadow declaration in that base class (or a null
5961   /// pointer if the constructor was declared in that base class).
5962   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5963       InheritedFromBases;
5964 
5965 public:
5966   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5967                            ConstructorUsingShadowDecl *Shadow)
5968       : S(S), UseLoc(UseLoc) {
5969     bool DiagnosedMultipleConstructedBases = false;
5970     CXXRecordDecl *ConstructedBase = nullptr;
5971     UsingDecl *ConstructedBaseUsing = nullptr;
5972 
5973     // Find the set of such base class subobjects and check that there's a
5974     // unique constructed subobject.
5975     for (auto *D : Shadow->redecls()) {
5976       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5977       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5978       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5979 
5980       InheritedFromBases.insert(
5981           std::make_pair(DNominatedBase->getCanonicalDecl(),
5982                          DShadow->getNominatedBaseClassShadowDecl()));
5983       if (DShadow->constructsVirtualBase())
5984         InheritedFromBases.insert(
5985             std::make_pair(DConstructedBase->getCanonicalDecl(),
5986                            DShadow->getConstructedBaseClassShadowDecl()));
5987       else
5988         assert(DNominatedBase == DConstructedBase);
5989 
5990       // [class.inhctor.init]p2:
5991       //   If the constructor was inherited from multiple base class subobjects
5992       //   of type B, the program is ill-formed.
5993       if (!ConstructedBase) {
5994         ConstructedBase = DConstructedBase;
5995         ConstructedBaseUsing = D->getUsingDecl();
5996       } else if (ConstructedBase != DConstructedBase &&
5997                  !Shadow->isInvalidDecl()) {
5998         if (!DiagnosedMultipleConstructedBases) {
5999           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6000               << Shadow->getTargetDecl();
6001           S.Diag(ConstructedBaseUsing->getLocation(),
6002                diag::note_ambiguous_inherited_constructor_using)
6003               << ConstructedBase;
6004           DiagnosedMultipleConstructedBases = true;
6005         }
6006         S.Diag(D->getUsingDecl()->getLocation(),
6007                diag::note_ambiguous_inherited_constructor_using)
6008             << DConstructedBase;
6009       }
6010     }
6011 
6012     if (DiagnosedMultipleConstructedBases)
6013       Shadow->setInvalidDecl();
6014   }
6015 
6016   /// Find the constructor to use for inherited construction of a base class,
6017   /// and whether that base class constructor inherits the constructor from a
6018   /// virtual base class (in which case it won't actually invoke it).
6019   std::pair<CXXConstructorDecl *, bool>
6020   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6021     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6022     if (It == InheritedFromBases.end())
6023       return std::make_pair(nullptr, false);
6024 
6025     // This is an intermediary class.
6026     if (It->second)
6027       return std::make_pair(
6028           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6029           It->second->constructsVirtualBase());
6030 
6031     // This is the base class from which the constructor was inherited.
6032     return std::make_pair(Ctor, false);
6033   }
6034 };
6035 
6036 /// Is the special member function which would be selected to perform the
6037 /// specified operation on the specified class type a constexpr constructor?
6038 static bool
6039 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6040                          Sema::CXXSpecialMember CSM, unsigned Quals,
6041                          bool ConstRHS,
6042                          CXXConstructorDecl *InheritedCtor = nullptr,
6043                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6044   // If we're inheriting a constructor, see if we need to call it for this base
6045   // class.
6046   if (InheritedCtor) {
6047     assert(CSM == Sema::CXXDefaultConstructor);
6048     auto BaseCtor =
6049         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6050     if (BaseCtor)
6051       return BaseCtor->isConstexpr();
6052   }
6053 
6054   if (CSM == Sema::CXXDefaultConstructor)
6055     return ClassDecl->hasConstexprDefaultConstructor();
6056 
6057   Sema::SpecialMemberOverloadResult SMOR =
6058       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6059   if (!SMOR.getMethod())
6060     // A constructor we wouldn't select can't be "involved in initializing"
6061     // anything.
6062     return true;
6063   return SMOR.getMethod()->isConstexpr();
6064 }
6065 
6066 /// Determine whether the specified special member function would be constexpr
6067 /// if it were implicitly defined.
6068 static bool defaultedSpecialMemberIsConstexpr(
6069     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6070     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6071     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6072   if (!S.getLangOpts().CPlusPlus11)
6073     return false;
6074 
6075   // C++11 [dcl.constexpr]p4:
6076   // In the definition of a constexpr constructor [...]
6077   bool Ctor = true;
6078   switch (CSM) {
6079   case Sema::CXXDefaultConstructor:
6080     if (Inherited)
6081       break;
6082     // Since default constructor lookup is essentially trivial (and cannot
6083     // involve, for instance, template instantiation), we compute whether a
6084     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6085     //
6086     // This is important for performance; we need to know whether the default
6087     // constructor is constexpr to determine whether the type is a literal type.
6088     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6089 
6090   case Sema::CXXCopyConstructor:
6091   case Sema::CXXMoveConstructor:
6092     // For copy or move constructors, we need to perform overload resolution.
6093     break;
6094 
6095   case Sema::CXXCopyAssignment:
6096   case Sema::CXXMoveAssignment:
6097     if (!S.getLangOpts().CPlusPlus14)
6098       return false;
6099     // In C++1y, we need to perform overload resolution.
6100     Ctor = false;
6101     break;
6102 
6103   case Sema::CXXDestructor:
6104   case Sema::CXXInvalid:
6105     return false;
6106   }
6107 
6108   //   -- if the class is a non-empty union, or for each non-empty anonymous
6109   //      union member of a non-union class, exactly one non-static data member
6110   //      shall be initialized; [DR1359]
6111   //
6112   // If we squint, this is guaranteed, since exactly one non-static data member
6113   // will be initialized (if the constructor isn't deleted), we just don't know
6114   // which one.
6115   if (Ctor && ClassDecl->isUnion())
6116     return CSM == Sema::CXXDefaultConstructor
6117                ? ClassDecl->hasInClassInitializer() ||
6118                      !ClassDecl->hasVariantMembers()
6119                : true;
6120 
6121   //   -- the class shall not have any virtual base classes;
6122   if (Ctor && ClassDecl->getNumVBases())
6123     return false;
6124 
6125   // C++1y [class.copy]p26:
6126   //   -- [the class] is a literal type, and
6127   if (!Ctor && !ClassDecl->isLiteral())
6128     return false;
6129 
6130   //   -- every constructor involved in initializing [...] base class
6131   //      sub-objects shall be a constexpr constructor;
6132   //   -- the assignment operator selected to copy/move each direct base
6133   //      class is a constexpr function, and
6134   for (const auto &B : ClassDecl->bases()) {
6135     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6136     if (!BaseType) continue;
6137 
6138     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6139     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6140                                   InheritedCtor, Inherited))
6141       return false;
6142   }
6143 
6144   //   -- every constructor involved in initializing non-static data members
6145   //      [...] shall be a constexpr constructor;
6146   //   -- every non-static data member and base class sub-object shall be
6147   //      initialized
6148   //   -- for each non-static data member of X that is of class type (or array
6149   //      thereof), the assignment operator selected to copy/move that member is
6150   //      a constexpr function
6151   for (const auto *F : ClassDecl->fields()) {
6152     if (F->isInvalidDecl())
6153       continue;
6154     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6155       continue;
6156     QualType BaseType = S.Context.getBaseElementType(F->getType());
6157     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6158       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6159       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6160                                     BaseType.getCVRQualifiers(),
6161                                     ConstArg && !F->isMutable()))
6162         return false;
6163     } else if (CSM == Sema::CXXDefaultConstructor) {
6164       return false;
6165     }
6166   }
6167 
6168   // All OK, it's constexpr!
6169   return true;
6170 }
6171 
6172 static Sema::ImplicitExceptionSpecification
6173 ComputeDefaultedSpecialMemberExceptionSpec(
6174     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6175     Sema::InheritedConstructorInfo *ICI);
6176 
6177 static Sema::ImplicitExceptionSpecification
6178 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6179   auto CSM = S.getSpecialMember(MD);
6180   if (CSM != Sema::CXXInvalid)
6181     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6182 
6183   auto *CD = cast<CXXConstructorDecl>(MD);
6184   assert(CD->getInheritedConstructor() &&
6185          "only special members have implicit exception specs");
6186   Sema::InheritedConstructorInfo ICI(
6187       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6188   return ComputeDefaultedSpecialMemberExceptionSpec(
6189       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6190 }
6191 
6192 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6193                                                             CXXMethodDecl *MD) {
6194   FunctionProtoType::ExtProtoInfo EPI;
6195 
6196   // Build an exception specification pointing back at this member.
6197   EPI.ExceptionSpec.Type = EST_Unevaluated;
6198   EPI.ExceptionSpec.SourceDecl = MD;
6199 
6200   // Set the calling convention to the default for C++ instance methods.
6201   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6202       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6203                                             /*IsCXXMethod=*/true));
6204   return EPI;
6205 }
6206 
6207 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6208   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6209   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6210     return;
6211 
6212   // Evaluate the exception specification.
6213   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6214   auto ESI = IES.getExceptionSpec();
6215 
6216   // Update the type of the special member to use it.
6217   UpdateExceptionSpec(MD, ESI);
6218 
6219   // A user-provided destructor can be defined outside the class. When that
6220   // happens, be sure to update the exception specification on both
6221   // declarations.
6222   const FunctionProtoType *CanonicalFPT =
6223     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6224   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6225     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6226 }
6227 
6228 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6229   CXXRecordDecl *RD = MD->getParent();
6230   CXXSpecialMember CSM = getSpecialMember(MD);
6231 
6232   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6233          "not an explicitly-defaulted special member");
6234 
6235   // Whether this was the first-declared instance of the constructor.
6236   // This affects whether we implicitly add an exception spec and constexpr.
6237   bool First = MD == MD->getCanonicalDecl();
6238 
6239   bool HadError = false;
6240 
6241   // C++11 [dcl.fct.def.default]p1:
6242   //   A function that is explicitly defaulted shall
6243   //     -- be a special member function (checked elsewhere),
6244   //     -- have the same type (except for ref-qualifiers, and except that a
6245   //        copy operation can take a non-const reference) as an implicit
6246   //        declaration, and
6247   //     -- not have default arguments.
6248   unsigned ExpectedParams = 1;
6249   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6250     ExpectedParams = 0;
6251   if (MD->getNumParams() != ExpectedParams) {
6252     // This also checks for default arguments: a copy or move constructor with a
6253     // default argument is classified as a default constructor, and assignment
6254     // operations and destructors can't have default arguments.
6255     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6256       << CSM << MD->getSourceRange();
6257     HadError = true;
6258   } else if (MD->isVariadic()) {
6259     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6260       << CSM << MD->getSourceRange();
6261     HadError = true;
6262   }
6263 
6264   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6265 
6266   bool CanHaveConstParam = false;
6267   if (CSM == CXXCopyConstructor)
6268     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6269   else if (CSM == CXXCopyAssignment)
6270     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6271 
6272   QualType ReturnType = Context.VoidTy;
6273   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6274     // Check for return type matching.
6275     ReturnType = Type->getReturnType();
6276     QualType ExpectedReturnType =
6277         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6278     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6279       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6280         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6281       HadError = true;
6282     }
6283 
6284     // A defaulted special member cannot have cv-qualifiers.
6285     if (Type->getTypeQuals()) {
6286       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6287         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6288       HadError = true;
6289     }
6290   }
6291 
6292   // Check for parameter type matching.
6293   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6294   bool HasConstParam = false;
6295   if (ExpectedParams && ArgType->isReferenceType()) {
6296     // Argument must be reference to possibly-const T.
6297     QualType ReferentType = ArgType->getPointeeType();
6298     HasConstParam = ReferentType.isConstQualified();
6299 
6300     if (ReferentType.isVolatileQualified()) {
6301       Diag(MD->getLocation(),
6302            diag::err_defaulted_special_member_volatile_param) << CSM;
6303       HadError = true;
6304     }
6305 
6306     if (HasConstParam && !CanHaveConstParam) {
6307       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6308         Diag(MD->getLocation(),
6309              diag::err_defaulted_special_member_copy_const_param)
6310           << (CSM == CXXCopyAssignment);
6311         // FIXME: Explain why this special member can't be const.
6312       } else {
6313         Diag(MD->getLocation(),
6314              diag::err_defaulted_special_member_move_const_param)
6315           << (CSM == CXXMoveAssignment);
6316       }
6317       HadError = true;
6318     }
6319   } else if (ExpectedParams) {
6320     // A copy assignment operator can take its argument by value, but a
6321     // defaulted one cannot.
6322     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6323     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6324     HadError = true;
6325   }
6326 
6327   // C++11 [dcl.fct.def.default]p2:
6328   //   An explicitly-defaulted function may be declared constexpr only if it
6329   //   would have been implicitly declared as constexpr,
6330   // Do not apply this rule to members of class templates, since core issue 1358
6331   // makes such functions always instantiate to constexpr functions. For
6332   // functions which cannot be constexpr (for non-constructors in C++11 and for
6333   // destructors in C++1y), this is checked elsewhere.
6334   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6335                                                      HasConstParam);
6336   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6337                                  : isa<CXXConstructorDecl>(MD)) &&
6338       MD->isConstexpr() && !Constexpr &&
6339       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6340     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6341     // FIXME: Explain why the special member can't be constexpr.
6342     HadError = true;
6343   }
6344 
6345   //   and may have an explicit exception-specification only if it is compatible
6346   //   with the exception-specification on the implicit declaration.
6347   if (Type->hasExceptionSpec()) {
6348     // Delay the check if this is the first declaration of the special member,
6349     // since we may not have parsed some necessary in-class initializers yet.
6350     if (First) {
6351       // If the exception specification needs to be instantiated, do so now,
6352       // before we clobber it with an EST_Unevaluated specification below.
6353       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6354         InstantiateExceptionSpec(MD->getLocStart(), MD);
6355         Type = MD->getType()->getAs<FunctionProtoType>();
6356       }
6357       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6358     } else
6359       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6360   }
6361 
6362   //   If a function is explicitly defaulted on its first declaration,
6363   if (First) {
6364     //  -- it is implicitly considered to be constexpr if the implicit
6365     //     definition would be,
6366     MD->setConstexpr(Constexpr);
6367 
6368     //  -- it is implicitly considered to have the same exception-specification
6369     //     as if it had been implicitly declared,
6370     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6371     EPI.ExceptionSpec.Type = EST_Unevaluated;
6372     EPI.ExceptionSpec.SourceDecl = MD;
6373     MD->setType(Context.getFunctionType(ReturnType,
6374                                         llvm::makeArrayRef(&ArgType,
6375                                                            ExpectedParams),
6376                                         EPI));
6377   }
6378 
6379   if (ShouldDeleteSpecialMember(MD, CSM)) {
6380     if (First) {
6381       SetDeclDeleted(MD, MD->getLocation());
6382     } else {
6383       // C++11 [dcl.fct.def.default]p4:
6384       //   [For a] user-provided explicitly-defaulted function [...] if such a
6385       //   function is implicitly defined as deleted, the program is ill-formed.
6386       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6387       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6388       HadError = true;
6389     }
6390   }
6391 
6392   if (HadError)
6393     MD->setInvalidDecl();
6394 }
6395 
6396 /// Check whether the exception specification provided for an
6397 /// explicitly-defaulted special member matches the exception specification
6398 /// that would have been generated for an implicit special member, per
6399 /// C++11 [dcl.fct.def.default]p2.
6400 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6401     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6402   // If the exception specification was explicitly specified but hadn't been
6403   // parsed when the method was defaulted, grab it now.
6404   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6405     SpecifiedType =
6406         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6407 
6408   // Compute the implicit exception specification.
6409   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6410                                                        /*IsCXXMethod=*/true);
6411   FunctionProtoType::ExtProtoInfo EPI(CC);
6412   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6413   EPI.ExceptionSpec = IES.getExceptionSpec();
6414   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6415     Context.getFunctionType(Context.VoidTy, None, EPI));
6416 
6417   // Ensure that it matches.
6418   CheckEquivalentExceptionSpec(
6419     PDiag(diag::err_incorrect_defaulted_exception_spec)
6420       << getSpecialMember(MD), PDiag(),
6421     ImplicitType, SourceLocation(),
6422     SpecifiedType, MD->getLocation());
6423 }
6424 
6425 void Sema::CheckDelayedMemberExceptionSpecs() {
6426   decltype(DelayedExceptionSpecChecks) Checks;
6427   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6428 
6429   std::swap(Checks, DelayedExceptionSpecChecks);
6430   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6431 
6432   // Perform any deferred checking of exception specifications for virtual
6433   // destructors.
6434   for (auto &Check : Checks)
6435     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6436 
6437   // Check that any explicitly-defaulted methods have exception specifications
6438   // compatible with their implicit exception specifications.
6439   for (auto &Spec : Specs)
6440     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6441 }
6442 
6443 namespace {
6444 /// CRTP base class for visiting operations performed by a special member
6445 /// function (or inherited constructor).
6446 template<typename Derived>
6447 struct SpecialMemberVisitor {
6448   Sema &S;
6449   CXXMethodDecl *MD;
6450   Sema::CXXSpecialMember CSM;
6451   Sema::InheritedConstructorInfo *ICI;
6452 
6453   // Properties of the special member, computed for convenience.
6454   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6455 
6456   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6457                        Sema::InheritedConstructorInfo *ICI)
6458       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6459     switch (CSM) {
6460     case Sema::CXXDefaultConstructor:
6461     case Sema::CXXCopyConstructor:
6462     case Sema::CXXMoveConstructor:
6463       IsConstructor = true;
6464       break;
6465     case Sema::CXXCopyAssignment:
6466     case Sema::CXXMoveAssignment:
6467       IsAssignment = true;
6468       break;
6469     case Sema::CXXDestructor:
6470       break;
6471     case Sema::CXXInvalid:
6472       llvm_unreachable("invalid special member kind");
6473     }
6474 
6475     if (MD->getNumParams()) {
6476       if (const ReferenceType *RT =
6477               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6478         ConstArg = RT->getPointeeType().isConstQualified();
6479     }
6480   }
6481 
6482   Derived &getDerived() { return static_cast<Derived&>(*this); }
6483 
6484   /// Is this a "move" special member?
6485   bool isMove() const {
6486     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6487   }
6488 
6489   /// Look up the corresponding special member in the given class.
6490   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6491                                              unsigned Quals, bool IsMutable) {
6492     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6493                                        ConstArg && !IsMutable);
6494   }
6495 
6496   /// Look up the constructor for the specified base class to see if it's
6497   /// overridden due to this being an inherited constructor.
6498   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6499     if (!ICI)
6500       return {};
6501     assert(CSM == Sema::CXXDefaultConstructor);
6502     auto *BaseCtor =
6503       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6504     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6505       return MD;
6506     return {};
6507   }
6508 
6509   /// A base or member subobject.
6510   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6511 
6512   /// Get the location to use for a subobject in diagnostics.
6513   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6514     // FIXME: For an indirect virtual base, the direct base leading to
6515     // the indirect virtual base would be a more useful choice.
6516     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6517       return B->getBaseTypeLoc();
6518     else
6519       return Subobj.get<FieldDecl*>()->getLocation();
6520   }
6521 
6522   enum BasesToVisit {
6523     /// Visit all non-virtual (direct) bases.
6524     VisitNonVirtualBases,
6525     /// Visit all direct bases, virtual or not.
6526     VisitDirectBases,
6527     /// Visit all non-virtual bases, and all virtual bases if the class
6528     /// is not abstract.
6529     VisitPotentiallyConstructedBases,
6530     /// Visit all direct or virtual bases.
6531     VisitAllBases
6532   };
6533 
6534   // Visit the bases and members of the class.
6535   bool visit(BasesToVisit Bases) {
6536     CXXRecordDecl *RD = MD->getParent();
6537 
6538     if (Bases == VisitPotentiallyConstructedBases)
6539       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6540 
6541     for (auto &B : RD->bases())
6542       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6543           getDerived().visitBase(&B))
6544         return true;
6545 
6546     if (Bases == VisitAllBases)
6547       for (auto &B : RD->vbases())
6548         if (getDerived().visitBase(&B))
6549           return true;
6550 
6551     for (auto *F : RD->fields())
6552       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6553           getDerived().visitField(F))
6554         return true;
6555 
6556     return false;
6557   }
6558 };
6559 }
6560 
6561 namespace {
6562 struct SpecialMemberDeletionInfo
6563     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6564   bool Diagnose;
6565 
6566   SourceLocation Loc;
6567 
6568   bool AllFieldsAreConst;
6569 
6570   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6571                             Sema::CXXSpecialMember CSM,
6572                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6573       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6574         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6575 
6576   bool inUnion() const { return MD->getParent()->isUnion(); }
6577 
6578   Sema::CXXSpecialMember getEffectiveCSM() {
6579     return ICI ? Sema::CXXInvalid : CSM;
6580   }
6581 
6582   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6583   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6584 
6585   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6586   bool shouldDeleteForField(FieldDecl *FD);
6587   bool shouldDeleteForAllConstMembers();
6588 
6589   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6590                                      unsigned Quals);
6591   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6592                                     Sema::SpecialMemberOverloadResult SMOR,
6593                                     bool IsDtorCallInCtor);
6594 
6595   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6596 };
6597 }
6598 
6599 /// Is the given special member inaccessible when used on the given
6600 /// sub-object.
6601 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6602                                              CXXMethodDecl *target) {
6603   /// If we're operating on a base class, the object type is the
6604   /// type of this special member.
6605   QualType objectTy;
6606   AccessSpecifier access = target->getAccess();
6607   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6608     objectTy = S.Context.getTypeDeclType(MD->getParent());
6609     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6610 
6611   // If we're operating on a field, the object type is the type of the field.
6612   } else {
6613     objectTy = S.Context.getTypeDeclType(target->getParent());
6614   }
6615 
6616   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6617 }
6618 
6619 /// Check whether we should delete a special member due to the implicit
6620 /// definition containing a call to a special member of a subobject.
6621 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6622     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6623     bool IsDtorCallInCtor) {
6624   CXXMethodDecl *Decl = SMOR.getMethod();
6625   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6626 
6627   int DiagKind = -1;
6628 
6629   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6630     DiagKind = !Decl ? 0 : 1;
6631   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6632     DiagKind = 2;
6633   else if (!isAccessible(Subobj, Decl))
6634     DiagKind = 3;
6635   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6636            !Decl->isTrivial()) {
6637     // A member of a union must have a trivial corresponding special member.
6638     // As a weird special case, a destructor call from a union's constructor
6639     // must be accessible and non-deleted, but need not be trivial. Such a
6640     // destructor is never actually called, but is semantically checked as
6641     // if it were.
6642     DiagKind = 4;
6643   }
6644 
6645   if (DiagKind == -1)
6646     return false;
6647 
6648   if (Diagnose) {
6649     if (Field) {
6650       S.Diag(Field->getLocation(),
6651              diag::note_deleted_special_member_class_subobject)
6652         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6653         << Field << DiagKind << IsDtorCallInCtor;
6654     } else {
6655       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6656       S.Diag(Base->getLocStart(),
6657              diag::note_deleted_special_member_class_subobject)
6658         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6659         << Base->getType() << DiagKind << IsDtorCallInCtor;
6660     }
6661 
6662     if (DiagKind == 1)
6663       S.NoteDeletedFunction(Decl);
6664     // FIXME: Explain inaccessibility if DiagKind == 3.
6665   }
6666 
6667   return true;
6668 }
6669 
6670 /// Check whether we should delete a special member function due to having a
6671 /// direct or virtual base class or non-static data member of class type M.
6672 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6673     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6674   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6675   bool IsMutable = Field && Field->isMutable();
6676 
6677   // C++11 [class.ctor]p5:
6678   // -- any direct or virtual base class, or non-static data member with no
6679   //    brace-or-equal-initializer, has class type M (or array thereof) and
6680   //    either M has no default constructor or overload resolution as applied
6681   //    to M's default constructor results in an ambiguity or in a function
6682   //    that is deleted or inaccessible
6683   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6684   // -- a direct or virtual base class B that cannot be copied/moved because
6685   //    overload resolution, as applied to B's corresponding special member,
6686   //    results in an ambiguity or a function that is deleted or inaccessible
6687   //    from the defaulted special member
6688   // C++11 [class.dtor]p5:
6689   // -- any direct or virtual base class [...] has a type with a destructor
6690   //    that is deleted or inaccessible
6691   if (!(CSM == Sema::CXXDefaultConstructor &&
6692         Field && Field->hasInClassInitializer()) &&
6693       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6694                                    false))
6695     return true;
6696 
6697   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6698   // -- any direct or virtual base class or non-static data member has a
6699   //    type with a destructor that is deleted or inaccessible
6700   if (IsConstructor) {
6701     Sema::SpecialMemberOverloadResult SMOR =
6702         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6703                               false, false, false, false, false);
6704     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6705       return true;
6706   }
6707 
6708   return false;
6709 }
6710 
6711 /// Check whether we should delete a special member function due to the class
6712 /// having a particular direct or virtual base class.
6713 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6714   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6715   // If program is correct, BaseClass cannot be null, but if it is, the error
6716   // must be reported elsewhere.
6717   if (!BaseClass)
6718     return false;
6719   // If we have an inheriting constructor, check whether we're calling an
6720   // inherited constructor instead of a default constructor.
6721   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6722   if (auto *BaseCtor = SMOR.getMethod()) {
6723     // Note that we do not check access along this path; other than that,
6724     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6725     // FIXME: Check that the base has a usable destructor! Sink this into
6726     // shouldDeleteForClassSubobject.
6727     if (BaseCtor->isDeleted() && Diagnose) {
6728       S.Diag(Base->getLocStart(),
6729              diag::note_deleted_special_member_class_subobject)
6730         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6731         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6732       S.NoteDeletedFunction(BaseCtor);
6733     }
6734     return BaseCtor->isDeleted();
6735   }
6736   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6737 }
6738 
6739 /// Check whether we should delete a special member function due to the class
6740 /// having a particular non-static data member.
6741 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6742   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6743   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6744 
6745   if (CSM == Sema::CXXDefaultConstructor) {
6746     // For a default constructor, all references must be initialized in-class
6747     // and, if a union, it must have a non-const member.
6748     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6749       if (Diagnose)
6750         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6751           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6752       return true;
6753     }
6754     // C++11 [class.ctor]p5: any non-variant non-static data member of
6755     // const-qualified type (or array thereof) with no
6756     // brace-or-equal-initializer does not have a user-provided default
6757     // constructor.
6758     if (!inUnion() && FieldType.isConstQualified() &&
6759         !FD->hasInClassInitializer() &&
6760         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6761       if (Diagnose)
6762         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6763           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6764       return true;
6765     }
6766 
6767     if (inUnion() && !FieldType.isConstQualified())
6768       AllFieldsAreConst = false;
6769   } else if (CSM == Sema::CXXCopyConstructor) {
6770     // For a copy constructor, data members must not be of rvalue reference
6771     // type.
6772     if (FieldType->isRValueReferenceType()) {
6773       if (Diagnose)
6774         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6775           << MD->getParent() << FD << FieldType;
6776       return true;
6777     }
6778   } else if (IsAssignment) {
6779     // For an assignment operator, data members must not be of reference type.
6780     if (FieldType->isReferenceType()) {
6781       if (Diagnose)
6782         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6783           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6784       return true;
6785     }
6786     if (!FieldRecord && FieldType.isConstQualified()) {
6787       // C++11 [class.copy]p23:
6788       // -- a non-static data member of const non-class type (or array thereof)
6789       if (Diagnose)
6790         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6791           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6792       return true;
6793     }
6794   }
6795 
6796   if (FieldRecord) {
6797     // Some additional restrictions exist on the variant members.
6798     if (!inUnion() && FieldRecord->isUnion() &&
6799         FieldRecord->isAnonymousStructOrUnion()) {
6800       bool AllVariantFieldsAreConst = true;
6801 
6802       // FIXME: Handle anonymous unions declared within anonymous unions.
6803       for (auto *UI : FieldRecord->fields()) {
6804         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6805 
6806         if (!UnionFieldType.isConstQualified())
6807           AllVariantFieldsAreConst = false;
6808 
6809         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6810         if (UnionFieldRecord &&
6811             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6812                                           UnionFieldType.getCVRQualifiers()))
6813           return true;
6814       }
6815 
6816       // At least one member in each anonymous union must be non-const
6817       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6818           !FieldRecord->field_empty()) {
6819         if (Diagnose)
6820           S.Diag(FieldRecord->getLocation(),
6821                  diag::note_deleted_default_ctor_all_const)
6822             << !!ICI << MD->getParent() << /*anonymous union*/1;
6823         return true;
6824       }
6825 
6826       // Don't check the implicit member of the anonymous union type.
6827       // This is technically non-conformant, but sanity demands it.
6828       return false;
6829     }
6830 
6831     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6832                                       FieldType.getCVRQualifiers()))
6833       return true;
6834   }
6835 
6836   return false;
6837 }
6838 
6839 /// C++11 [class.ctor] p5:
6840 ///   A defaulted default constructor for a class X is defined as deleted if
6841 /// X is a union and all of its variant members are of const-qualified type.
6842 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6843   // This is a silly definition, because it gives an empty union a deleted
6844   // default constructor. Don't do that.
6845   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6846     bool AnyFields = false;
6847     for (auto *F : MD->getParent()->fields())
6848       if ((AnyFields = !F->isUnnamedBitfield()))
6849         break;
6850     if (!AnyFields)
6851       return false;
6852     if (Diagnose)
6853       S.Diag(MD->getParent()->getLocation(),
6854              diag::note_deleted_default_ctor_all_const)
6855         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6856     return true;
6857   }
6858   return false;
6859 }
6860 
6861 /// Determine whether a defaulted special member function should be defined as
6862 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6863 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6864 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6865                                      InheritedConstructorInfo *ICI,
6866                                      bool Diagnose) {
6867   if (MD->isInvalidDecl())
6868     return false;
6869   CXXRecordDecl *RD = MD->getParent();
6870   assert(!RD->isDependentType() && "do deletion after instantiation");
6871   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6872     return false;
6873 
6874   // C++11 [expr.lambda.prim]p19:
6875   //   The closure type associated with a lambda-expression has a
6876   //   deleted (8.4.3) default constructor and a deleted copy
6877   //   assignment operator.
6878   if (RD->isLambda() &&
6879       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6880     if (Diagnose)
6881       Diag(RD->getLocation(), diag::note_lambda_decl);
6882     return true;
6883   }
6884 
6885   // For an anonymous struct or union, the copy and assignment special members
6886   // will never be used, so skip the check. For an anonymous union declared at
6887   // namespace scope, the constructor and destructor are used.
6888   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6889       RD->isAnonymousStructOrUnion())
6890     return false;
6891 
6892   // C++11 [class.copy]p7, p18:
6893   //   If the class definition declares a move constructor or move assignment
6894   //   operator, an implicitly declared copy constructor or copy assignment
6895   //   operator is defined as deleted.
6896   if (MD->isImplicit() &&
6897       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6898     CXXMethodDecl *UserDeclaredMove = nullptr;
6899 
6900     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6901     // deletion of the corresponding copy operation, not both copy operations.
6902     // MSVC 2015 has adopted the standards conforming behavior.
6903     bool DeletesOnlyMatchingCopy =
6904         getLangOpts().MSVCCompat &&
6905         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6906 
6907     if (RD->hasUserDeclaredMoveConstructor() &&
6908         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6909       if (!Diagnose) return true;
6910 
6911       // Find any user-declared move constructor.
6912       for (auto *I : RD->ctors()) {
6913         if (I->isMoveConstructor()) {
6914           UserDeclaredMove = I;
6915           break;
6916         }
6917       }
6918       assert(UserDeclaredMove);
6919     } else if (RD->hasUserDeclaredMoveAssignment() &&
6920                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6921       if (!Diagnose) return true;
6922 
6923       // Find any user-declared move assignment operator.
6924       for (auto *I : RD->methods()) {
6925         if (I->isMoveAssignmentOperator()) {
6926           UserDeclaredMove = I;
6927           break;
6928         }
6929       }
6930       assert(UserDeclaredMove);
6931     }
6932 
6933     if (UserDeclaredMove) {
6934       Diag(UserDeclaredMove->getLocation(),
6935            diag::note_deleted_copy_user_declared_move)
6936         << (CSM == CXXCopyAssignment) << RD
6937         << UserDeclaredMove->isMoveAssignmentOperator();
6938       return true;
6939     }
6940   }
6941 
6942   // Do access control from the special member function
6943   ContextRAII MethodContext(*this, MD);
6944 
6945   // C++11 [class.dtor]p5:
6946   // -- for a virtual destructor, lookup of the non-array deallocation function
6947   //    results in an ambiguity or in a function that is deleted or inaccessible
6948   if (CSM == CXXDestructor && MD->isVirtual()) {
6949     FunctionDecl *OperatorDelete = nullptr;
6950     DeclarationName Name =
6951       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6952     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6953                                  OperatorDelete, /*Diagnose*/false)) {
6954       if (Diagnose)
6955         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6956       return true;
6957     }
6958   }
6959 
6960   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6961 
6962   // Per DR1611, do not consider virtual bases of constructors of abstract
6963   // classes, since we are not going to construct them.
6964   // Per DR1658, do not consider virtual bases of destructors of abstract
6965   // classes either.
6966   // Per DR2180, for assignment operators we only assign (and thus only
6967   // consider) direct bases.
6968   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6969                                  : SMI.VisitPotentiallyConstructedBases))
6970     return true;
6971 
6972   if (SMI.shouldDeleteForAllConstMembers())
6973     return true;
6974 
6975   if (getLangOpts().CUDA) {
6976     // We should delete the special member in CUDA mode if target inference
6977     // failed.
6978     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6979                                                    Diagnose);
6980   }
6981 
6982   return false;
6983 }
6984 
6985 /// Perform lookup for a special member of the specified kind, and determine
6986 /// whether it is trivial. If the triviality can be determined without the
6987 /// lookup, skip it. This is intended for use when determining whether a
6988 /// special member of a containing object is trivial, and thus does not ever
6989 /// perform overload resolution for default constructors.
6990 ///
6991 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6992 /// member that was most likely to be intended to be trivial, if any.
6993 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6994                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6995                                      bool ConstRHS, CXXMethodDecl **Selected) {
6996   if (Selected)
6997     *Selected = nullptr;
6998 
6999   switch (CSM) {
7000   case Sema::CXXInvalid:
7001     llvm_unreachable("not a special member");
7002 
7003   case Sema::CXXDefaultConstructor:
7004     // C++11 [class.ctor]p5:
7005     //   A default constructor is trivial if:
7006     //    - all the [direct subobjects] have trivial default constructors
7007     //
7008     // Note, no overload resolution is performed in this case.
7009     if (RD->hasTrivialDefaultConstructor())
7010       return true;
7011 
7012     if (Selected) {
7013       // If there's a default constructor which could have been trivial, dig it
7014       // out. Otherwise, if there's any user-provided default constructor, point
7015       // to that as an example of why there's not a trivial one.
7016       CXXConstructorDecl *DefCtor = nullptr;
7017       if (RD->needsImplicitDefaultConstructor())
7018         S.DeclareImplicitDefaultConstructor(RD);
7019       for (auto *CI : RD->ctors()) {
7020         if (!CI->isDefaultConstructor())
7021           continue;
7022         DefCtor = CI;
7023         if (!DefCtor->isUserProvided())
7024           break;
7025       }
7026 
7027       *Selected = DefCtor;
7028     }
7029 
7030     return false;
7031 
7032   case Sema::CXXDestructor:
7033     // C++11 [class.dtor]p5:
7034     //   A destructor is trivial if:
7035     //    - all the direct [subobjects] have trivial destructors
7036     if (RD->hasTrivialDestructor())
7037       return true;
7038 
7039     if (Selected) {
7040       if (RD->needsImplicitDestructor())
7041         S.DeclareImplicitDestructor(RD);
7042       *Selected = RD->getDestructor();
7043     }
7044 
7045     return false;
7046 
7047   case Sema::CXXCopyConstructor:
7048     // C++11 [class.copy]p12:
7049     //   A copy constructor is trivial if:
7050     //    - the constructor selected to copy each direct [subobject] is trivial
7051     if (RD->hasTrivialCopyConstructor()) {
7052       if (Quals == Qualifiers::Const)
7053         // We must either select the trivial copy constructor or reach an
7054         // ambiguity; no need to actually perform overload resolution.
7055         return true;
7056     } else if (!Selected) {
7057       return false;
7058     }
7059     // In C++98, we are not supposed to perform overload resolution here, but we
7060     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7061     // cases like B as having a non-trivial copy constructor:
7062     //   struct A { template<typename T> A(T&); };
7063     //   struct B { mutable A a; };
7064     goto NeedOverloadResolution;
7065 
7066   case Sema::CXXCopyAssignment:
7067     // C++11 [class.copy]p25:
7068     //   A copy assignment operator is trivial if:
7069     //    - the assignment operator selected to copy each direct [subobject] is
7070     //      trivial
7071     if (RD->hasTrivialCopyAssignment()) {
7072       if (Quals == Qualifiers::Const)
7073         return true;
7074     } else if (!Selected) {
7075       return false;
7076     }
7077     // In C++98, we are not supposed to perform overload resolution here, but we
7078     // treat that as a language defect.
7079     goto NeedOverloadResolution;
7080 
7081   case Sema::CXXMoveConstructor:
7082   case Sema::CXXMoveAssignment:
7083   NeedOverloadResolution:
7084     Sema::SpecialMemberOverloadResult SMOR =
7085         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7086 
7087     // The standard doesn't describe how to behave if the lookup is ambiguous.
7088     // We treat it as not making the member non-trivial, just like the standard
7089     // mandates for the default constructor. This should rarely matter, because
7090     // the member will also be deleted.
7091     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7092       return true;
7093 
7094     if (!SMOR.getMethod()) {
7095       assert(SMOR.getKind() ==
7096              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7097       return false;
7098     }
7099 
7100     // We deliberately don't check if we found a deleted special member. We're
7101     // not supposed to!
7102     if (Selected)
7103       *Selected = SMOR.getMethod();
7104     return SMOR.getMethod()->isTrivial();
7105   }
7106 
7107   llvm_unreachable("unknown special method kind");
7108 }
7109 
7110 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7111   for (auto *CI : RD->ctors())
7112     if (!CI->isImplicit())
7113       return CI;
7114 
7115   // Look for constructor templates.
7116   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7117   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7118     if (CXXConstructorDecl *CD =
7119           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7120       return CD;
7121   }
7122 
7123   return nullptr;
7124 }
7125 
7126 /// The kind of subobject we are checking for triviality. The values of this
7127 /// enumeration are used in diagnostics.
7128 enum TrivialSubobjectKind {
7129   /// The subobject is a base class.
7130   TSK_BaseClass,
7131   /// The subobject is a non-static data member.
7132   TSK_Field,
7133   /// The object is actually the complete object.
7134   TSK_CompleteObject
7135 };
7136 
7137 /// Check whether the special member selected for a given type would be trivial.
7138 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7139                                       QualType SubType, bool ConstRHS,
7140                                       Sema::CXXSpecialMember CSM,
7141                                       TrivialSubobjectKind Kind,
7142                                       bool Diagnose) {
7143   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7144   if (!SubRD)
7145     return true;
7146 
7147   CXXMethodDecl *Selected;
7148   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7149                                ConstRHS, Diagnose ? &Selected : nullptr))
7150     return true;
7151 
7152   if (Diagnose) {
7153     if (ConstRHS)
7154       SubType.addConst();
7155 
7156     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7157       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7158         << Kind << SubType.getUnqualifiedType();
7159       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7160         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7161     } else if (!Selected)
7162       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7163         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7164     else if (Selected->isUserProvided()) {
7165       if (Kind == TSK_CompleteObject)
7166         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7167           << Kind << SubType.getUnqualifiedType() << CSM;
7168       else {
7169         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7170           << Kind << SubType.getUnqualifiedType() << CSM;
7171         S.Diag(Selected->getLocation(), diag::note_declared_at);
7172       }
7173     } else {
7174       if (Kind != TSK_CompleteObject)
7175         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7176           << Kind << SubType.getUnqualifiedType() << CSM;
7177 
7178       // Explain why the defaulted or deleted special member isn't trivial.
7179       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7180     }
7181   }
7182 
7183   return false;
7184 }
7185 
7186 /// Check whether the members of a class type allow a special member to be
7187 /// trivial.
7188 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7189                                      Sema::CXXSpecialMember CSM,
7190                                      bool ConstArg, bool Diagnose) {
7191   for (const auto *FI : RD->fields()) {
7192     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7193       continue;
7194 
7195     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7196 
7197     // Pretend anonymous struct or union members are members of this class.
7198     if (FI->isAnonymousStructOrUnion()) {
7199       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7200                                     CSM, ConstArg, Diagnose))
7201         return false;
7202       continue;
7203     }
7204 
7205     // C++11 [class.ctor]p5:
7206     //   A default constructor is trivial if [...]
7207     //    -- no non-static data member of its class has a
7208     //       brace-or-equal-initializer
7209     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7210       if (Diagnose)
7211         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7212       return false;
7213     }
7214 
7215     // Objective C ARC 4.3.5:
7216     //   [...] nontrivally ownership-qualified types are [...] not trivially
7217     //   default constructible, copy constructible, move constructible, copy
7218     //   assignable, move assignable, or destructible [...]
7219     if (FieldType.hasNonTrivialObjCLifetime()) {
7220       if (Diagnose)
7221         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7222           << RD << FieldType.getObjCLifetime();
7223       return false;
7224     }
7225 
7226     bool ConstRHS = ConstArg && !FI->isMutable();
7227     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7228                                    CSM, TSK_Field, Diagnose))
7229       return false;
7230   }
7231 
7232   return true;
7233 }
7234 
7235 /// Diagnose why the specified class does not have a trivial special member of
7236 /// the given kind.
7237 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7238   QualType Ty = Context.getRecordType(RD);
7239 
7240   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7241   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7242                             TSK_CompleteObject, /*Diagnose*/true);
7243 }
7244 
7245 /// Determine whether a defaulted or deleted special member function is trivial,
7246 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7247 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7248 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7249                                   bool Diagnose) {
7250   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7251 
7252   CXXRecordDecl *RD = MD->getParent();
7253 
7254   bool ConstArg = false;
7255 
7256   // C++11 [class.copy]p12, p25: [DR1593]
7257   //   A [special member] is trivial if [...] its parameter-type-list is
7258   //   equivalent to the parameter-type-list of an implicit declaration [...]
7259   switch (CSM) {
7260   case CXXDefaultConstructor:
7261   case CXXDestructor:
7262     // Trivial default constructors and destructors cannot have parameters.
7263     break;
7264 
7265   case CXXCopyConstructor:
7266   case CXXCopyAssignment: {
7267     // Trivial copy operations always have const, non-volatile parameter types.
7268     ConstArg = true;
7269     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7270     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7271     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7272       if (Diagnose)
7273         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7274           << Param0->getSourceRange() << Param0->getType()
7275           << Context.getLValueReferenceType(
7276                Context.getRecordType(RD).withConst());
7277       return false;
7278     }
7279     break;
7280   }
7281 
7282   case CXXMoveConstructor:
7283   case CXXMoveAssignment: {
7284     // Trivial move operations always have non-cv-qualified parameters.
7285     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7286     const RValueReferenceType *RT =
7287       Param0->getType()->getAs<RValueReferenceType>();
7288     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7289       if (Diagnose)
7290         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7291           << Param0->getSourceRange() << Param0->getType()
7292           << Context.getRValueReferenceType(Context.getRecordType(RD));
7293       return false;
7294     }
7295     break;
7296   }
7297 
7298   case CXXInvalid:
7299     llvm_unreachable("not a special member");
7300   }
7301 
7302   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7303     if (Diagnose)
7304       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7305            diag::note_nontrivial_default_arg)
7306         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7307     return false;
7308   }
7309   if (MD->isVariadic()) {
7310     if (Diagnose)
7311       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7312     return false;
7313   }
7314 
7315   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7316   //   A copy/move [constructor or assignment operator] is trivial if
7317   //    -- the [member] selected to copy/move each direct base class subobject
7318   //       is trivial
7319   //
7320   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7321   //   A [default constructor or destructor] is trivial if
7322   //    -- all the direct base classes have trivial [default constructors or
7323   //       destructors]
7324   for (const auto &BI : RD->bases())
7325     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7326                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7327       return false;
7328 
7329   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7330   //   A copy/move [constructor or assignment operator] for a class X is
7331   //   trivial if
7332   //    -- for each non-static data member of X that is of class type (or array
7333   //       thereof), the constructor selected to copy/move that member is
7334   //       trivial
7335   //
7336   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7337   //   A [default constructor or destructor] is trivial if
7338   //    -- for all of the non-static data members of its class that are of class
7339   //       type (or array thereof), each such class has a trivial [default
7340   //       constructor or destructor]
7341   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7342     return false;
7343 
7344   // C++11 [class.dtor]p5:
7345   //   A destructor is trivial if [...]
7346   //    -- the destructor is not virtual
7347   if (CSM == CXXDestructor && MD->isVirtual()) {
7348     if (Diagnose)
7349       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7350     return false;
7351   }
7352 
7353   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7354   //   A [special member] for class X is trivial if [...]
7355   //    -- class X has no virtual functions and no virtual base classes
7356   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7357     if (!Diagnose)
7358       return false;
7359 
7360     if (RD->getNumVBases()) {
7361       // Check for virtual bases. We already know that the corresponding
7362       // member in all bases is trivial, so vbases must all be direct.
7363       CXXBaseSpecifier &BS = *RD->vbases_begin();
7364       assert(BS.isVirtual());
7365       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7366       return false;
7367     }
7368 
7369     // Must have a virtual method.
7370     for (const auto *MI : RD->methods()) {
7371       if (MI->isVirtual()) {
7372         SourceLocation MLoc = MI->getLocStart();
7373         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7374         return false;
7375       }
7376     }
7377 
7378     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7379   }
7380 
7381   // Looks like it's trivial!
7382   return true;
7383 }
7384 
7385 namespace {
7386 struct FindHiddenVirtualMethod {
7387   Sema *S;
7388   CXXMethodDecl *Method;
7389   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7390   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7391 
7392 private:
7393   /// Check whether any most overriden method from MD in Methods
7394   static bool CheckMostOverridenMethods(
7395       const CXXMethodDecl *MD,
7396       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7397     if (MD->size_overridden_methods() == 0)
7398       return Methods.count(MD->getCanonicalDecl());
7399     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7400                                         E = MD->end_overridden_methods();
7401          I != E; ++I)
7402       if (CheckMostOverridenMethods(*I, Methods))
7403         return true;
7404     return false;
7405   }
7406 
7407 public:
7408   /// Member lookup function that determines whether a given C++
7409   /// method overloads virtual methods in a base class without overriding any,
7410   /// to be used with CXXRecordDecl::lookupInBases().
7411   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7412     RecordDecl *BaseRecord =
7413         Specifier->getType()->getAs<RecordType>()->getDecl();
7414 
7415     DeclarationName Name = Method->getDeclName();
7416     assert(Name.getNameKind() == DeclarationName::Identifier);
7417 
7418     bool foundSameNameMethod = false;
7419     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7420     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7421          Path.Decls = Path.Decls.slice(1)) {
7422       NamedDecl *D = Path.Decls.front();
7423       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7424         MD = MD->getCanonicalDecl();
7425         foundSameNameMethod = true;
7426         // Interested only in hidden virtual methods.
7427         if (!MD->isVirtual())
7428           continue;
7429         // If the method we are checking overrides a method from its base
7430         // don't warn about the other overloaded methods. Clang deviates from
7431         // GCC by only diagnosing overloads of inherited virtual functions that
7432         // do not override any other virtual functions in the base. GCC's
7433         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7434         // function from a base class. These cases may be better served by a
7435         // warning (not specific to virtual functions) on call sites when the
7436         // call would select a different function from the base class, were it
7437         // visible.
7438         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7439         if (!S->IsOverload(Method, MD, false))
7440           return true;
7441         // Collect the overload only if its hidden.
7442         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7443           overloadedMethods.push_back(MD);
7444       }
7445     }
7446 
7447     if (foundSameNameMethod)
7448       OverloadedMethods.append(overloadedMethods.begin(),
7449                                overloadedMethods.end());
7450     return foundSameNameMethod;
7451   }
7452 };
7453 } // end anonymous namespace
7454 
7455 /// \brief Add the most overriden methods from MD to Methods
7456 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7457                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7458   if (MD->size_overridden_methods() == 0)
7459     Methods.insert(MD->getCanonicalDecl());
7460   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7461                                       E = MD->end_overridden_methods();
7462        I != E; ++I)
7463     AddMostOverridenMethods(*I, Methods);
7464 }
7465 
7466 /// \brief Check if a method overloads virtual methods in a base class without
7467 /// overriding any.
7468 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7469                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7470   if (!MD->getDeclName().isIdentifier())
7471     return;
7472 
7473   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7474                      /*bool RecordPaths=*/false,
7475                      /*bool DetectVirtual=*/false);
7476   FindHiddenVirtualMethod FHVM;
7477   FHVM.Method = MD;
7478   FHVM.S = this;
7479 
7480   // Keep the base methods that were overriden or introduced in the subclass
7481   // by 'using' in a set. A base method not in this set is hidden.
7482   CXXRecordDecl *DC = MD->getParent();
7483   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7484   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7485     NamedDecl *ND = *I;
7486     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7487       ND = shad->getTargetDecl();
7488     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7489       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7490   }
7491 
7492   if (DC->lookupInBases(FHVM, Paths))
7493     OverloadedMethods = FHVM.OverloadedMethods;
7494 }
7495 
7496 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7497                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7498   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7499     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7500     PartialDiagnostic PD = PDiag(
7501          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7502     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7503     Diag(overloadedMD->getLocation(), PD);
7504   }
7505 }
7506 
7507 /// \brief Diagnose methods which overload virtual methods in a base class
7508 /// without overriding any.
7509 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7510   if (MD->isInvalidDecl())
7511     return;
7512 
7513   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7514     return;
7515 
7516   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7517   FindHiddenVirtualMethods(MD, OverloadedMethods);
7518   if (!OverloadedMethods.empty()) {
7519     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7520       << MD << (OverloadedMethods.size() > 1);
7521 
7522     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7523   }
7524 }
7525 
7526 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7527                                              Decl *TagDecl,
7528                                              SourceLocation LBrac,
7529                                              SourceLocation RBrac,
7530                                              AttributeList *AttrList) {
7531   if (!TagDecl)
7532     return;
7533 
7534   AdjustDeclIfTemplate(TagDecl);
7535 
7536   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7537     if (l->getKind() != AttributeList::AT_Visibility)
7538       continue;
7539     l->setInvalid();
7540     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7541       l->getName();
7542   }
7543 
7544   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7545               // strict aliasing violation!
7546               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7547               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7548 
7549   CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7550 }
7551 
7552 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7553 /// special functions, such as the default constructor, copy
7554 /// constructor, or destructor, to the given C++ class (C++
7555 /// [special]p1).  This routine can only be executed just before the
7556 /// definition of the class is complete.
7557 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7558   if (ClassDecl->needsImplicitDefaultConstructor()) {
7559     ++ASTContext::NumImplicitDefaultConstructors;
7560 
7561     if (ClassDecl->hasInheritedConstructor())
7562       DeclareImplicitDefaultConstructor(ClassDecl);
7563   }
7564 
7565   if (ClassDecl->needsImplicitCopyConstructor()) {
7566     ++ASTContext::NumImplicitCopyConstructors;
7567 
7568     // If the properties or semantics of the copy constructor couldn't be
7569     // determined while the class was being declared, force a declaration
7570     // of it now.
7571     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7572         ClassDecl->hasInheritedConstructor())
7573       DeclareImplicitCopyConstructor(ClassDecl);
7574     // For the MS ABI we need to know whether the copy ctor is deleted. A
7575     // prerequisite for deleting the implicit copy ctor is that the class has a
7576     // move ctor or move assignment that is either user-declared or whose
7577     // semantics are inherited from a subobject. FIXME: We should provide a more
7578     // direct way for CodeGen to ask whether the constructor was deleted.
7579     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7580              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7581               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7582               ClassDecl->hasUserDeclaredMoveAssignment() ||
7583               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7584       DeclareImplicitCopyConstructor(ClassDecl);
7585   }
7586 
7587   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7588     ++ASTContext::NumImplicitMoveConstructors;
7589 
7590     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7591         ClassDecl->hasInheritedConstructor())
7592       DeclareImplicitMoveConstructor(ClassDecl);
7593   }
7594 
7595   if (ClassDecl->needsImplicitCopyAssignment()) {
7596     ++ASTContext::NumImplicitCopyAssignmentOperators;
7597 
7598     // If we have a dynamic class, then the copy assignment operator may be
7599     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7600     // it shows up in the right place in the vtable and that we diagnose
7601     // problems with the implicit exception specification.
7602     if (ClassDecl->isDynamicClass() ||
7603         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7604         ClassDecl->hasInheritedAssignment())
7605       DeclareImplicitCopyAssignment(ClassDecl);
7606   }
7607 
7608   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7609     ++ASTContext::NumImplicitMoveAssignmentOperators;
7610 
7611     // Likewise for the move assignment operator.
7612     if (ClassDecl->isDynamicClass() ||
7613         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7614         ClassDecl->hasInheritedAssignment())
7615       DeclareImplicitMoveAssignment(ClassDecl);
7616   }
7617 
7618   if (ClassDecl->needsImplicitDestructor()) {
7619     ++ASTContext::NumImplicitDestructors;
7620 
7621     // If we have a dynamic class, then the destructor may be virtual, so we
7622     // have to declare the destructor immediately. This ensures that, e.g., it
7623     // shows up in the right place in the vtable and that we diagnose problems
7624     // with the implicit exception specification.
7625     if (ClassDecl->isDynamicClass() ||
7626         ClassDecl->needsOverloadResolutionForDestructor())
7627       DeclareImplicitDestructor(ClassDecl);
7628   }
7629 }
7630 
7631 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7632   if (!D)
7633     return 0;
7634 
7635   // The order of template parameters is not important here. All names
7636   // get added to the same scope.
7637   SmallVector<TemplateParameterList *, 4> ParameterLists;
7638 
7639   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7640     D = TD->getTemplatedDecl();
7641 
7642   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7643     ParameterLists.push_back(PSD->getTemplateParameters());
7644 
7645   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7646     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7647       ParameterLists.push_back(DD->getTemplateParameterList(i));
7648 
7649     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7650       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7651         ParameterLists.push_back(FTD->getTemplateParameters());
7652     }
7653   }
7654 
7655   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7656     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7657       ParameterLists.push_back(TD->getTemplateParameterList(i));
7658 
7659     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7660       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7661         ParameterLists.push_back(CTD->getTemplateParameters());
7662     }
7663   }
7664 
7665   unsigned Count = 0;
7666   for (TemplateParameterList *Params : ParameterLists) {
7667     if (Params->size() > 0)
7668       // Ignore explicit specializations; they don't contribute to the template
7669       // depth.
7670       ++Count;
7671     for (NamedDecl *Param : *Params) {
7672       if (Param->getDeclName()) {
7673         S->AddDecl(Param);
7674         IdResolver.AddDecl(Param);
7675       }
7676     }
7677   }
7678 
7679   return Count;
7680 }
7681 
7682 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7683   if (!RecordD) return;
7684   AdjustDeclIfTemplate(RecordD);
7685   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7686   PushDeclContext(S, Record);
7687 }
7688 
7689 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7690   if (!RecordD) return;
7691   PopDeclContext();
7692 }
7693 
7694 /// This is used to implement the constant expression evaluation part of the
7695 /// attribute enable_if extension. There is nothing in standard C++ which would
7696 /// require reentering parameters.
7697 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7698   if (!Param)
7699     return;
7700 
7701   S->AddDecl(Param);
7702   if (Param->getDeclName())
7703     IdResolver.AddDecl(Param);
7704 }
7705 
7706 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7707 /// parsing a top-level (non-nested) C++ class, and we are now
7708 /// parsing those parts of the given Method declaration that could
7709 /// not be parsed earlier (C++ [class.mem]p2), such as default
7710 /// arguments. This action should enter the scope of the given
7711 /// Method declaration as if we had just parsed the qualified method
7712 /// name. However, it should not bring the parameters into scope;
7713 /// that will be performed by ActOnDelayedCXXMethodParameter.
7714 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7715 }
7716 
7717 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7718 /// C++ method declaration. We're (re-)introducing the given
7719 /// function parameter into scope for use in parsing later parts of
7720 /// the method declaration. For example, we could see an
7721 /// ActOnParamDefaultArgument event for this parameter.
7722 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7723   if (!ParamD)
7724     return;
7725 
7726   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7727 
7728   // If this parameter has an unparsed default argument, clear it out
7729   // to make way for the parsed default argument.
7730   if (Param->hasUnparsedDefaultArg())
7731     Param->setDefaultArg(nullptr);
7732 
7733   S->AddDecl(Param);
7734   if (Param->getDeclName())
7735     IdResolver.AddDecl(Param);
7736 }
7737 
7738 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7739 /// processing the delayed method declaration for Method. The method
7740 /// declaration is now considered finished. There may be a separate
7741 /// ActOnStartOfFunctionDef action later (not necessarily
7742 /// immediately!) for this method, if it was also defined inside the
7743 /// class body.
7744 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7745   if (!MethodD)
7746     return;
7747 
7748   AdjustDeclIfTemplate(MethodD);
7749 
7750   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7751 
7752   // Now that we have our default arguments, check the constructor
7753   // again. It could produce additional diagnostics or affect whether
7754   // the class has implicitly-declared destructors, among other
7755   // things.
7756   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7757     CheckConstructor(Constructor);
7758 
7759   // Check the default arguments, which we may have added.
7760   if (!Method->isInvalidDecl())
7761     CheckCXXDefaultArguments(Method);
7762 }
7763 
7764 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7765 /// the well-formedness of the constructor declarator @p D with type @p
7766 /// R. If there are any errors in the declarator, this routine will
7767 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7768 /// will be updated to reflect a well-formed type for the constructor and
7769 /// returned.
7770 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7771                                           StorageClass &SC) {
7772   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7773 
7774   // C++ [class.ctor]p3:
7775   //   A constructor shall not be virtual (10.3) or static (9.4). A
7776   //   constructor can be invoked for a const, volatile or const
7777   //   volatile object. A constructor shall not be declared const,
7778   //   volatile, or const volatile (9.3.2).
7779   if (isVirtual) {
7780     if (!D.isInvalidType())
7781       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7782         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7783         << SourceRange(D.getIdentifierLoc());
7784     D.setInvalidType();
7785   }
7786   if (SC == SC_Static) {
7787     if (!D.isInvalidType())
7788       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7789         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7790         << SourceRange(D.getIdentifierLoc());
7791     D.setInvalidType();
7792     SC = SC_None;
7793   }
7794 
7795   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7796     diagnoseIgnoredQualifiers(
7797         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7798         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7799         D.getDeclSpec().getRestrictSpecLoc(),
7800         D.getDeclSpec().getAtomicSpecLoc());
7801     D.setInvalidType();
7802   }
7803 
7804   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7805   if (FTI.TypeQuals != 0) {
7806     if (FTI.TypeQuals & Qualifiers::Const)
7807       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7808         << "const" << SourceRange(D.getIdentifierLoc());
7809     if (FTI.TypeQuals & Qualifiers::Volatile)
7810       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7811         << "volatile" << SourceRange(D.getIdentifierLoc());
7812     if (FTI.TypeQuals & Qualifiers::Restrict)
7813       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7814         << "restrict" << SourceRange(D.getIdentifierLoc());
7815     D.setInvalidType();
7816   }
7817 
7818   // C++0x [class.ctor]p4:
7819   //   A constructor shall not be declared with a ref-qualifier.
7820   if (FTI.hasRefQualifier()) {
7821     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7822       << FTI.RefQualifierIsLValueRef
7823       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7824     D.setInvalidType();
7825   }
7826 
7827   // Rebuild the function type "R" without any type qualifiers (in
7828   // case any of the errors above fired) and with "void" as the
7829   // return type, since constructors don't have return types.
7830   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7831   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7832     return R;
7833 
7834   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7835   EPI.TypeQuals = 0;
7836   EPI.RefQualifier = RQ_None;
7837 
7838   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7839 }
7840 
7841 /// CheckConstructor - Checks a fully-formed constructor for
7842 /// well-formedness, issuing any diagnostics required. Returns true if
7843 /// the constructor declarator is invalid.
7844 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7845   CXXRecordDecl *ClassDecl
7846     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7847   if (!ClassDecl)
7848     return Constructor->setInvalidDecl();
7849 
7850   // C++ [class.copy]p3:
7851   //   A declaration of a constructor for a class X is ill-formed if
7852   //   its first parameter is of type (optionally cv-qualified) X and
7853   //   either there are no other parameters or else all other
7854   //   parameters have default arguments.
7855   if (!Constructor->isInvalidDecl() &&
7856       ((Constructor->getNumParams() == 1) ||
7857        (Constructor->getNumParams() > 1 &&
7858         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7859       Constructor->getTemplateSpecializationKind()
7860                                               != TSK_ImplicitInstantiation) {
7861     QualType ParamType = Constructor->getParamDecl(0)->getType();
7862     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7863     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7864       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7865       const char *ConstRef
7866         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7867                                                         : " const &";
7868       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7869         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7870 
7871       // FIXME: Rather that making the constructor invalid, we should endeavor
7872       // to fix the type.
7873       Constructor->setInvalidDecl();
7874     }
7875   }
7876 }
7877 
7878 /// CheckDestructor - Checks a fully-formed destructor definition for
7879 /// well-formedness, issuing any diagnostics required.  Returns true
7880 /// on error.
7881 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7882   CXXRecordDecl *RD = Destructor->getParent();
7883 
7884   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7885     SourceLocation Loc;
7886 
7887     if (!Destructor->isImplicit())
7888       Loc = Destructor->getLocation();
7889     else
7890       Loc = RD->getLocation();
7891 
7892     // If we have a virtual destructor, look up the deallocation function
7893     if (FunctionDecl *OperatorDelete =
7894             FindDeallocationFunctionForDestructor(Loc, RD)) {
7895       MarkFunctionReferenced(Loc, OperatorDelete);
7896       Destructor->setOperatorDelete(OperatorDelete);
7897     }
7898   }
7899 
7900   return false;
7901 }
7902 
7903 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7904 /// the well-formednes of the destructor declarator @p D with type @p
7905 /// R. If there are any errors in the declarator, this routine will
7906 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7907 /// will be updated to reflect a well-formed type for the destructor and
7908 /// returned.
7909 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7910                                          StorageClass& SC) {
7911   // C++ [class.dtor]p1:
7912   //   [...] A typedef-name that names a class is a class-name
7913   //   (7.1.3); however, a typedef-name that names a class shall not
7914   //   be used as the identifier in the declarator for a destructor
7915   //   declaration.
7916   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7917   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7918     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7919       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7920   else if (const TemplateSpecializationType *TST =
7921              DeclaratorType->getAs<TemplateSpecializationType>())
7922     if (TST->isTypeAlias())
7923       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7924         << DeclaratorType << 1;
7925 
7926   // C++ [class.dtor]p2:
7927   //   A destructor is used to destroy objects of its class type. A
7928   //   destructor takes no parameters, and no return type can be
7929   //   specified for it (not even void). The address of a destructor
7930   //   shall not be taken. A destructor shall not be static. A
7931   //   destructor can be invoked for a const, volatile or const
7932   //   volatile object. A destructor shall not be declared const,
7933   //   volatile or const volatile (9.3.2).
7934   if (SC == SC_Static) {
7935     if (!D.isInvalidType())
7936       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7937         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7938         << SourceRange(D.getIdentifierLoc())
7939         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7940 
7941     SC = SC_None;
7942   }
7943   if (!D.isInvalidType()) {
7944     // Destructors don't have return types, but the parser will
7945     // happily parse something like:
7946     //
7947     //   class X {
7948     //     float ~X();
7949     //   };
7950     //
7951     // The return type will be eliminated later.
7952     if (D.getDeclSpec().hasTypeSpecifier())
7953       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7954         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7955         << SourceRange(D.getIdentifierLoc());
7956     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7957       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7958                                 SourceLocation(),
7959                                 D.getDeclSpec().getConstSpecLoc(),
7960                                 D.getDeclSpec().getVolatileSpecLoc(),
7961                                 D.getDeclSpec().getRestrictSpecLoc(),
7962                                 D.getDeclSpec().getAtomicSpecLoc());
7963       D.setInvalidType();
7964     }
7965   }
7966 
7967   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7968   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7969     if (FTI.TypeQuals & Qualifiers::Const)
7970       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7971         << "const" << SourceRange(D.getIdentifierLoc());
7972     if (FTI.TypeQuals & Qualifiers::Volatile)
7973       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7974         << "volatile" << SourceRange(D.getIdentifierLoc());
7975     if (FTI.TypeQuals & Qualifiers::Restrict)
7976       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7977         << "restrict" << SourceRange(D.getIdentifierLoc());
7978     D.setInvalidType();
7979   }
7980 
7981   // C++0x [class.dtor]p2:
7982   //   A destructor shall not be declared with a ref-qualifier.
7983   if (FTI.hasRefQualifier()) {
7984     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7985       << FTI.RefQualifierIsLValueRef
7986       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7987     D.setInvalidType();
7988   }
7989 
7990   // Make sure we don't have any parameters.
7991   if (FTIHasNonVoidParameters(FTI)) {
7992     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7993 
7994     // Delete the parameters.
7995     FTI.freeParams();
7996     D.setInvalidType();
7997   }
7998 
7999   // Make sure the destructor isn't variadic.
8000   if (FTI.isVariadic) {
8001     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8002     D.setInvalidType();
8003   }
8004 
8005   // Rebuild the function type "R" without any type qualifiers or
8006   // parameters (in case any of the errors above fired) and with
8007   // "void" as the return type, since destructors don't have return
8008   // types.
8009   if (!D.isInvalidType())
8010     return R;
8011 
8012   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8013   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8014   EPI.Variadic = false;
8015   EPI.TypeQuals = 0;
8016   EPI.RefQualifier = RQ_None;
8017   return Context.getFunctionType(Context.VoidTy, None, EPI);
8018 }
8019 
8020 static void extendLeft(SourceRange &R, SourceRange Before) {
8021   if (Before.isInvalid())
8022     return;
8023   R.setBegin(Before.getBegin());
8024   if (R.getEnd().isInvalid())
8025     R.setEnd(Before.getEnd());
8026 }
8027 
8028 static void extendRight(SourceRange &R, SourceRange After) {
8029   if (After.isInvalid())
8030     return;
8031   if (R.getBegin().isInvalid())
8032     R.setBegin(After.getBegin());
8033   R.setEnd(After.getEnd());
8034 }
8035 
8036 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8037 /// well-formednes of the conversion function declarator @p D with
8038 /// type @p R. If there are any errors in the declarator, this routine
8039 /// will emit diagnostics and return true. Otherwise, it will return
8040 /// false. Either way, the type @p R will be updated to reflect a
8041 /// well-formed type for the conversion operator.
8042 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8043                                      StorageClass& SC) {
8044   // C++ [class.conv.fct]p1:
8045   //   Neither parameter types nor return type can be specified. The
8046   //   type of a conversion function (8.3.5) is "function taking no
8047   //   parameter returning conversion-type-id."
8048   if (SC == SC_Static) {
8049     if (!D.isInvalidType())
8050       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8051         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8052         << D.getName().getSourceRange();
8053     D.setInvalidType();
8054     SC = SC_None;
8055   }
8056 
8057   TypeSourceInfo *ConvTSI = nullptr;
8058   QualType ConvType =
8059       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8060 
8061   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
8062     // Conversion functions don't have return types, but the parser will
8063     // happily parse something like:
8064     //
8065     //   class X {
8066     //     float operator bool();
8067     //   };
8068     //
8069     // The return type will be changed later anyway.
8070     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8071       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8072       << SourceRange(D.getIdentifierLoc());
8073     D.setInvalidType();
8074   }
8075 
8076   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8077 
8078   // Make sure we don't have any parameters.
8079   if (Proto->getNumParams() > 0) {
8080     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8081 
8082     // Delete the parameters.
8083     D.getFunctionTypeInfo().freeParams();
8084     D.setInvalidType();
8085   } else if (Proto->isVariadic()) {
8086     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8087     D.setInvalidType();
8088   }
8089 
8090   // Diagnose "&operator bool()" and other such nonsense.  This
8091   // is actually a gcc extension which we don't support.
8092   if (Proto->getReturnType() != ConvType) {
8093     bool NeedsTypedef = false;
8094     SourceRange Before, After;
8095 
8096     // Walk the chunks and extract information on them for our diagnostic.
8097     bool PastFunctionChunk = false;
8098     for (auto &Chunk : D.type_objects()) {
8099       switch (Chunk.Kind) {
8100       case DeclaratorChunk::Function:
8101         if (!PastFunctionChunk) {
8102           if (Chunk.Fun.HasTrailingReturnType) {
8103             TypeSourceInfo *TRT = nullptr;
8104             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8105             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8106           }
8107           PastFunctionChunk = true;
8108           break;
8109         }
8110         // Fall through.
8111       case DeclaratorChunk::Array:
8112         NeedsTypedef = true;
8113         extendRight(After, Chunk.getSourceRange());
8114         break;
8115 
8116       case DeclaratorChunk::Pointer:
8117       case DeclaratorChunk::BlockPointer:
8118       case DeclaratorChunk::Reference:
8119       case DeclaratorChunk::MemberPointer:
8120       case DeclaratorChunk::Pipe:
8121         extendLeft(Before, Chunk.getSourceRange());
8122         break;
8123 
8124       case DeclaratorChunk::Paren:
8125         extendLeft(Before, Chunk.Loc);
8126         extendRight(After, Chunk.EndLoc);
8127         break;
8128       }
8129     }
8130 
8131     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8132                          After.isValid()  ? After.getBegin() :
8133                                             D.getIdentifierLoc();
8134     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8135     DB << Before << After;
8136 
8137     if (!NeedsTypedef) {
8138       DB << /*don't need a typedef*/0;
8139 
8140       // If we can provide a correct fix-it hint, do so.
8141       if (After.isInvalid() && ConvTSI) {
8142         SourceLocation InsertLoc =
8143             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8144         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8145            << FixItHint::CreateInsertionFromRange(
8146                   InsertLoc, CharSourceRange::getTokenRange(Before))
8147            << FixItHint::CreateRemoval(Before);
8148       }
8149     } else if (!Proto->getReturnType()->isDependentType()) {
8150       DB << /*typedef*/1 << Proto->getReturnType();
8151     } else if (getLangOpts().CPlusPlus11) {
8152       DB << /*alias template*/2 << Proto->getReturnType();
8153     } else {
8154       DB << /*might not be fixable*/3;
8155     }
8156 
8157     // Recover by incorporating the other type chunks into the result type.
8158     // Note, this does *not* change the name of the function. This is compatible
8159     // with the GCC extension:
8160     //   struct S { &operator int(); } s;
8161     //   int &r = s.operator int(); // ok in GCC
8162     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8163     ConvType = Proto->getReturnType();
8164   }
8165 
8166   // C++ [class.conv.fct]p4:
8167   //   The conversion-type-id shall not represent a function type nor
8168   //   an array type.
8169   if (ConvType->isArrayType()) {
8170     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8171     ConvType = Context.getPointerType(ConvType);
8172     D.setInvalidType();
8173   } else if (ConvType->isFunctionType()) {
8174     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8175     ConvType = Context.getPointerType(ConvType);
8176     D.setInvalidType();
8177   }
8178 
8179   // Rebuild the function type "R" without any parameters (in case any
8180   // of the errors above fired) and with the conversion type as the
8181   // return type.
8182   if (D.isInvalidType())
8183     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8184 
8185   // C++0x explicit conversion operators.
8186   if (D.getDeclSpec().isExplicitSpecified())
8187     Diag(D.getDeclSpec().getExplicitSpecLoc(),
8188          getLangOpts().CPlusPlus11 ?
8189            diag::warn_cxx98_compat_explicit_conversion_functions :
8190            diag::ext_explicit_conversion_functions)
8191       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8192 }
8193 
8194 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8195 /// the declaration of the given C++ conversion function. This routine
8196 /// is responsible for recording the conversion function in the C++
8197 /// class, if possible.
8198 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8199   assert(Conversion && "Expected to receive a conversion function declaration");
8200 
8201   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8202 
8203   // Make sure we aren't redeclaring the conversion function.
8204   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8205 
8206   // C++ [class.conv.fct]p1:
8207   //   [...] A conversion function is never used to convert a
8208   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8209   //   same object type (or a reference to it), to a (possibly
8210   //   cv-qualified) base class of that type (or a reference to it),
8211   //   or to (possibly cv-qualified) void.
8212   // FIXME: Suppress this warning if the conversion function ends up being a
8213   // virtual function that overrides a virtual function in a base class.
8214   QualType ClassType
8215     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8216   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8217     ConvType = ConvTypeRef->getPointeeType();
8218   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8219       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8220     /* Suppress diagnostics for instantiations. */;
8221   else if (ConvType->isRecordType()) {
8222     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8223     if (ConvType == ClassType)
8224       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8225         << ClassType;
8226     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8227       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8228         <<  ClassType << ConvType;
8229   } else if (ConvType->isVoidType()) {
8230     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8231       << ClassType << ConvType;
8232   }
8233 
8234   if (FunctionTemplateDecl *ConversionTemplate
8235                                 = Conversion->getDescribedFunctionTemplate())
8236     return ConversionTemplate;
8237 
8238   return Conversion;
8239 }
8240 
8241 namespace {
8242 /// Utility class to accumulate and print a diagnostic listing the invalid
8243 /// specifier(s) on a declaration.
8244 struct BadSpecifierDiagnoser {
8245   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8246       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8247   ~BadSpecifierDiagnoser() {
8248     Diagnostic << Specifiers;
8249   }
8250 
8251   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8252     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8253   }
8254   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8255     return check(SpecLoc,
8256                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8257   }
8258   void check(SourceLocation SpecLoc, const char *Spec) {
8259     if (SpecLoc.isInvalid()) return;
8260     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8261     if (!Specifiers.empty()) Specifiers += " ";
8262     Specifiers += Spec;
8263   }
8264 
8265   Sema &S;
8266   Sema::SemaDiagnosticBuilder Diagnostic;
8267   std::string Specifiers;
8268 };
8269 }
8270 
8271 /// Check the validity of a declarator that we parsed for a deduction-guide.
8272 /// These aren't actually declarators in the grammar, so we need to check that
8273 /// the user didn't specify any pieces that are not part of the deduction-guide
8274 /// grammar.
8275 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8276                                          StorageClass &SC) {
8277   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8278   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8279   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8280 
8281   // C++ [temp.deduct.guide]p3:
8282   //   A deduction-gide shall be declared in the same scope as the
8283   //   corresponding class template.
8284   if (!CurContext->getRedeclContext()->Equals(
8285           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8286     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8287       << GuidedTemplateDecl;
8288     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8289   }
8290 
8291   auto &DS = D.getMutableDeclSpec();
8292   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8293   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8294       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8295       DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8296       DS.isConceptSpecified()) {
8297     BadSpecifierDiagnoser Diagnoser(
8298         *this, D.getIdentifierLoc(),
8299         diag::err_deduction_guide_invalid_specifier);
8300 
8301     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8302     DS.ClearStorageClassSpecs();
8303     SC = SC_None;
8304 
8305     // 'explicit' is permitted.
8306     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8307     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8308     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8309     Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8310     DS.ClearConstexprSpec();
8311     DS.ClearConceptSpec();
8312 
8313     Diagnoser.check(DS.getConstSpecLoc(), "const");
8314     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8315     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8316     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8317     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8318     DS.ClearTypeQualifiers();
8319 
8320     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8321     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8322     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8323     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8324     DS.ClearTypeSpecType();
8325   }
8326 
8327   if (D.isInvalidType())
8328     return;
8329 
8330   // Check the declarator is simple enough.
8331   bool FoundFunction = false;
8332   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8333     if (Chunk.Kind == DeclaratorChunk::Paren)
8334       continue;
8335     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8336       Diag(D.getDeclSpec().getLocStart(),
8337           diag::err_deduction_guide_with_complex_decl)
8338         << D.getSourceRange();
8339       break;
8340     }
8341     if (!Chunk.Fun.hasTrailingReturnType()) {
8342       Diag(D.getName().getLocStart(),
8343            diag::err_deduction_guide_no_trailing_return_type);
8344       break;
8345     }
8346 
8347     // Check that the return type is written as a specialization of
8348     // the template specified as the deduction-guide's name.
8349     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8350     TypeSourceInfo *TSI = nullptr;
8351     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8352     assert(TSI && "deduction guide has valid type but invalid return type?");
8353     bool AcceptableReturnType = false;
8354     bool MightInstantiateToSpecialization = false;
8355     if (auto RetTST =
8356             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8357       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8358       bool TemplateMatches =
8359           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8360       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8361         AcceptableReturnType = true;
8362       else {
8363         // This could still instantiate to the right type, unless we know it
8364         // names the wrong class template.
8365         auto *TD = SpecifiedName.getAsTemplateDecl();
8366         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8367                                              !TemplateMatches);
8368       }
8369     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8370       MightInstantiateToSpecialization = true;
8371     }
8372 
8373     if (!AcceptableReturnType) {
8374       Diag(TSI->getTypeLoc().getLocStart(),
8375            diag::err_deduction_guide_bad_trailing_return_type)
8376         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8377         << TSI->getTypeLoc().getSourceRange();
8378     }
8379 
8380     // Keep going to check that we don't have any inner declarator pieces (we
8381     // could still have a function returning a pointer to a function).
8382     FoundFunction = true;
8383   }
8384 
8385   if (D.isFunctionDefinition())
8386     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8387 }
8388 
8389 //===----------------------------------------------------------------------===//
8390 // Namespace Handling
8391 //===----------------------------------------------------------------------===//
8392 
8393 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8394 /// reopened.
8395 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8396                                             SourceLocation Loc,
8397                                             IdentifierInfo *II, bool *IsInline,
8398                                             NamespaceDecl *PrevNS) {
8399   assert(*IsInline != PrevNS->isInline());
8400 
8401   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8402   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8403   // inline namespaces, with the intention of bringing names into namespace std.
8404   //
8405   // We support this just well enough to get that case working; this is not
8406   // sufficient to support reopening namespaces as inline in general.
8407   if (*IsInline && II && II->getName().startswith("__atomic") &&
8408       S.getSourceManager().isInSystemHeader(Loc)) {
8409     // Mark all prior declarations of the namespace as inline.
8410     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8411          NS = NS->getPreviousDecl())
8412       NS->setInline(*IsInline);
8413     // Patch up the lookup table for the containing namespace. This isn't really
8414     // correct, but it's good enough for this particular case.
8415     for (auto *I : PrevNS->decls())
8416       if (auto *ND = dyn_cast<NamedDecl>(I))
8417         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8418     return;
8419   }
8420 
8421   if (PrevNS->isInline())
8422     // The user probably just forgot the 'inline', so suggest that it
8423     // be added back.
8424     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8425       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8426   else
8427     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8428 
8429   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8430   *IsInline = PrevNS->isInline();
8431 }
8432 
8433 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8434 /// definition.
8435 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8436                                    SourceLocation InlineLoc,
8437                                    SourceLocation NamespaceLoc,
8438                                    SourceLocation IdentLoc,
8439                                    IdentifierInfo *II,
8440                                    SourceLocation LBrace,
8441                                    AttributeList *AttrList,
8442                                    UsingDirectiveDecl *&UD) {
8443   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8444   // For anonymous namespace, take the location of the left brace.
8445   SourceLocation Loc = II ? IdentLoc : LBrace;
8446   bool IsInline = InlineLoc.isValid();
8447   bool IsInvalid = false;
8448   bool IsStd = false;
8449   bool AddToKnown = false;
8450   Scope *DeclRegionScope = NamespcScope->getParent();
8451 
8452   NamespaceDecl *PrevNS = nullptr;
8453   if (II) {
8454     // C++ [namespace.def]p2:
8455     //   The identifier in an original-namespace-definition shall not
8456     //   have been previously defined in the declarative region in
8457     //   which the original-namespace-definition appears. The
8458     //   identifier in an original-namespace-definition is the name of
8459     //   the namespace. Subsequently in that declarative region, it is
8460     //   treated as an original-namespace-name.
8461     //
8462     // Since namespace names are unique in their scope, and we don't
8463     // look through using directives, just look for any ordinary names
8464     // as if by qualified name lookup.
8465     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8466     LookupQualifiedName(R, CurContext->getRedeclContext());
8467     NamedDecl *PrevDecl =
8468         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8469     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8470 
8471     if (PrevNS) {
8472       // This is an extended namespace definition.
8473       if (IsInline != PrevNS->isInline())
8474         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8475                                         &IsInline, PrevNS);
8476     } else if (PrevDecl) {
8477       // This is an invalid name redefinition.
8478       Diag(Loc, diag::err_redefinition_different_kind)
8479         << II;
8480       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8481       IsInvalid = true;
8482       // Continue on to push Namespc as current DeclContext and return it.
8483     } else if (II->isStr("std") &&
8484                CurContext->getRedeclContext()->isTranslationUnit()) {
8485       // This is the first "real" definition of the namespace "std", so update
8486       // our cache of the "std" namespace to point at this definition.
8487       PrevNS = getStdNamespace();
8488       IsStd = true;
8489       AddToKnown = !IsInline;
8490     } else {
8491       // We've seen this namespace for the first time.
8492       AddToKnown = !IsInline;
8493     }
8494   } else {
8495     // Anonymous namespaces.
8496 
8497     // Determine whether the parent already has an anonymous namespace.
8498     DeclContext *Parent = CurContext->getRedeclContext();
8499     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8500       PrevNS = TU->getAnonymousNamespace();
8501     } else {
8502       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8503       PrevNS = ND->getAnonymousNamespace();
8504     }
8505 
8506     if (PrevNS && IsInline != PrevNS->isInline())
8507       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8508                                       &IsInline, PrevNS);
8509   }
8510 
8511   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8512                                                  StartLoc, Loc, II, PrevNS);
8513   if (IsInvalid)
8514     Namespc->setInvalidDecl();
8515 
8516   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8517   AddPragmaAttributes(DeclRegionScope, Namespc);
8518 
8519   // FIXME: Should we be merging attributes?
8520   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8521     PushNamespaceVisibilityAttr(Attr, Loc);
8522 
8523   if (IsStd)
8524     StdNamespace = Namespc;
8525   if (AddToKnown)
8526     KnownNamespaces[Namespc] = false;
8527 
8528   if (II) {
8529     PushOnScopeChains(Namespc, DeclRegionScope);
8530   } else {
8531     // Link the anonymous namespace into its parent.
8532     DeclContext *Parent = CurContext->getRedeclContext();
8533     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8534       TU->setAnonymousNamespace(Namespc);
8535     } else {
8536       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8537     }
8538 
8539     CurContext->addDecl(Namespc);
8540 
8541     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8542     //   behaves as if it were replaced by
8543     //     namespace unique { /* empty body */ }
8544     //     using namespace unique;
8545     //     namespace unique { namespace-body }
8546     //   where all occurrences of 'unique' in a translation unit are
8547     //   replaced by the same identifier and this identifier differs
8548     //   from all other identifiers in the entire program.
8549 
8550     // We just create the namespace with an empty name and then add an
8551     // implicit using declaration, just like the standard suggests.
8552     //
8553     // CodeGen enforces the "universally unique" aspect by giving all
8554     // declarations semantically contained within an anonymous
8555     // namespace internal linkage.
8556 
8557     if (!PrevNS) {
8558       UD = UsingDirectiveDecl::Create(Context, Parent,
8559                                       /* 'using' */ LBrace,
8560                                       /* 'namespace' */ SourceLocation(),
8561                                       /* qualifier */ NestedNameSpecifierLoc(),
8562                                       /* identifier */ SourceLocation(),
8563                                       Namespc,
8564                                       /* Ancestor */ Parent);
8565       UD->setImplicit();
8566       Parent->addDecl(UD);
8567     }
8568   }
8569 
8570   ActOnDocumentableDecl(Namespc);
8571 
8572   // Although we could have an invalid decl (i.e. the namespace name is a
8573   // redefinition), push it as current DeclContext and try to continue parsing.
8574   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8575   // for the namespace has the declarations that showed up in that particular
8576   // namespace definition.
8577   PushDeclContext(NamespcScope, Namespc);
8578   return Namespc;
8579 }
8580 
8581 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8582 /// is a namespace alias, returns the namespace it points to.
8583 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8584   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8585     return AD->getNamespace();
8586   return dyn_cast_or_null<NamespaceDecl>(D);
8587 }
8588 
8589 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8590 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8591 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8592   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8593   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8594   Namespc->setRBraceLoc(RBrace);
8595   PopDeclContext();
8596   if (Namespc->hasAttr<VisibilityAttr>())
8597     PopPragmaVisibility(true, RBrace);
8598 }
8599 
8600 CXXRecordDecl *Sema::getStdBadAlloc() const {
8601   return cast_or_null<CXXRecordDecl>(
8602                                   StdBadAlloc.get(Context.getExternalSource()));
8603 }
8604 
8605 EnumDecl *Sema::getStdAlignValT() const {
8606   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8607 }
8608 
8609 NamespaceDecl *Sema::getStdNamespace() const {
8610   return cast_or_null<NamespaceDecl>(
8611                                  StdNamespace.get(Context.getExternalSource()));
8612 }
8613 
8614 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8615   if (!StdExperimentalNamespaceCache) {
8616     if (auto Std = getStdNamespace()) {
8617       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8618                           SourceLocation(), LookupNamespaceName);
8619       if (!LookupQualifiedName(Result, Std) ||
8620           !(StdExperimentalNamespaceCache =
8621                 Result.getAsSingle<NamespaceDecl>()))
8622         Result.suppressDiagnostics();
8623     }
8624   }
8625   return StdExperimentalNamespaceCache;
8626 }
8627 
8628 /// \brief Retrieve the special "std" namespace, which may require us to
8629 /// implicitly define the namespace.
8630 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8631   if (!StdNamespace) {
8632     // The "std" namespace has not yet been defined, so build one implicitly.
8633     StdNamespace = NamespaceDecl::Create(Context,
8634                                          Context.getTranslationUnitDecl(),
8635                                          /*Inline=*/false,
8636                                          SourceLocation(), SourceLocation(),
8637                                          &PP.getIdentifierTable().get("std"),
8638                                          /*PrevDecl=*/nullptr);
8639     getStdNamespace()->setImplicit(true);
8640   }
8641 
8642   return getStdNamespace();
8643 }
8644 
8645 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8646   assert(getLangOpts().CPlusPlus &&
8647          "Looking for std::initializer_list outside of C++.");
8648 
8649   // We're looking for implicit instantiations of
8650   // template <typename E> class std::initializer_list.
8651 
8652   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8653     return false;
8654 
8655   ClassTemplateDecl *Template = nullptr;
8656   const TemplateArgument *Arguments = nullptr;
8657 
8658   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8659 
8660     ClassTemplateSpecializationDecl *Specialization =
8661         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8662     if (!Specialization)
8663       return false;
8664 
8665     Template = Specialization->getSpecializedTemplate();
8666     Arguments = Specialization->getTemplateArgs().data();
8667   } else if (const TemplateSpecializationType *TST =
8668                  Ty->getAs<TemplateSpecializationType>()) {
8669     Template = dyn_cast_or_null<ClassTemplateDecl>(
8670         TST->getTemplateName().getAsTemplateDecl());
8671     Arguments = TST->getArgs();
8672   }
8673   if (!Template)
8674     return false;
8675 
8676   if (!StdInitializerList) {
8677     // Haven't recognized std::initializer_list yet, maybe this is it.
8678     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8679     if (TemplateClass->getIdentifier() !=
8680             &PP.getIdentifierTable().get("initializer_list") ||
8681         !getStdNamespace()->InEnclosingNamespaceSetOf(
8682             TemplateClass->getDeclContext()))
8683       return false;
8684     // This is a template called std::initializer_list, but is it the right
8685     // template?
8686     TemplateParameterList *Params = Template->getTemplateParameters();
8687     if (Params->getMinRequiredArguments() != 1)
8688       return false;
8689     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8690       return false;
8691 
8692     // It's the right template.
8693     StdInitializerList = Template;
8694   }
8695 
8696   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8697     return false;
8698 
8699   // This is an instance of std::initializer_list. Find the argument type.
8700   if (Element)
8701     *Element = Arguments[0].getAsType();
8702   return true;
8703 }
8704 
8705 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8706   NamespaceDecl *Std = S.getStdNamespace();
8707   if (!Std) {
8708     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8709     return nullptr;
8710   }
8711 
8712   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8713                       Loc, Sema::LookupOrdinaryName);
8714   if (!S.LookupQualifiedName(Result, Std)) {
8715     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8716     return nullptr;
8717   }
8718   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8719   if (!Template) {
8720     Result.suppressDiagnostics();
8721     // We found something weird. Complain about the first thing we found.
8722     NamedDecl *Found = *Result.begin();
8723     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8724     return nullptr;
8725   }
8726 
8727   // We found some template called std::initializer_list. Now verify that it's
8728   // correct.
8729   TemplateParameterList *Params = Template->getTemplateParameters();
8730   if (Params->getMinRequiredArguments() != 1 ||
8731       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8732     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8733     return nullptr;
8734   }
8735 
8736   return Template;
8737 }
8738 
8739 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8740   if (!StdInitializerList) {
8741     StdInitializerList = LookupStdInitializerList(*this, Loc);
8742     if (!StdInitializerList)
8743       return QualType();
8744   }
8745 
8746   TemplateArgumentListInfo Args(Loc, Loc);
8747   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8748                                        Context.getTrivialTypeSourceInfo(Element,
8749                                                                         Loc)));
8750   return Context.getCanonicalType(
8751       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8752 }
8753 
8754 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
8755   // C++ [dcl.init.list]p2:
8756   //   A constructor is an initializer-list constructor if its first parameter
8757   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8758   //   std::initializer_list<E> for some type E, and either there are no other
8759   //   parameters or else all other parameters have default arguments.
8760   if (Ctor->getNumParams() < 1 ||
8761       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8762     return false;
8763 
8764   QualType ArgType = Ctor->getParamDecl(0)->getType();
8765   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8766     ArgType = RT->getPointeeType().getUnqualifiedType();
8767 
8768   return isStdInitializerList(ArgType, nullptr);
8769 }
8770 
8771 /// \brief Determine whether a using statement is in a context where it will be
8772 /// apply in all contexts.
8773 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8774   switch (CurContext->getDeclKind()) {
8775     case Decl::TranslationUnit:
8776       return true;
8777     case Decl::LinkageSpec:
8778       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8779     default:
8780       return false;
8781   }
8782 }
8783 
8784 namespace {
8785 
8786 // Callback to only accept typo corrections that are namespaces.
8787 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8788 public:
8789   bool ValidateCandidate(const TypoCorrection &candidate) override {
8790     if (NamedDecl *ND = candidate.getCorrectionDecl())
8791       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8792     return false;
8793   }
8794 };
8795 
8796 }
8797 
8798 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8799                                        CXXScopeSpec &SS,
8800                                        SourceLocation IdentLoc,
8801                                        IdentifierInfo *Ident) {
8802   R.clear();
8803   if (TypoCorrection Corrected =
8804           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8805                         llvm::make_unique<NamespaceValidatorCCC>(),
8806                         Sema::CTK_ErrorRecovery)) {
8807     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8808       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8809       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8810                               Ident->getName().equals(CorrectedStr);
8811       S.diagnoseTypo(Corrected,
8812                      S.PDiag(diag::err_using_directive_member_suggest)
8813                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8814                      S.PDiag(diag::note_namespace_defined_here));
8815     } else {
8816       S.diagnoseTypo(Corrected,
8817                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8818                      S.PDiag(diag::note_namespace_defined_here));
8819     }
8820     R.addDecl(Corrected.getFoundDecl());
8821     return true;
8822   }
8823   return false;
8824 }
8825 
8826 Decl *Sema::ActOnUsingDirective(Scope *S,
8827                                           SourceLocation UsingLoc,
8828                                           SourceLocation NamespcLoc,
8829                                           CXXScopeSpec &SS,
8830                                           SourceLocation IdentLoc,
8831                                           IdentifierInfo *NamespcName,
8832                                           AttributeList *AttrList) {
8833   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8834   assert(NamespcName && "Invalid NamespcName.");
8835   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8836 
8837   // This can only happen along a recovery path.
8838   while (S->isTemplateParamScope())
8839     S = S->getParent();
8840   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8841 
8842   UsingDirectiveDecl *UDir = nullptr;
8843   NestedNameSpecifier *Qualifier = nullptr;
8844   if (SS.isSet())
8845     Qualifier = SS.getScopeRep();
8846 
8847   // Lookup namespace name.
8848   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8849   LookupParsedName(R, S, &SS);
8850   if (R.isAmbiguous())
8851     return nullptr;
8852 
8853   if (R.empty()) {
8854     R.clear();
8855     // Allow "using namespace std;" or "using namespace ::std;" even if
8856     // "std" hasn't been defined yet, for GCC compatibility.
8857     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8858         NamespcName->isStr("std")) {
8859       Diag(IdentLoc, diag::ext_using_undefined_std);
8860       R.addDecl(getOrCreateStdNamespace());
8861       R.resolveKind();
8862     }
8863     // Otherwise, attempt typo correction.
8864     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8865   }
8866 
8867   if (!R.empty()) {
8868     NamedDecl *Named = R.getRepresentativeDecl();
8869     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8870     assert(NS && "expected namespace decl");
8871 
8872     // The use of a nested name specifier may trigger deprecation warnings.
8873     DiagnoseUseOfDecl(Named, IdentLoc);
8874 
8875     // C++ [namespace.udir]p1:
8876     //   A using-directive specifies that the names in the nominated
8877     //   namespace can be used in the scope in which the
8878     //   using-directive appears after the using-directive. During
8879     //   unqualified name lookup (3.4.1), the names appear as if they
8880     //   were declared in the nearest enclosing namespace which
8881     //   contains both the using-directive and the nominated
8882     //   namespace. [Note: in this context, "contains" means "contains
8883     //   directly or indirectly". ]
8884 
8885     // Find enclosing context containing both using-directive and
8886     // nominated namespace.
8887     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8888     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8889       CommonAncestor = CommonAncestor->getParent();
8890 
8891     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8892                                       SS.getWithLocInContext(Context),
8893                                       IdentLoc, Named, CommonAncestor);
8894 
8895     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8896         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8897       Diag(IdentLoc, diag::warn_using_directive_in_header);
8898     }
8899 
8900     PushUsingDirective(S, UDir);
8901   } else {
8902     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8903   }
8904 
8905   if (UDir)
8906     ProcessDeclAttributeList(S, UDir, AttrList);
8907 
8908   return UDir;
8909 }
8910 
8911 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8912   // If the scope has an associated entity and the using directive is at
8913   // namespace or translation unit scope, add the UsingDirectiveDecl into
8914   // its lookup structure so qualified name lookup can find it.
8915   DeclContext *Ctx = S->getEntity();
8916   if (Ctx && !Ctx->isFunctionOrMethod())
8917     Ctx->addDecl(UDir);
8918   else
8919     // Otherwise, it is at block scope. The using-directives will affect lookup
8920     // only to the end of the scope.
8921     S->PushUsingDirective(UDir);
8922 }
8923 
8924 
8925 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8926                                   AccessSpecifier AS,
8927                                   SourceLocation UsingLoc,
8928                                   SourceLocation TypenameLoc,
8929                                   CXXScopeSpec &SS,
8930                                   UnqualifiedId &Name,
8931                                   SourceLocation EllipsisLoc,
8932                                   AttributeList *AttrList) {
8933   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8934 
8935   if (SS.isEmpty()) {
8936     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8937     return nullptr;
8938   }
8939 
8940   switch (Name.getKind()) {
8941   case UnqualifiedId::IK_ImplicitSelfParam:
8942   case UnqualifiedId::IK_Identifier:
8943   case UnqualifiedId::IK_OperatorFunctionId:
8944   case UnqualifiedId::IK_LiteralOperatorId:
8945   case UnqualifiedId::IK_ConversionFunctionId:
8946     break;
8947 
8948   case UnqualifiedId::IK_ConstructorName:
8949   case UnqualifiedId::IK_ConstructorTemplateId:
8950     // C++11 inheriting constructors.
8951     Diag(Name.getLocStart(),
8952          getLangOpts().CPlusPlus11 ?
8953            diag::warn_cxx98_compat_using_decl_constructor :
8954            diag::err_using_decl_constructor)
8955       << SS.getRange();
8956 
8957     if (getLangOpts().CPlusPlus11) break;
8958 
8959     return nullptr;
8960 
8961   case UnqualifiedId::IK_DestructorName:
8962     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8963       << SS.getRange();
8964     return nullptr;
8965 
8966   case UnqualifiedId::IK_TemplateId:
8967     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8968       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8969     return nullptr;
8970 
8971   case UnqualifiedId::IK_DeductionGuideName:
8972     llvm_unreachable("cannot parse qualified deduction guide name");
8973   }
8974 
8975   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8976   DeclarationName TargetName = TargetNameInfo.getName();
8977   if (!TargetName)
8978     return nullptr;
8979 
8980   // Warn about access declarations.
8981   if (UsingLoc.isInvalid()) {
8982     Diag(Name.getLocStart(),
8983          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8984                                    : diag::warn_access_decl_deprecated)
8985       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8986   }
8987 
8988   if (EllipsisLoc.isInvalid()) {
8989     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8990         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8991       return nullptr;
8992   } else {
8993     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8994         !TargetNameInfo.containsUnexpandedParameterPack()) {
8995       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8996         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8997       EllipsisLoc = SourceLocation();
8998     }
8999   }
9000 
9001   NamedDecl *UD =
9002       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9003                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9004                             /*IsInstantiation*/false);
9005   if (UD)
9006     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9007 
9008   return UD;
9009 }
9010 
9011 /// \brief Determine whether a using declaration considers the given
9012 /// declarations as "equivalent", e.g., if they are redeclarations of
9013 /// the same entity or are both typedefs of the same type.
9014 static bool
9015 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9016   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9017     return true;
9018 
9019   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9020     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9021       return Context.hasSameType(TD1->getUnderlyingType(),
9022                                  TD2->getUnderlyingType());
9023 
9024   return false;
9025 }
9026 
9027 
9028 /// Determines whether to create a using shadow decl for a particular
9029 /// decl, given the set of decls existing prior to this using lookup.
9030 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9031                                 const LookupResult &Previous,
9032                                 UsingShadowDecl *&PrevShadow) {
9033   // Diagnose finding a decl which is not from a base class of the
9034   // current class.  We do this now because there are cases where this
9035   // function will silently decide not to build a shadow decl, which
9036   // will pre-empt further diagnostics.
9037   //
9038   // We don't need to do this in C++11 because we do the check once on
9039   // the qualifier.
9040   //
9041   // FIXME: diagnose the following if we care enough:
9042   //   struct A { int foo; };
9043   //   struct B : A { using A::foo; };
9044   //   template <class T> struct C : A {};
9045   //   template <class T> struct D : C<T> { using B::foo; } // <---
9046   // This is invalid (during instantiation) in C++03 because B::foo
9047   // resolves to the using decl in B, which is not a base class of D<T>.
9048   // We can't diagnose it immediately because C<T> is an unknown
9049   // specialization.  The UsingShadowDecl in D<T> then points directly
9050   // to A::foo, which will look well-formed when we instantiate.
9051   // The right solution is to not collapse the shadow-decl chain.
9052   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9053     DeclContext *OrigDC = Orig->getDeclContext();
9054 
9055     // Handle enums and anonymous structs.
9056     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9057     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9058     while (OrigRec->isAnonymousStructOrUnion())
9059       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9060 
9061     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9062       if (OrigDC == CurContext) {
9063         Diag(Using->getLocation(),
9064              diag::err_using_decl_nested_name_specifier_is_current_class)
9065           << Using->getQualifierLoc().getSourceRange();
9066         Diag(Orig->getLocation(), diag::note_using_decl_target);
9067         Using->setInvalidDecl();
9068         return true;
9069       }
9070 
9071       Diag(Using->getQualifierLoc().getBeginLoc(),
9072            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9073         << Using->getQualifier()
9074         << cast<CXXRecordDecl>(CurContext)
9075         << Using->getQualifierLoc().getSourceRange();
9076       Diag(Orig->getLocation(), diag::note_using_decl_target);
9077       Using->setInvalidDecl();
9078       return true;
9079     }
9080   }
9081 
9082   if (Previous.empty()) return false;
9083 
9084   NamedDecl *Target = Orig;
9085   if (isa<UsingShadowDecl>(Target))
9086     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9087 
9088   // If the target happens to be one of the previous declarations, we
9089   // don't have a conflict.
9090   //
9091   // FIXME: but we might be increasing its access, in which case we
9092   // should redeclare it.
9093   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9094   bool FoundEquivalentDecl = false;
9095   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9096          I != E; ++I) {
9097     NamedDecl *D = (*I)->getUnderlyingDecl();
9098     // We can have UsingDecls in our Previous results because we use the same
9099     // LookupResult for checking whether the UsingDecl itself is a valid
9100     // redeclaration.
9101     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9102       continue;
9103 
9104     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9105       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9106         PrevShadow = Shadow;
9107       FoundEquivalentDecl = true;
9108     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9109       // We don't conflict with an existing using shadow decl of an equivalent
9110       // declaration, but we're not a redeclaration of it.
9111       FoundEquivalentDecl = true;
9112     }
9113 
9114     if (isVisible(D))
9115       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9116   }
9117 
9118   if (FoundEquivalentDecl)
9119     return false;
9120 
9121   if (FunctionDecl *FD = Target->getAsFunction()) {
9122     NamedDecl *OldDecl = nullptr;
9123     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9124                           /*IsForUsingDecl*/ true)) {
9125     case Ovl_Overload:
9126       return false;
9127 
9128     case Ovl_NonFunction:
9129       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9130       break;
9131 
9132     // We found a decl with the exact signature.
9133     case Ovl_Match:
9134       // If we're in a record, we want to hide the target, so we
9135       // return true (without a diagnostic) to tell the caller not to
9136       // build a shadow decl.
9137       if (CurContext->isRecord())
9138         return true;
9139 
9140       // If we're not in a record, this is an error.
9141       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9142       break;
9143     }
9144 
9145     Diag(Target->getLocation(), diag::note_using_decl_target);
9146     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9147     Using->setInvalidDecl();
9148     return true;
9149   }
9150 
9151   // Target is not a function.
9152 
9153   if (isa<TagDecl>(Target)) {
9154     // No conflict between a tag and a non-tag.
9155     if (!Tag) return false;
9156 
9157     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9158     Diag(Target->getLocation(), diag::note_using_decl_target);
9159     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9160     Using->setInvalidDecl();
9161     return true;
9162   }
9163 
9164   // No conflict between a tag and a non-tag.
9165   if (!NonTag) return false;
9166 
9167   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9168   Diag(Target->getLocation(), diag::note_using_decl_target);
9169   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9170   Using->setInvalidDecl();
9171   return true;
9172 }
9173 
9174 /// Determine whether a direct base class is a virtual base class.
9175 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9176   if (!Derived->getNumVBases())
9177     return false;
9178   for (auto &B : Derived->bases())
9179     if (B.getType()->getAsCXXRecordDecl() == Base)
9180       return B.isVirtual();
9181   llvm_unreachable("not a direct base class");
9182 }
9183 
9184 /// Builds a shadow declaration corresponding to a 'using' declaration.
9185 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9186                                             UsingDecl *UD,
9187                                             NamedDecl *Orig,
9188                                             UsingShadowDecl *PrevDecl) {
9189   // If we resolved to another shadow declaration, just coalesce them.
9190   NamedDecl *Target = Orig;
9191   if (isa<UsingShadowDecl>(Target)) {
9192     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9193     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9194   }
9195 
9196   NamedDecl *NonTemplateTarget = Target;
9197   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9198     NonTemplateTarget = TargetTD->getTemplatedDecl();
9199 
9200   UsingShadowDecl *Shadow;
9201   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9202     bool IsVirtualBase =
9203         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9204                             UD->getQualifier()->getAsRecordDecl());
9205     Shadow = ConstructorUsingShadowDecl::Create(
9206         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9207   } else {
9208     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9209                                      Target);
9210   }
9211   UD->addShadowDecl(Shadow);
9212 
9213   Shadow->setAccess(UD->getAccess());
9214   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9215     Shadow->setInvalidDecl();
9216 
9217   Shadow->setPreviousDecl(PrevDecl);
9218 
9219   if (S)
9220     PushOnScopeChains(Shadow, S);
9221   else
9222     CurContext->addDecl(Shadow);
9223 
9224 
9225   return Shadow;
9226 }
9227 
9228 /// Hides a using shadow declaration.  This is required by the current
9229 /// using-decl implementation when a resolvable using declaration in a
9230 /// class is followed by a declaration which would hide or override
9231 /// one or more of the using decl's targets; for example:
9232 ///
9233 ///   struct Base { void foo(int); };
9234 ///   struct Derived : Base {
9235 ///     using Base::foo;
9236 ///     void foo(int);
9237 ///   };
9238 ///
9239 /// The governing language is C++03 [namespace.udecl]p12:
9240 ///
9241 ///   When a using-declaration brings names from a base class into a
9242 ///   derived class scope, member functions in the derived class
9243 ///   override and/or hide member functions with the same name and
9244 ///   parameter types in a base class (rather than conflicting).
9245 ///
9246 /// There are two ways to implement this:
9247 ///   (1) optimistically create shadow decls when they're not hidden
9248 ///       by existing declarations, or
9249 ///   (2) don't create any shadow decls (or at least don't make them
9250 ///       visible) until we've fully parsed/instantiated the class.
9251 /// The problem with (1) is that we might have to retroactively remove
9252 /// a shadow decl, which requires several O(n) operations because the
9253 /// decl structures are (very reasonably) not designed for removal.
9254 /// (2) avoids this but is very fiddly and phase-dependent.
9255 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9256   if (Shadow->getDeclName().getNameKind() ==
9257         DeclarationName::CXXConversionFunctionName)
9258     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9259 
9260   // Remove it from the DeclContext...
9261   Shadow->getDeclContext()->removeDecl(Shadow);
9262 
9263   // ...and the scope, if applicable...
9264   if (S) {
9265     S->RemoveDecl(Shadow);
9266     IdResolver.RemoveDecl(Shadow);
9267   }
9268 
9269   // ...and the using decl.
9270   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9271 
9272   // TODO: complain somehow if Shadow was used.  It shouldn't
9273   // be possible for this to happen, because...?
9274 }
9275 
9276 /// Find the base specifier for a base class with the given type.
9277 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9278                                                 QualType DesiredBase,
9279                                                 bool &AnyDependentBases) {
9280   // Check whether the named type is a direct base class.
9281   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9282   for (auto &Base : Derived->bases()) {
9283     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9284     if (CanonicalDesiredBase == BaseType)
9285       return &Base;
9286     if (BaseType->isDependentType())
9287       AnyDependentBases = true;
9288   }
9289   return nullptr;
9290 }
9291 
9292 namespace {
9293 class UsingValidatorCCC : public CorrectionCandidateCallback {
9294 public:
9295   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9296                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9297       : HasTypenameKeyword(HasTypenameKeyword),
9298         IsInstantiation(IsInstantiation), OldNNS(NNS),
9299         RequireMemberOf(RequireMemberOf) {}
9300 
9301   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9302     NamedDecl *ND = Candidate.getCorrectionDecl();
9303 
9304     // Keywords are not valid here.
9305     if (!ND || isa<NamespaceDecl>(ND))
9306       return false;
9307 
9308     // Completely unqualified names are invalid for a 'using' declaration.
9309     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9310       return false;
9311 
9312     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9313     // reject.
9314 
9315     if (RequireMemberOf) {
9316       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9317       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9318         // No-one ever wants a using-declaration to name an injected-class-name
9319         // of a base class, unless they're declaring an inheriting constructor.
9320         ASTContext &Ctx = ND->getASTContext();
9321         if (!Ctx.getLangOpts().CPlusPlus11)
9322           return false;
9323         QualType FoundType = Ctx.getRecordType(FoundRecord);
9324 
9325         // Check that the injected-class-name is named as a member of its own
9326         // type; we don't want to suggest 'using Derived::Base;', since that
9327         // means something else.
9328         NestedNameSpecifier *Specifier =
9329             Candidate.WillReplaceSpecifier()
9330                 ? Candidate.getCorrectionSpecifier()
9331                 : OldNNS;
9332         if (!Specifier->getAsType() ||
9333             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9334           return false;
9335 
9336         // Check that this inheriting constructor declaration actually names a
9337         // direct base class of the current class.
9338         bool AnyDependentBases = false;
9339         if (!findDirectBaseWithType(RequireMemberOf,
9340                                     Ctx.getRecordType(FoundRecord),
9341                                     AnyDependentBases) &&
9342             !AnyDependentBases)
9343           return false;
9344       } else {
9345         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9346         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9347           return false;
9348 
9349         // FIXME: Check that the base class member is accessible?
9350       }
9351     } else {
9352       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9353       if (FoundRecord && FoundRecord->isInjectedClassName())
9354         return false;
9355     }
9356 
9357     if (isa<TypeDecl>(ND))
9358       return HasTypenameKeyword || !IsInstantiation;
9359 
9360     return !HasTypenameKeyword;
9361   }
9362 
9363 private:
9364   bool HasTypenameKeyword;
9365   bool IsInstantiation;
9366   NestedNameSpecifier *OldNNS;
9367   CXXRecordDecl *RequireMemberOf;
9368 };
9369 } // end anonymous namespace
9370 
9371 /// Builds a using declaration.
9372 ///
9373 /// \param IsInstantiation - Whether this call arises from an
9374 ///   instantiation of an unresolved using declaration.  We treat
9375 ///   the lookup differently for these declarations.
9376 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9377                                        SourceLocation UsingLoc,
9378                                        bool HasTypenameKeyword,
9379                                        SourceLocation TypenameLoc,
9380                                        CXXScopeSpec &SS,
9381                                        DeclarationNameInfo NameInfo,
9382                                        SourceLocation EllipsisLoc,
9383                                        AttributeList *AttrList,
9384                                        bool IsInstantiation) {
9385   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9386   SourceLocation IdentLoc = NameInfo.getLoc();
9387   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9388 
9389   // FIXME: We ignore attributes for now.
9390 
9391   // For an inheriting constructor declaration, the name of the using
9392   // declaration is the name of a constructor in this class, not in the
9393   // base class.
9394   DeclarationNameInfo UsingName = NameInfo;
9395   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9396     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9397       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9398           Context.getCanonicalType(Context.getRecordType(RD))));
9399 
9400   // Do the redeclaration lookup in the current scope.
9401   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9402                         ForRedeclaration);
9403   Previous.setHideTags(false);
9404   if (S) {
9405     LookupName(Previous, S);
9406 
9407     // It is really dumb that we have to do this.
9408     LookupResult::Filter F = Previous.makeFilter();
9409     while (F.hasNext()) {
9410       NamedDecl *D = F.next();
9411       if (!isDeclInScope(D, CurContext, S))
9412         F.erase();
9413       // If we found a local extern declaration that's not ordinarily visible,
9414       // and this declaration is being added to a non-block scope, ignore it.
9415       // We're only checking for scope conflicts here, not also for violations
9416       // of the linkage rules.
9417       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9418                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9419         F.erase();
9420     }
9421     F.done();
9422   } else {
9423     assert(IsInstantiation && "no scope in non-instantiation");
9424     if (CurContext->isRecord())
9425       LookupQualifiedName(Previous, CurContext);
9426     else {
9427       // No redeclaration check is needed here; in non-member contexts we
9428       // diagnosed all possible conflicts with other using-declarations when
9429       // building the template:
9430       //
9431       // For a dependent non-type using declaration, the only valid case is
9432       // if we instantiate to a single enumerator. We check for conflicts
9433       // between shadow declarations we introduce, and we check in the template
9434       // definition for conflicts between a non-type using declaration and any
9435       // other declaration, which together covers all cases.
9436       //
9437       // A dependent typename using declaration will never successfully
9438       // instantiate, since it will always name a class member, so we reject
9439       // that in the template definition.
9440     }
9441   }
9442 
9443   // Check for invalid redeclarations.
9444   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9445                                   SS, IdentLoc, Previous))
9446     return nullptr;
9447 
9448   // Check for bad qualifiers.
9449   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9450                               IdentLoc))
9451     return nullptr;
9452 
9453   DeclContext *LookupContext = computeDeclContext(SS);
9454   NamedDecl *D;
9455   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9456   if (!LookupContext || EllipsisLoc.isValid()) {
9457     if (HasTypenameKeyword) {
9458       // FIXME: not all declaration name kinds are legal here
9459       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9460                                               UsingLoc, TypenameLoc,
9461                                               QualifierLoc,
9462                                               IdentLoc, NameInfo.getName(),
9463                                               EllipsisLoc);
9464     } else {
9465       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9466                                            QualifierLoc, NameInfo, EllipsisLoc);
9467     }
9468     D->setAccess(AS);
9469     CurContext->addDecl(D);
9470     return D;
9471   }
9472 
9473   auto Build = [&](bool Invalid) {
9474     UsingDecl *UD =
9475         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9476                           UsingName, HasTypenameKeyword);
9477     UD->setAccess(AS);
9478     CurContext->addDecl(UD);
9479     UD->setInvalidDecl(Invalid);
9480     return UD;
9481   };
9482   auto BuildInvalid = [&]{ return Build(true); };
9483   auto BuildValid = [&]{ return Build(false); };
9484 
9485   if (RequireCompleteDeclContext(SS, LookupContext))
9486     return BuildInvalid();
9487 
9488   // Look up the target name.
9489   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9490 
9491   // Unlike most lookups, we don't always want to hide tag
9492   // declarations: tag names are visible through the using declaration
9493   // even if hidden by ordinary names, *except* in a dependent context
9494   // where it's important for the sanity of two-phase lookup.
9495   if (!IsInstantiation)
9496     R.setHideTags(false);
9497 
9498   // For the purposes of this lookup, we have a base object type
9499   // equal to that of the current context.
9500   if (CurContext->isRecord()) {
9501     R.setBaseObjectType(
9502                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9503   }
9504 
9505   LookupQualifiedName(R, LookupContext);
9506 
9507   // Try to correct typos if possible. If constructor name lookup finds no
9508   // results, that means the named class has no explicit constructors, and we
9509   // suppressed declaring implicit ones (probably because it's dependent or
9510   // invalid).
9511   if (R.empty() &&
9512       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9513     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9514     // it will believe that glibc provides a ::gets in cases where it does not,
9515     // and will try to pull it into namespace std with a using-declaration.
9516     // Just ignore the using-declaration in that case.
9517     auto *II = NameInfo.getName().getAsIdentifierInfo();
9518     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9519         CurContext->isStdNamespace() &&
9520         isa<TranslationUnitDecl>(LookupContext) &&
9521         getSourceManager().isInSystemHeader(UsingLoc))
9522       return nullptr;
9523     if (TypoCorrection Corrected = CorrectTypo(
9524             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9525             llvm::make_unique<UsingValidatorCCC>(
9526                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9527                 dyn_cast<CXXRecordDecl>(CurContext)),
9528             CTK_ErrorRecovery)) {
9529       // We reject candidates where DroppedSpecifier == true, hence the
9530       // literal '0' below.
9531       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9532                                 << NameInfo.getName() << LookupContext << 0
9533                                 << SS.getRange());
9534 
9535       // If we picked a correction with no attached Decl we can't do anything
9536       // useful with it, bail out.
9537       NamedDecl *ND = Corrected.getCorrectionDecl();
9538       if (!ND)
9539         return BuildInvalid();
9540 
9541       // If we corrected to an inheriting constructor, handle it as one.
9542       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9543       if (RD && RD->isInjectedClassName()) {
9544         // The parent of the injected class name is the class itself.
9545         RD = cast<CXXRecordDecl>(RD->getParent());
9546 
9547         // Fix up the information we'll use to build the using declaration.
9548         if (Corrected.WillReplaceSpecifier()) {
9549           NestedNameSpecifierLocBuilder Builder;
9550           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9551                               QualifierLoc.getSourceRange());
9552           QualifierLoc = Builder.getWithLocInContext(Context);
9553         }
9554 
9555         // In this case, the name we introduce is the name of a derived class
9556         // constructor.
9557         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9558         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9559             Context.getCanonicalType(Context.getRecordType(CurClass))));
9560         UsingName.setNamedTypeInfo(nullptr);
9561         for (auto *Ctor : LookupConstructors(RD))
9562           R.addDecl(Ctor);
9563         R.resolveKind();
9564       } else {
9565         // FIXME: Pick up all the declarations if we found an overloaded
9566         // function.
9567         UsingName.setName(ND->getDeclName());
9568         R.addDecl(ND);
9569       }
9570     } else {
9571       Diag(IdentLoc, diag::err_no_member)
9572         << NameInfo.getName() << LookupContext << SS.getRange();
9573       return BuildInvalid();
9574     }
9575   }
9576 
9577   if (R.isAmbiguous())
9578     return BuildInvalid();
9579 
9580   if (HasTypenameKeyword) {
9581     // If we asked for a typename and got a non-type decl, error out.
9582     if (!R.getAsSingle<TypeDecl>()) {
9583       Diag(IdentLoc, diag::err_using_typename_non_type);
9584       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9585         Diag((*I)->getUnderlyingDecl()->getLocation(),
9586              diag::note_using_decl_target);
9587       return BuildInvalid();
9588     }
9589   } else {
9590     // If we asked for a non-typename and we got a type, error out,
9591     // but only if this is an instantiation of an unresolved using
9592     // decl.  Otherwise just silently find the type name.
9593     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9594       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9595       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9596       return BuildInvalid();
9597     }
9598   }
9599 
9600   // C++14 [namespace.udecl]p6:
9601   // A using-declaration shall not name a namespace.
9602   if (R.getAsSingle<NamespaceDecl>()) {
9603     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9604       << SS.getRange();
9605     return BuildInvalid();
9606   }
9607 
9608   // C++14 [namespace.udecl]p7:
9609   // A using-declaration shall not name a scoped enumerator.
9610   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9611     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9612       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9613         << SS.getRange();
9614       return BuildInvalid();
9615     }
9616   }
9617 
9618   UsingDecl *UD = BuildValid();
9619 
9620   // Some additional rules apply to inheriting constructors.
9621   if (UsingName.getName().getNameKind() ==
9622         DeclarationName::CXXConstructorName) {
9623     // Suppress access diagnostics; the access check is instead performed at the
9624     // point of use for an inheriting constructor.
9625     R.suppressDiagnostics();
9626     if (CheckInheritingConstructorUsingDecl(UD))
9627       return UD;
9628   }
9629 
9630   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9631     UsingShadowDecl *PrevDecl = nullptr;
9632     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9633       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9634   }
9635 
9636   return UD;
9637 }
9638 
9639 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9640                                     ArrayRef<NamedDecl *> Expansions) {
9641   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9642          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9643          isa<UsingPackDecl>(InstantiatedFrom));
9644 
9645   auto *UPD =
9646       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9647   UPD->setAccess(InstantiatedFrom->getAccess());
9648   CurContext->addDecl(UPD);
9649   return UPD;
9650 }
9651 
9652 /// Additional checks for a using declaration referring to a constructor name.
9653 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9654   assert(!UD->hasTypename() && "expecting a constructor name");
9655 
9656   const Type *SourceType = UD->getQualifier()->getAsType();
9657   assert(SourceType &&
9658          "Using decl naming constructor doesn't have type in scope spec.");
9659   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9660 
9661   // Check whether the named type is a direct base class.
9662   bool AnyDependentBases = false;
9663   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9664                                       AnyDependentBases);
9665   if (!Base && !AnyDependentBases) {
9666     Diag(UD->getUsingLoc(),
9667          diag::err_using_decl_constructor_not_in_direct_base)
9668       << UD->getNameInfo().getSourceRange()
9669       << QualType(SourceType, 0) << TargetClass;
9670     UD->setInvalidDecl();
9671     return true;
9672   }
9673 
9674   if (Base)
9675     Base->setInheritConstructors();
9676 
9677   return false;
9678 }
9679 
9680 /// Checks that the given using declaration is not an invalid
9681 /// redeclaration.  Note that this is checking only for the using decl
9682 /// itself, not for any ill-formedness among the UsingShadowDecls.
9683 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9684                                        bool HasTypenameKeyword,
9685                                        const CXXScopeSpec &SS,
9686                                        SourceLocation NameLoc,
9687                                        const LookupResult &Prev) {
9688   NestedNameSpecifier *Qual = SS.getScopeRep();
9689 
9690   // C++03 [namespace.udecl]p8:
9691   // C++0x [namespace.udecl]p10:
9692   //   A using-declaration is a declaration and can therefore be used
9693   //   repeatedly where (and only where) multiple declarations are
9694   //   allowed.
9695   //
9696   // That's in non-member contexts.
9697   if (!CurContext->getRedeclContext()->isRecord()) {
9698     // A dependent qualifier outside a class can only ever resolve to an
9699     // enumeration type. Therefore it conflicts with any other non-type
9700     // declaration in the same scope.
9701     // FIXME: How should we check for dependent type-type conflicts at block
9702     // scope?
9703     if (Qual->isDependent() && !HasTypenameKeyword) {
9704       for (auto *D : Prev) {
9705         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9706           bool OldCouldBeEnumerator =
9707               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9708           Diag(NameLoc,
9709                OldCouldBeEnumerator ? diag::err_redefinition
9710                                     : diag::err_redefinition_different_kind)
9711               << Prev.getLookupName();
9712           Diag(D->getLocation(), diag::note_previous_definition);
9713           return true;
9714         }
9715       }
9716     }
9717     return false;
9718   }
9719 
9720   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9721     NamedDecl *D = *I;
9722 
9723     bool DTypename;
9724     NestedNameSpecifier *DQual;
9725     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9726       DTypename = UD->hasTypename();
9727       DQual = UD->getQualifier();
9728     } else if (UnresolvedUsingValueDecl *UD
9729                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9730       DTypename = false;
9731       DQual = UD->getQualifier();
9732     } else if (UnresolvedUsingTypenameDecl *UD
9733                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9734       DTypename = true;
9735       DQual = UD->getQualifier();
9736     } else continue;
9737 
9738     // using decls differ if one says 'typename' and the other doesn't.
9739     // FIXME: non-dependent using decls?
9740     if (HasTypenameKeyword != DTypename) continue;
9741 
9742     // using decls differ if they name different scopes (but note that
9743     // template instantiation can cause this check to trigger when it
9744     // didn't before instantiation).
9745     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9746         Context.getCanonicalNestedNameSpecifier(DQual))
9747       continue;
9748 
9749     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9750     Diag(D->getLocation(), diag::note_using_decl) << 1;
9751     return true;
9752   }
9753 
9754   return false;
9755 }
9756 
9757 
9758 /// Checks that the given nested-name qualifier used in a using decl
9759 /// in the current context is appropriately related to the current
9760 /// scope.  If an error is found, diagnoses it and returns true.
9761 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9762                                    bool HasTypename,
9763                                    const CXXScopeSpec &SS,
9764                                    const DeclarationNameInfo &NameInfo,
9765                                    SourceLocation NameLoc) {
9766   DeclContext *NamedContext = computeDeclContext(SS);
9767 
9768   if (!CurContext->isRecord()) {
9769     // C++03 [namespace.udecl]p3:
9770     // C++0x [namespace.udecl]p8:
9771     //   A using-declaration for a class member shall be a member-declaration.
9772 
9773     // If we weren't able to compute a valid scope, it might validly be a
9774     // dependent class scope or a dependent enumeration unscoped scope. If
9775     // we have a 'typename' keyword, the scope must resolve to a class type.
9776     if ((HasTypename && !NamedContext) ||
9777         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9778       auto *RD = NamedContext
9779                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9780                      : nullptr;
9781       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9782         RD = nullptr;
9783 
9784       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9785         << SS.getRange();
9786 
9787       // If we have a complete, non-dependent source type, try to suggest a
9788       // way to get the same effect.
9789       if (!RD)
9790         return true;
9791 
9792       // Find what this using-declaration was referring to.
9793       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9794       R.setHideTags(false);
9795       R.suppressDiagnostics();
9796       LookupQualifiedName(R, RD);
9797 
9798       if (R.getAsSingle<TypeDecl>()) {
9799         if (getLangOpts().CPlusPlus11) {
9800           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9801           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9802             << 0 // alias declaration
9803             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9804                                           NameInfo.getName().getAsString() +
9805                                               " = ");
9806         } else {
9807           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9808           SourceLocation InsertLoc =
9809               getLocForEndOfToken(NameInfo.getLocEnd());
9810           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9811             << 1 // typedef declaration
9812             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9813             << FixItHint::CreateInsertion(
9814                    InsertLoc, " " + NameInfo.getName().getAsString());
9815         }
9816       } else if (R.getAsSingle<VarDecl>()) {
9817         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9818         // repeating the type of the static data member here.
9819         FixItHint FixIt;
9820         if (getLangOpts().CPlusPlus11) {
9821           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9822           FixIt = FixItHint::CreateReplacement(
9823               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9824         }
9825 
9826         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9827           << 2 // reference declaration
9828           << FixIt;
9829       } else if (R.getAsSingle<EnumConstantDecl>()) {
9830         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9831         // repeating the type of the enumeration here, and we can't do so if
9832         // the type is anonymous.
9833         FixItHint FixIt;
9834         if (getLangOpts().CPlusPlus11) {
9835           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9836           FixIt = FixItHint::CreateReplacement(
9837               UsingLoc,
9838               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9839         }
9840 
9841         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9842           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9843           << FixIt;
9844       }
9845       return true;
9846     }
9847 
9848     // Otherwise, this might be valid.
9849     return false;
9850   }
9851 
9852   // The current scope is a record.
9853 
9854   // If the named context is dependent, we can't decide much.
9855   if (!NamedContext) {
9856     // FIXME: in C++0x, we can diagnose if we can prove that the
9857     // nested-name-specifier does not refer to a base class, which is
9858     // still possible in some cases.
9859 
9860     // Otherwise we have to conservatively report that things might be
9861     // okay.
9862     return false;
9863   }
9864 
9865   if (!NamedContext->isRecord()) {
9866     // Ideally this would point at the last name in the specifier,
9867     // but we don't have that level of source info.
9868     Diag(SS.getRange().getBegin(),
9869          diag::err_using_decl_nested_name_specifier_is_not_class)
9870       << SS.getScopeRep() << SS.getRange();
9871     return true;
9872   }
9873 
9874   if (!NamedContext->isDependentContext() &&
9875       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9876     return true;
9877 
9878   if (getLangOpts().CPlusPlus11) {
9879     // C++11 [namespace.udecl]p3:
9880     //   In a using-declaration used as a member-declaration, the
9881     //   nested-name-specifier shall name a base class of the class
9882     //   being defined.
9883 
9884     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9885                                  cast<CXXRecordDecl>(NamedContext))) {
9886       if (CurContext == NamedContext) {
9887         Diag(NameLoc,
9888              diag::err_using_decl_nested_name_specifier_is_current_class)
9889           << SS.getRange();
9890         return true;
9891       }
9892 
9893       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9894         Diag(SS.getRange().getBegin(),
9895              diag::err_using_decl_nested_name_specifier_is_not_base_class)
9896           << SS.getScopeRep()
9897           << cast<CXXRecordDecl>(CurContext)
9898           << SS.getRange();
9899       }
9900       return true;
9901     }
9902 
9903     return false;
9904   }
9905 
9906   // C++03 [namespace.udecl]p4:
9907   //   A using-declaration used as a member-declaration shall refer
9908   //   to a member of a base class of the class being defined [etc.].
9909 
9910   // Salient point: SS doesn't have to name a base class as long as
9911   // lookup only finds members from base classes.  Therefore we can
9912   // diagnose here only if we can prove that that can't happen,
9913   // i.e. if the class hierarchies provably don't intersect.
9914 
9915   // TODO: it would be nice if "definitely valid" results were cached
9916   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9917   // need to be repeated.
9918 
9919   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9920   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9921     Bases.insert(Base);
9922     return true;
9923   };
9924 
9925   // Collect all bases. Return false if we find a dependent base.
9926   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9927     return false;
9928 
9929   // Returns true if the base is dependent or is one of the accumulated base
9930   // classes.
9931   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9932     return !Bases.count(Base);
9933   };
9934 
9935   // Return false if the class has a dependent base or if it or one
9936   // of its bases is present in the base set of the current context.
9937   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9938       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9939     return false;
9940 
9941   Diag(SS.getRange().getBegin(),
9942        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9943     << SS.getScopeRep()
9944     << cast<CXXRecordDecl>(CurContext)
9945     << SS.getRange();
9946 
9947   return true;
9948 }
9949 
9950 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9951                                   AccessSpecifier AS,
9952                                   MultiTemplateParamsArg TemplateParamLists,
9953                                   SourceLocation UsingLoc,
9954                                   UnqualifiedId &Name,
9955                                   AttributeList *AttrList,
9956                                   TypeResult Type,
9957                                   Decl *DeclFromDeclSpec) {
9958   // Skip up to the relevant declaration scope.
9959   while (S->isTemplateParamScope())
9960     S = S->getParent();
9961   assert((S->getFlags() & Scope::DeclScope) &&
9962          "got alias-declaration outside of declaration scope");
9963 
9964   if (Type.isInvalid())
9965     return nullptr;
9966 
9967   bool Invalid = false;
9968   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9969   TypeSourceInfo *TInfo = nullptr;
9970   GetTypeFromParser(Type.get(), &TInfo);
9971 
9972   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9973     return nullptr;
9974 
9975   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9976                                       UPPC_DeclarationType)) {
9977     Invalid = true;
9978     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9979                                              TInfo->getTypeLoc().getBeginLoc());
9980   }
9981 
9982   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9983   LookupName(Previous, S);
9984 
9985   // Warn about shadowing the name of a template parameter.
9986   if (Previous.isSingleResult() &&
9987       Previous.getFoundDecl()->isTemplateParameter()) {
9988     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9989     Previous.clear();
9990   }
9991 
9992   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9993          "name in alias declaration must be an identifier");
9994   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9995                                                Name.StartLocation,
9996                                                Name.Identifier, TInfo);
9997 
9998   NewTD->setAccess(AS);
9999 
10000   if (Invalid)
10001     NewTD->setInvalidDecl();
10002 
10003   ProcessDeclAttributeList(S, NewTD, AttrList);
10004   AddPragmaAttributes(S, NewTD);
10005 
10006   CheckTypedefForVariablyModifiedType(S, NewTD);
10007   Invalid |= NewTD->isInvalidDecl();
10008 
10009   bool Redeclaration = false;
10010 
10011   NamedDecl *NewND;
10012   if (TemplateParamLists.size()) {
10013     TypeAliasTemplateDecl *OldDecl = nullptr;
10014     TemplateParameterList *OldTemplateParams = nullptr;
10015 
10016     if (TemplateParamLists.size() != 1) {
10017       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10018         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10019          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10020     }
10021     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10022 
10023     // Check that we can declare a template here.
10024     if (CheckTemplateDeclScope(S, TemplateParams))
10025       return nullptr;
10026 
10027     // Only consider previous declarations in the same scope.
10028     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10029                          /*ExplicitInstantiationOrSpecialization*/false);
10030     if (!Previous.empty()) {
10031       Redeclaration = true;
10032 
10033       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10034       if (!OldDecl && !Invalid) {
10035         Diag(UsingLoc, diag::err_redefinition_different_kind)
10036           << Name.Identifier;
10037 
10038         NamedDecl *OldD = Previous.getRepresentativeDecl();
10039         if (OldD->getLocation().isValid())
10040           Diag(OldD->getLocation(), diag::note_previous_definition);
10041 
10042         Invalid = true;
10043       }
10044 
10045       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10046         if (TemplateParameterListsAreEqual(TemplateParams,
10047                                            OldDecl->getTemplateParameters(),
10048                                            /*Complain=*/true,
10049                                            TPL_TemplateMatch))
10050           OldTemplateParams = OldDecl->getTemplateParameters();
10051         else
10052           Invalid = true;
10053 
10054         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10055         if (!Invalid &&
10056             !Context.hasSameType(OldTD->getUnderlyingType(),
10057                                  NewTD->getUnderlyingType())) {
10058           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10059           // but we can't reasonably accept it.
10060           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10061             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10062           if (OldTD->getLocation().isValid())
10063             Diag(OldTD->getLocation(), diag::note_previous_definition);
10064           Invalid = true;
10065         }
10066       }
10067     }
10068 
10069     // Merge any previous default template arguments into our parameters,
10070     // and check the parameter list.
10071     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10072                                    TPC_TypeAliasTemplate))
10073       return nullptr;
10074 
10075     TypeAliasTemplateDecl *NewDecl =
10076       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10077                                     Name.Identifier, TemplateParams,
10078                                     NewTD);
10079     NewTD->setDescribedAliasTemplate(NewDecl);
10080 
10081     NewDecl->setAccess(AS);
10082 
10083     if (Invalid)
10084       NewDecl->setInvalidDecl();
10085     else if (OldDecl)
10086       NewDecl->setPreviousDecl(OldDecl);
10087 
10088     NewND = NewDecl;
10089   } else {
10090     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10091       setTagNameForLinkagePurposes(TD, NewTD);
10092       handleTagNumbering(TD, S);
10093     }
10094     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10095     NewND = NewTD;
10096   }
10097 
10098   PushOnScopeChains(NewND, S);
10099   ActOnDocumentableDecl(NewND);
10100   return NewND;
10101 }
10102 
10103 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10104                                    SourceLocation AliasLoc,
10105                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10106                                    SourceLocation IdentLoc,
10107                                    IdentifierInfo *Ident) {
10108 
10109   // Lookup the namespace name.
10110   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10111   LookupParsedName(R, S, &SS);
10112 
10113   if (R.isAmbiguous())
10114     return nullptr;
10115 
10116   if (R.empty()) {
10117     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10118       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10119       return nullptr;
10120     }
10121   }
10122   assert(!R.isAmbiguous() && !R.empty());
10123   NamedDecl *ND = R.getRepresentativeDecl();
10124 
10125   // Check if we have a previous declaration with the same name.
10126   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10127                      ForRedeclaration);
10128   LookupName(PrevR, S);
10129 
10130   // Check we're not shadowing a template parameter.
10131   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10132     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10133     PrevR.clear();
10134   }
10135 
10136   // Filter out any other lookup result from an enclosing scope.
10137   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10138                        /*AllowInlineNamespace*/false);
10139 
10140   // Find the previous declaration and check that we can redeclare it.
10141   NamespaceAliasDecl *Prev = nullptr;
10142   if (PrevR.isSingleResult()) {
10143     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10144     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10145       // We already have an alias with the same name that points to the same
10146       // namespace; check that it matches.
10147       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10148         Prev = AD;
10149       } else if (isVisible(PrevDecl)) {
10150         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10151           << Alias;
10152         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10153           << AD->getNamespace();
10154         return nullptr;
10155       }
10156     } else if (isVisible(PrevDecl)) {
10157       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10158                             ? diag::err_redefinition
10159                             : diag::err_redefinition_different_kind;
10160       Diag(AliasLoc, DiagID) << Alias;
10161       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10162       return nullptr;
10163     }
10164   }
10165 
10166   // The use of a nested name specifier may trigger deprecation warnings.
10167   DiagnoseUseOfDecl(ND, IdentLoc);
10168 
10169   NamespaceAliasDecl *AliasDecl =
10170     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10171                                Alias, SS.getWithLocInContext(Context),
10172                                IdentLoc, ND);
10173   if (Prev)
10174     AliasDecl->setPreviousDecl(Prev);
10175 
10176   PushOnScopeChains(AliasDecl, S);
10177   return AliasDecl;
10178 }
10179 
10180 namespace {
10181 struct SpecialMemberExceptionSpecInfo
10182     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10183   SourceLocation Loc;
10184   Sema::ImplicitExceptionSpecification ExceptSpec;
10185 
10186   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10187                                  Sema::CXXSpecialMember CSM,
10188                                  Sema::InheritedConstructorInfo *ICI,
10189                                  SourceLocation Loc)
10190       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10191 
10192   bool visitBase(CXXBaseSpecifier *Base);
10193   bool visitField(FieldDecl *FD);
10194 
10195   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10196                            unsigned Quals);
10197 
10198   void visitSubobjectCall(Subobject Subobj,
10199                           Sema::SpecialMemberOverloadResult SMOR);
10200 };
10201 }
10202 
10203 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10204   auto *RT = Base->getType()->getAs<RecordType>();
10205   if (!RT)
10206     return false;
10207 
10208   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10209   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10210   if (auto *BaseCtor = SMOR.getMethod()) {
10211     visitSubobjectCall(Base, BaseCtor);
10212     return false;
10213   }
10214 
10215   visitClassSubobject(BaseClass, Base, 0);
10216   return false;
10217 }
10218 
10219 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10220   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10221     Expr *E = FD->getInClassInitializer();
10222     if (!E)
10223       // FIXME: It's a little wasteful to build and throw away a
10224       // CXXDefaultInitExpr here.
10225       // FIXME: We should have a single context note pointing at Loc, and
10226       // this location should be MD->getLocation() instead, since that's
10227       // the location where we actually use the default init expression.
10228       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10229     if (E)
10230       ExceptSpec.CalledExpr(E);
10231   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10232                             ->getAs<RecordType>()) {
10233     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10234                         FD->getType().getCVRQualifiers());
10235   }
10236   return false;
10237 }
10238 
10239 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10240                                                          Subobject Subobj,
10241                                                          unsigned Quals) {
10242   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10243   bool IsMutable = Field && Field->isMutable();
10244   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10245 }
10246 
10247 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10248     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10249   // Note, if lookup fails, it doesn't matter what exception specification we
10250   // choose because the special member will be deleted.
10251   if (CXXMethodDecl *MD = SMOR.getMethod())
10252     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10253 }
10254 
10255 static Sema::ImplicitExceptionSpecification
10256 ComputeDefaultedSpecialMemberExceptionSpec(
10257     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10258     Sema::InheritedConstructorInfo *ICI) {
10259   CXXRecordDecl *ClassDecl = MD->getParent();
10260 
10261   // C++ [except.spec]p14:
10262   //   An implicitly declared special member function (Clause 12) shall have an
10263   //   exception-specification. [...]
10264   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10265   if (ClassDecl->isInvalidDecl())
10266     return Info.ExceptSpec;
10267 
10268   // C++1z [except.spec]p7:
10269   //   [Look for exceptions thrown by] a constructor selected [...] to
10270   //   initialize a potentially constructed subobject,
10271   // C++1z [except.spec]p8:
10272   //   The exception specification for an implicitly-declared destructor, or a
10273   //   destructor without a noexcept-specifier, is potentially-throwing if and
10274   //   only if any of the destructors for any of its potentially constructed
10275   //   subojects is potentially throwing.
10276   // FIXME: We respect the first rule but ignore the "potentially constructed"
10277   // in the second rule to resolve a core issue (no number yet) that would have
10278   // us reject:
10279   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10280   //   struct B : A {};
10281   //   struct C : B { void f(); };
10282   // ... due to giving B::~B() a non-throwing exception specification.
10283   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10284                                 : Info.VisitAllBases);
10285 
10286   return Info.ExceptSpec;
10287 }
10288 
10289 namespace {
10290 /// RAII object to register a special member as being currently declared.
10291 struct DeclaringSpecialMember {
10292   Sema &S;
10293   Sema::SpecialMemberDecl D;
10294   Sema::ContextRAII SavedContext;
10295   bool WasAlreadyBeingDeclared;
10296 
10297   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10298       : S(S), D(RD, CSM), SavedContext(S, RD) {
10299     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10300     if (WasAlreadyBeingDeclared)
10301       // This almost never happens, but if it does, ensure that our cache
10302       // doesn't contain a stale result.
10303       S.SpecialMemberCache.clear();
10304     else {
10305       // Register a note to be produced if we encounter an error while
10306       // declaring the special member.
10307       Sema::CodeSynthesisContext Ctx;
10308       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10309       // FIXME: We don't have a location to use here. Using the class's
10310       // location maintains the fiction that we declare all special members
10311       // with the class, but (1) it's not clear that lying about that helps our
10312       // users understand what's going on, and (2) there may be outer contexts
10313       // on the stack (some of which are relevant) and printing them exposes
10314       // our lies.
10315       Ctx.PointOfInstantiation = RD->getLocation();
10316       Ctx.Entity = RD;
10317       Ctx.SpecialMember = CSM;
10318       S.pushCodeSynthesisContext(Ctx);
10319     }
10320   }
10321   ~DeclaringSpecialMember() {
10322     if (!WasAlreadyBeingDeclared) {
10323       S.SpecialMembersBeingDeclared.erase(D);
10324       S.popCodeSynthesisContext();
10325     }
10326   }
10327 
10328   /// \brief Are we already trying to declare this special member?
10329   bool isAlreadyBeingDeclared() const {
10330     return WasAlreadyBeingDeclared;
10331   }
10332 };
10333 }
10334 
10335 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10336   // Look up any existing declarations, but don't trigger declaration of all
10337   // implicit special members with this name.
10338   DeclarationName Name = FD->getDeclName();
10339   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10340                  ForRedeclaration);
10341   for (auto *D : FD->getParent()->lookup(Name))
10342     if (auto *Acceptable = R.getAcceptableDecl(D))
10343       R.addDecl(Acceptable);
10344   R.resolveKind();
10345   R.suppressDiagnostics();
10346 
10347   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10348 }
10349 
10350 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10351                                                      CXXRecordDecl *ClassDecl) {
10352   // C++ [class.ctor]p5:
10353   //   A default constructor for a class X is a constructor of class X
10354   //   that can be called without an argument. If there is no
10355   //   user-declared constructor for class X, a default constructor is
10356   //   implicitly declared. An implicitly-declared default constructor
10357   //   is an inline public member of its class.
10358   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10359          "Should not build implicit default constructor!");
10360 
10361   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10362   if (DSM.isAlreadyBeingDeclared())
10363     return nullptr;
10364 
10365   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10366                                                      CXXDefaultConstructor,
10367                                                      false);
10368 
10369   // Create the actual constructor declaration.
10370   CanQualType ClassType
10371     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10372   SourceLocation ClassLoc = ClassDecl->getLocation();
10373   DeclarationName Name
10374     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10375   DeclarationNameInfo NameInfo(Name, ClassLoc);
10376   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10377       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10378       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10379       /*isImplicitlyDeclared=*/true, Constexpr);
10380   DefaultCon->setAccess(AS_public);
10381   DefaultCon->setDefaulted();
10382 
10383   if (getLangOpts().CUDA) {
10384     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10385                                             DefaultCon,
10386                                             /* ConstRHS */ false,
10387                                             /* Diagnose */ false);
10388   }
10389 
10390   // Build an exception specification pointing back at this constructor.
10391   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10392   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10393 
10394   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10395   // constructors is easy to compute.
10396   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10397 
10398   // Note that we have declared this constructor.
10399   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10400 
10401   Scope *S = getScopeForContext(ClassDecl);
10402   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10403 
10404   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10405     SetDeclDeleted(DefaultCon, ClassLoc);
10406 
10407   if (S)
10408     PushOnScopeChains(DefaultCon, S, false);
10409   ClassDecl->addDecl(DefaultCon);
10410 
10411   return DefaultCon;
10412 }
10413 
10414 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10415                                             CXXConstructorDecl *Constructor) {
10416   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10417           !Constructor->doesThisDeclarationHaveABody() &&
10418           !Constructor->isDeleted()) &&
10419     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10420   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10421     return;
10422 
10423   CXXRecordDecl *ClassDecl = Constructor->getParent();
10424   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10425 
10426   SynthesizedFunctionScope Scope(*this, Constructor);
10427 
10428   // The exception specification is needed because we are defining the
10429   // function.
10430   ResolveExceptionSpec(CurrentLocation,
10431                        Constructor->getType()->castAs<FunctionProtoType>());
10432   MarkVTableUsed(CurrentLocation, ClassDecl);
10433 
10434   // Add a context note for diagnostics produced after this point.
10435   Scope.addContextNote(CurrentLocation);
10436 
10437   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10438     Constructor->setInvalidDecl();
10439     return;
10440   }
10441 
10442   SourceLocation Loc = Constructor->getLocEnd().isValid()
10443                            ? Constructor->getLocEnd()
10444                            : Constructor->getLocation();
10445   Constructor->setBody(new (Context) CompoundStmt(Loc));
10446   Constructor->markUsed(Context);
10447 
10448   if (ASTMutationListener *L = getASTMutationListener()) {
10449     L->CompletedImplicitDefinition(Constructor);
10450   }
10451 
10452   DiagnoseUninitializedFields(*this, Constructor);
10453 }
10454 
10455 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10456   // Perform any delayed checks on exception specifications.
10457   CheckDelayedMemberExceptionSpecs();
10458 }
10459 
10460 /// Find or create the fake constructor we synthesize to model constructing an
10461 /// object of a derived class via a constructor of a base class.
10462 CXXConstructorDecl *
10463 Sema::findInheritingConstructor(SourceLocation Loc,
10464                                 CXXConstructorDecl *BaseCtor,
10465                                 ConstructorUsingShadowDecl *Shadow) {
10466   CXXRecordDecl *Derived = Shadow->getParent();
10467   SourceLocation UsingLoc = Shadow->getLocation();
10468 
10469   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10470   // For now we use the name of the base class constructor as a member of the
10471   // derived class to indicate a (fake) inherited constructor name.
10472   DeclarationName Name = BaseCtor->getDeclName();
10473 
10474   // Check to see if we already have a fake constructor for this inherited
10475   // constructor call.
10476   for (NamedDecl *Ctor : Derived->lookup(Name))
10477     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10478                                ->getInheritedConstructor()
10479                                .getConstructor(),
10480                            BaseCtor))
10481       return cast<CXXConstructorDecl>(Ctor);
10482 
10483   DeclarationNameInfo NameInfo(Name, UsingLoc);
10484   TypeSourceInfo *TInfo =
10485       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10486   FunctionProtoTypeLoc ProtoLoc =
10487       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10488 
10489   // Check the inherited constructor is valid and find the list of base classes
10490   // from which it was inherited.
10491   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10492 
10493   bool Constexpr =
10494       BaseCtor->isConstexpr() &&
10495       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10496                                         false, BaseCtor, &ICI);
10497 
10498   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10499       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10500       BaseCtor->isExplicit(), /*Inline=*/true,
10501       /*ImplicitlyDeclared=*/true, Constexpr,
10502       InheritedConstructor(Shadow, BaseCtor));
10503   if (Shadow->isInvalidDecl())
10504     DerivedCtor->setInvalidDecl();
10505 
10506   // Build an unevaluated exception specification for this fake constructor.
10507   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10508   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10509   EPI.ExceptionSpec.Type = EST_Unevaluated;
10510   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10511   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10512                                                FPT->getParamTypes(), EPI));
10513 
10514   // Build the parameter declarations.
10515   SmallVector<ParmVarDecl *, 16> ParamDecls;
10516   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10517     TypeSourceInfo *TInfo =
10518         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10519     ParmVarDecl *PD = ParmVarDecl::Create(
10520         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10521         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10522     PD->setScopeInfo(0, I);
10523     PD->setImplicit();
10524     // Ensure attributes are propagated onto parameters (this matters for
10525     // format, pass_object_size, ...).
10526     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10527     ParamDecls.push_back(PD);
10528     ProtoLoc.setParam(I, PD);
10529   }
10530 
10531   // Set up the new constructor.
10532   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10533   DerivedCtor->setAccess(BaseCtor->getAccess());
10534   DerivedCtor->setParams(ParamDecls);
10535   Derived->addDecl(DerivedCtor);
10536 
10537   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10538     SetDeclDeleted(DerivedCtor, UsingLoc);
10539 
10540   return DerivedCtor;
10541 }
10542 
10543 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10544   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10545                                Ctor->getInheritedConstructor().getShadowDecl());
10546   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10547                             /*Diagnose*/true);
10548 }
10549 
10550 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10551                                        CXXConstructorDecl *Constructor) {
10552   CXXRecordDecl *ClassDecl = Constructor->getParent();
10553   assert(Constructor->getInheritedConstructor() &&
10554          !Constructor->doesThisDeclarationHaveABody() &&
10555          !Constructor->isDeleted());
10556   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10557     return;
10558 
10559   // Initializations are performed "as if by a defaulted default constructor",
10560   // so enter the appropriate scope.
10561   SynthesizedFunctionScope Scope(*this, Constructor);
10562 
10563   // The exception specification is needed because we are defining the
10564   // function.
10565   ResolveExceptionSpec(CurrentLocation,
10566                        Constructor->getType()->castAs<FunctionProtoType>());
10567   MarkVTableUsed(CurrentLocation, ClassDecl);
10568 
10569   // Add a context note for diagnostics produced after this point.
10570   Scope.addContextNote(CurrentLocation);
10571 
10572   ConstructorUsingShadowDecl *Shadow =
10573       Constructor->getInheritedConstructor().getShadowDecl();
10574   CXXConstructorDecl *InheritedCtor =
10575       Constructor->getInheritedConstructor().getConstructor();
10576 
10577   // [class.inhctor.init]p1:
10578   //   initialization proceeds as if a defaulted default constructor is used to
10579   //   initialize the D object and each base class subobject from which the
10580   //   constructor was inherited
10581 
10582   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10583   CXXRecordDecl *RD = Shadow->getParent();
10584   SourceLocation InitLoc = Shadow->getLocation();
10585 
10586   // Build explicit initializers for all base classes from which the
10587   // constructor was inherited.
10588   SmallVector<CXXCtorInitializer*, 8> Inits;
10589   for (bool VBase : {false, true}) {
10590     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10591       if (B.isVirtual() != VBase)
10592         continue;
10593 
10594       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10595       if (!BaseRD)
10596         continue;
10597 
10598       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10599       if (!BaseCtor.first)
10600         continue;
10601 
10602       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10603       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10604           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10605 
10606       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10607       Inits.push_back(new (Context) CXXCtorInitializer(
10608           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10609           SourceLocation()));
10610     }
10611   }
10612 
10613   // We now proceed as if for a defaulted default constructor, with the relevant
10614   // initializers replaced.
10615 
10616   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
10617     Constructor->setInvalidDecl();
10618     return;
10619   }
10620 
10621   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10622   Constructor->markUsed(Context);
10623 
10624   if (ASTMutationListener *L = getASTMutationListener()) {
10625     L->CompletedImplicitDefinition(Constructor);
10626   }
10627 
10628   DiagnoseUninitializedFields(*this, Constructor);
10629 }
10630 
10631 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10632   // C++ [class.dtor]p2:
10633   //   If a class has no user-declared destructor, a destructor is
10634   //   declared implicitly. An implicitly-declared destructor is an
10635   //   inline public member of its class.
10636   assert(ClassDecl->needsImplicitDestructor());
10637 
10638   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10639   if (DSM.isAlreadyBeingDeclared())
10640     return nullptr;
10641 
10642   // Create the actual destructor declaration.
10643   CanQualType ClassType
10644     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10645   SourceLocation ClassLoc = ClassDecl->getLocation();
10646   DeclarationName Name
10647     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10648   DeclarationNameInfo NameInfo(Name, ClassLoc);
10649   CXXDestructorDecl *Destructor
10650       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10651                                   QualType(), nullptr, /*isInline=*/true,
10652                                   /*isImplicitlyDeclared=*/true);
10653   Destructor->setAccess(AS_public);
10654   Destructor->setDefaulted();
10655 
10656   if (getLangOpts().CUDA) {
10657     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10658                                             Destructor,
10659                                             /* ConstRHS */ false,
10660                                             /* Diagnose */ false);
10661   }
10662 
10663   // Build an exception specification pointing back at this destructor.
10664   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10665   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10666 
10667   // We don't need to use SpecialMemberIsTrivial here; triviality for
10668   // destructors is easy to compute.
10669   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10670 
10671   // Note that we have declared this destructor.
10672   ++ASTContext::NumImplicitDestructorsDeclared;
10673 
10674   Scope *S = getScopeForContext(ClassDecl);
10675   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10676 
10677   // We can't check whether an implicit destructor is deleted before we complete
10678   // the definition of the class, because its validity depends on the alignment
10679   // of the class. We'll check this from ActOnFields once the class is complete.
10680   if (ClassDecl->isCompleteDefinition() &&
10681       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10682     SetDeclDeleted(Destructor, ClassLoc);
10683 
10684   // Introduce this destructor into its scope.
10685   if (S)
10686     PushOnScopeChains(Destructor, S, false);
10687   ClassDecl->addDecl(Destructor);
10688 
10689   return Destructor;
10690 }
10691 
10692 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10693                                     CXXDestructorDecl *Destructor) {
10694   assert((Destructor->isDefaulted() &&
10695           !Destructor->doesThisDeclarationHaveABody() &&
10696           !Destructor->isDeleted()) &&
10697          "DefineImplicitDestructor - call it for implicit default dtor");
10698   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
10699     return;
10700 
10701   CXXRecordDecl *ClassDecl = Destructor->getParent();
10702   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10703 
10704   SynthesizedFunctionScope Scope(*this, Destructor);
10705 
10706   // The exception specification is needed because we are defining the
10707   // function.
10708   ResolveExceptionSpec(CurrentLocation,
10709                        Destructor->getType()->castAs<FunctionProtoType>());
10710   MarkVTableUsed(CurrentLocation, ClassDecl);
10711 
10712   // Add a context note for diagnostics produced after this point.
10713   Scope.addContextNote(CurrentLocation);
10714 
10715   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10716                                          Destructor->getParent());
10717 
10718   if (CheckDestructor(Destructor)) {
10719     Destructor->setInvalidDecl();
10720     return;
10721   }
10722 
10723   SourceLocation Loc = Destructor->getLocEnd().isValid()
10724                            ? Destructor->getLocEnd()
10725                            : Destructor->getLocation();
10726   Destructor->setBody(new (Context) CompoundStmt(Loc));
10727   Destructor->markUsed(Context);
10728 
10729   if (ASTMutationListener *L = getASTMutationListener()) {
10730     L->CompletedImplicitDefinition(Destructor);
10731   }
10732 }
10733 
10734 /// \brief Perform any semantic analysis which needs to be delayed until all
10735 /// pending class member declarations have been parsed.
10736 void Sema::ActOnFinishCXXMemberDecls() {
10737   // If the context is an invalid C++ class, just suppress these checks.
10738   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10739     if (Record->isInvalidDecl()) {
10740       DelayedDefaultedMemberExceptionSpecs.clear();
10741       DelayedExceptionSpecChecks.clear();
10742       return;
10743     }
10744     checkForMultipleExportedDefaultConstructors(*this, Record);
10745   }
10746 }
10747 
10748 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10749   referenceDLLExportedClassMethods();
10750 }
10751 
10752 void Sema::referenceDLLExportedClassMethods() {
10753   if (!DelayedDllExportClasses.empty()) {
10754     // Calling ReferenceDllExportedMethods might cause the current function to
10755     // be called again, so use a local copy of DelayedDllExportClasses.
10756     SmallVector<CXXRecordDecl *, 4> WorkList;
10757     std::swap(DelayedDllExportClasses, WorkList);
10758     for (CXXRecordDecl *Class : WorkList)
10759       ReferenceDllExportedMethods(*this, Class);
10760   }
10761 }
10762 
10763 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10764                                          CXXDestructorDecl *Destructor) {
10765   assert(getLangOpts().CPlusPlus11 &&
10766          "adjusting dtor exception specs was introduced in c++11");
10767 
10768   // C++11 [class.dtor]p3:
10769   //   A declaration of a destructor that does not have an exception-
10770   //   specification is implicitly considered to have the same exception-
10771   //   specification as an implicit declaration.
10772   const FunctionProtoType *DtorType = Destructor->getType()->
10773                                         getAs<FunctionProtoType>();
10774   if (DtorType->hasExceptionSpec())
10775     return;
10776 
10777   // Replace the destructor's type, building off the existing one. Fortunately,
10778   // the only thing of interest in the destructor type is its extended info.
10779   // The return and arguments are fixed.
10780   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10781   EPI.ExceptionSpec.Type = EST_Unevaluated;
10782   EPI.ExceptionSpec.SourceDecl = Destructor;
10783   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10784 
10785   // FIXME: If the destructor has a body that could throw, and the newly created
10786   // spec doesn't allow exceptions, we should emit a warning, because this
10787   // change in behavior can break conforming C++03 programs at runtime.
10788   // However, we don't have a body or an exception specification yet, so it
10789   // needs to be done somewhere else.
10790 }
10791 
10792 namespace {
10793 /// \brief An abstract base class for all helper classes used in building the
10794 //  copy/move operators. These classes serve as factory functions and help us
10795 //  avoid using the same Expr* in the AST twice.
10796 class ExprBuilder {
10797   ExprBuilder(const ExprBuilder&) = delete;
10798   ExprBuilder &operator=(const ExprBuilder&) = delete;
10799 
10800 protected:
10801   static Expr *assertNotNull(Expr *E) {
10802     assert(E && "Expression construction must not fail.");
10803     return E;
10804   }
10805 
10806 public:
10807   ExprBuilder() {}
10808   virtual ~ExprBuilder() {}
10809 
10810   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10811 };
10812 
10813 class RefBuilder: public ExprBuilder {
10814   VarDecl *Var;
10815   QualType VarType;
10816 
10817 public:
10818   Expr *build(Sema &S, SourceLocation Loc) const override {
10819     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10820   }
10821 
10822   RefBuilder(VarDecl *Var, QualType VarType)
10823       : Var(Var), VarType(VarType) {}
10824 };
10825 
10826 class ThisBuilder: public ExprBuilder {
10827 public:
10828   Expr *build(Sema &S, SourceLocation Loc) const override {
10829     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10830   }
10831 };
10832 
10833 class CastBuilder: public ExprBuilder {
10834   const ExprBuilder &Builder;
10835   QualType Type;
10836   ExprValueKind Kind;
10837   const CXXCastPath &Path;
10838 
10839 public:
10840   Expr *build(Sema &S, SourceLocation Loc) const override {
10841     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10842                                              CK_UncheckedDerivedToBase, Kind,
10843                                              &Path).get());
10844   }
10845 
10846   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10847               const CXXCastPath &Path)
10848       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10849 };
10850 
10851 class DerefBuilder: public ExprBuilder {
10852   const ExprBuilder &Builder;
10853 
10854 public:
10855   Expr *build(Sema &S, SourceLocation Loc) const override {
10856     return assertNotNull(
10857         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10858   }
10859 
10860   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10861 };
10862 
10863 class MemberBuilder: public ExprBuilder {
10864   const ExprBuilder &Builder;
10865   QualType Type;
10866   CXXScopeSpec SS;
10867   bool IsArrow;
10868   LookupResult &MemberLookup;
10869 
10870 public:
10871   Expr *build(Sema &S, SourceLocation Loc) const override {
10872     return assertNotNull(S.BuildMemberReferenceExpr(
10873         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10874         nullptr, MemberLookup, nullptr, nullptr).get());
10875   }
10876 
10877   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10878                 LookupResult &MemberLookup)
10879       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10880         MemberLookup(MemberLookup) {}
10881 };
10882 
10883 class MoveCastBuilder: public ExprBuilder {
10884   const ExprBuilder &Builder;
10885 
10886 public:
10887   Expr *build(Sema &S, SourceLocation Loc) const override {
10888     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10889   }
10890 
10891   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10892 };
10893 
10894 class LvalueConvBuilder: public ExprBuilder {
10895   const ExprBuilder &Builder;
10896 
10897 public:
10898   Expr *build(Sema &S, SourceLocation Loc) const override {
10899     return assertNotNull(
10900         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10901   }
10902 
10903   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10904 };
10905 
10906 class SubscriptBuilder: public ExprBuilder {
10907   const ExprBuilder &Base;
10908   const ExprBuilder &Index;
10909 
10910 public:
10911   Expr *build(Sema &S, SourceLocation Loc) const override {
10912     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10913         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10914   }
10915 
10916   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10917       : Base(Base), Index(Index) {}
10918 };
10919 
10920 } // end anonymous namespace
10921 
10922 /// When generating a defaulted copy or move assignment operator, if a field
10923 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10924 /// do so. This optimization only applies for arrays of scalars, and for arrays
10925 /// of class type where the selected copy/move-assignment operator is trivial.
10926 static StmtResult
10927 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10928                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10929   // Compute the size of the memory buffer to be copied.
10930   QualType SizeType = S.Context.getSizeType();
10931   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10932                    S.Context.getTypeSizeInChars(T).getQuantity());
10933 
10934   // Take the address of the field references for "from" and "to". We
10935   // directly construct UnaryOperators here because semantic analysis
10936   // does not permit us to take the address of an xvalue.
10937   Expr *From = FromB.build(S, Loc);
10938   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10939                          S.Context.getPointerType(From->getType()),
10940                          VK_RValue, OK_Ordinary, Loc);
10941   Expr *To = ToB.build(S, Loc);
10942   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10943                        S.Context.getPointerType(To->getType()),
10944                        VK_RValue, OK_Ordinary, Loc);
10945 
10946   const Type *E = T->getBaseElementTypeUnsafe();
10947   bool NeedsCollectableMemCpy =
10948     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10949 
10950   // Create a reference to the __builtin_objc_memmove_collectable function
10951   StringRef MemCpyName = NeedsCollectableMemCpy ?
10952     "__builtin_objc_memmove_collectable" :
10953     "__builtin_memcpy";
10954   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10955                  Sema::LookupOrdinaryName);
10956   S.LookupName(R, S.TUScope, true);
10957 
10958   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10959   if (!MemCpy)
10960     // Something went horribly wrong earlier, and we will have complained
10961     // about it.
10962     return StmtError();
10963 
10964   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10965                                             VK_RValue, Loc, nullptr);
10966   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10967 
10968   Expr *CallArgs[] = {
10969     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10970   };
10971   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10972                                     Loc, CallArgs, Loc);
10973 
10974   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10975   return Call.getAs<Stmt>();
10976 }
10977 
10978 /// \brief Builds a statement that copies/moves the given entity from \p From to
10979 /// \c To.
10980 ///
10981 /// This routine is used to copy/move the members of a class with an
10982 /// implicitly-declared copy/move assignment operator. When the entities being
10983 /// copied are arrays, this routine builds for loops to copy them.
10984 ///
10985 /// \param S The Sema object used for type-checking.
10986 ///
10987 /// \param Loc The location where the implicit copy/move is being generated.
10988 ///
10989 /// \param T The type of the expressions being copied/moved. Both expressions
10990 /// must have this type.
10991 ///
10992 /// \param To The expression we are copying/moving to.
10993 ///
10994 /// \param From The expression we are copying/moving from.
10995 ///
10996 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10997 /// Otherwise, it's a non-static member subobject.
10998 ///
10999 /// \param Copying Whether we're copying or moving.
11000 ///
11001 /// \param Depth Internal parameter recording the depth of the recursion.
11002 ///
11003 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11004 /// if a memcpy should be used instead.
11005 static StmtResult
11006 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11007                                  const ExprBuilder &To, const ExprBuilder &From,
11008                                  bool CopyingBaseSubobject, bool Copying,
11009                                  unsigned Depth = 0) {
11010   // C++11 [class.copy]p28:
11011   //   Each subobject is assigned in the manner appropriate to its type:
11012   //
11013   //     - if the subobject is of class type, as if by a call to operator= with
11014   //       the subobject as the object expression and the corresponding
11015   //       subobject of x as a single function argument (as if by explicit
11016   //       qualification; that is, ignoring any possible virtual overriding
11017   //       functions in more derived classes);
11018   //
11019   // C++03 [class.copy]p13:
11020   //     - if the subobject is of class type, the copy assignment operator for
11021   //       the class is used (as if by explicit qualification; that is,
11022   //       ignoring any possible virtual overriding functions in more derived
11023   //       classes);
11024   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11025     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11026 
11027     // Look for operator=.
11028     DeclarationName Name
11029       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11030     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11031     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11032 
11033     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11034     // operator.
11035     if (!S.getLangOpts().CPlusPlus11) {
11036       LookupResult::Filter F = OpLookup.makeFilter();
11037       while (F.hasNext()) {
11038         NamedDecl *D = F.next();
11039         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11040           if (Method->isCopyAssignmentOperator() ||
11041               (!Copying && Method->isMoveAssignmentOperator()))
11042             continue;
11043 
11044         F.erase();
11045       }
11046       F.done();
11047     }
11048 
11049     // Suppress the protected check (C++ [class.protected]) for each of the
11050     // assignment operators we found. This strange dance is required when
11051     // we're assigning via a base classes's copy-assignment operator. To
11052     // ensure that we're getting the right base class subobject (without
11053     // ambiguities), we need to cast "this" to that subobject type; to
11054     // ensure that we don't go through the virtual call mechanism, we need
11055     // to qualify the operator= name with the base class (see below). However,
11056     // this means that if the base class has a protected copy assignment
11057     // operator, the protected member access check will fail. So, we
11058     // rewrite "protected" access to "public" access in this case, since we
11059     // know by construction that we're calling from a derived class.
11060     if (CopyingBaseSubobject) {
11061       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11062            L != LEnd; ++L) {
11063         if (L.getAccess() == AS_protected)
11064           L.setAccess(AS_public);
11065       }
11066     }
11067 
11068     // Create the nested-name-specifier that will be used to qualify the
11069     // reference to operator=; this is required to suppress the virtual
11070     // call mechanism.
11071     CXXScopeSpec SS;
11072     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11073     SS.MakeTrivial(S.Context,
11074                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11075                                                CanonicalT),
11076                    Loc);
11077 
11078     // Create the reference to operator=.
11079     ExprResult OpEqualRef
11080       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11081                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11082                                    /*FirstQualifierInScope=*/nullptr,
11083                                    OpLookup,
11084                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11085                                    /*SuppressQualifierCheck=*/true);
11086     if (OpEqualRef.isInvalid())
11087       return StmtError();
11088 
11089     // Build the call to the assignment operator.
11090 
11091     Expr *FromInst = From.build(S, Loc);
11092     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11093                                                   OpEqualRef.getAs<Expr>(),
11094                                                   Loc, FromInst, Loc);
11095     if (Call.isInvalid())
11096       return StmtError();
11097 
11098     // If we built a call to a trivial 'operator=' while copying an array,
11099     // bail out. We'll replace the whole shebang with a memcpy.
11100     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11101     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11102       return StmtResult((Stmt*)nullptr);
11103 
11104     // Convert to an expression-statement, and clean up any produced
11105     // temporaries.
11106     return S.ActOnExprStmt(Call);
11107   }
11108 
11109   //     - if the subobject is of scalar type, the built-in assignment
11110   //       operator is used.
11111   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11112   if (!ArrayTy) {
11113     ExprResult Assignment = S.CreateBuiltinBinOp(
11114         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11115     if (Assignment.isInvalid())
11116       return StmtError();
11117     return S.ActOnExprStmt(Assignment);
11118   }
11119 
11120   //     - if the subobject is an array, each element is assigned, in the
11121   //       manner appropriate to the element type;
11122 
11123   // Construct a loop over the array bounds, e.g.,
11124   //
11125   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11126   //
11127   // that will copy each of the array elements.
11128   QualType SizeType = S.Context.getSizeType();
11129 
11130   // Create the iteration variable.
11131   IdentifierInfo *IterationVarName = nullptr;
11132   {
11133     SmallString<8> Str;
11134     llvm::raw_svector_ostream OS(Str);
11135     OS << "__i" << Depth;
11136     IterationVarName = &S.Context.Idents.get(OS.str());
11137   }
11138   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11139                                           IterationVarName, SizeType,
11140                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11141                                           SC_None);
11142 
11143   // Initialize the iteration variable to zero.
11144   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11145   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11146 
11147   // Creates a reference to the iteration variable.
11148   RefBuilder IterationVarRef(IterationVar, SizeType);
11149   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11150 
11151   // Create the DeclStmt that holds the iteration variable.
11152   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11153 
11154   // Subscript the "from" and "to" expressions with the iteration variable.
11155   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11156   MoveCastBuilder FromIndexMove(FromIndexCopy);
11157   const ExprBuilder *FromIndex;
11158   if (Copying)
11159     FromIndex = &FromIndexCopy;
11160   else
11161     FromIndex = &FromIndexMove;
11162 
11163   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11164 
11165   // Build the copy/move for an individual element of the array.
11166   StmtResult Copy =
11167     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11168                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11169                                      Copying, Depth + 1);
11170   // Bail out if copying fails or if we determined that we should use memcpy.
11171   if (Copy.isInvalid() || !Copy.get())
11172     return Copy;
11173 
11174   // Create the comparison against the array bound.
11175   llvm::APInt Upper
11176     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11177   Expr *Comparison
11178     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11179                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11180                                      BO_NE, S.Context.BoolTy,
11181                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11182 
11183   // Create the pre-increment of the iteration variable.
11184   Expr *Increment
11185     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11186                                     SizeType, VK_LValue, OK_Ordinary, Loc);
11187 
11188   // Construct the loop that copies all elements of this array.
11189   return S.ActOnForStmt(
11190       Loc, Loc, InitStmt,
11191       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11192       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11193 }
11194 
11195 static StmtResult
11196 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11197                       const ExprBuilder &To, const ExprBuilder &From,
11198                       bool CopyingBaseSubobject, bool Copying) {
11199   // Maybe we should use a memcpy?
11200   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11201       T.isTriviallyCopyableType(S.Context))
11202     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11203 
11204   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11205                                                      CopyingBaseSubobject,
11206                                                      Copying, 0));
11207 
11208   // If we ended up picking a trivial assignment operator for an array of a
11209   // non-trivially-copyable class type, just emit a memcpy.
11210   if (!Result.isInvalid() && !Result.get())
11211     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11212 
11213   return Result;
11214 }
11215 
11216 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11217   // Note: The following rules are largely analoguous to the copy
11218   // constructor rules. Note that virtual bases are not taken into account
11219   // for determining the argument type of the operator. Note also that
11220   // operators taking an object instead of a reference are allowed.
11221   assert(ClassDecl->needsImplicitCopyAssignment());
11222 
11223   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11224   if (DSM.isAlreadyBeingDeclared())
11225     return nullptr;
11226 
11227   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11228   QualType RetType = Context.getLValueReferenceType(ArgType);
11229   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11230   if (Const)
11231     ArgType = ArgType.withConst();
11232   ArgType = Context.getLValueReferenceType(ArgType);
11233 
11234   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11235                                                      CXXCopyAssignment,
11236                                                      Const);
11237 
11238   //   An implicitly-declared copy assignment operator is an inline public
11239   //   member of its class.
11240   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11241   SourceLocation ClassLoc = ClassDecl->getLocation();
11242   DeclarationNameInfo NameInfo(Name, ClassLoc);
11243   CXXMethodDecl *CopyAssignment =
11244       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11245                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11246                             /*isInline=*/true, Constexpr, SourceLocation());
11247   CopyAssignment->setAccess(AS_public);
11248   CopyAssignment->setDefaulted();
11249   CopyAssignment->setImplicit();
11250 
11251   if (getLangOpts().CUDA) {
11252     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11253                                             CopyAssignment,
11254                                             /* ConstRHS */ Const,
11255                                             /* Diagnose */ false);
11256   }
11257 
11258   // Build an exception specification pointing back at this member.
11259   FunctionProtoType::ExtProtoInfo EPI =
11260       getImplicitMethodEPI(*this, CopyAssignment);
11261   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11262 
11263   // Add the parameter to the operator.
11264   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11265                                                ClassLoc, ClassLoc,
11266                                                /*Id=*/nullptr, ArgType,
11267                                                /*TInfo=*/nullptr, SC_None,
11268                                                nullptr);
11269   CopyAssignment->setParams(FromParam);
11270 
11271   CopyAssignment->setTrivial(
11272     ClassDecl->needsOverloadResolutionForCopyAssignment()
11273       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11274       : ClassDecl->hasTrivialCopyAssignment());
11275 
11276   // Note that we have added this copy-assignment operator.
11277   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11278 
11279   Scope *S = getScopeForContext(ClassDecl);
11280   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11281 
11282   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11283     SetDeclDeleted(CopyAssignment, ClassLoc);
11284 
11285   if (S)
11286     PushOnScopeChains(CopyAssignment, S, false);
11287   ClassDecl->addDecl(CopyAssignment);
11288 
11289   return CopyAssignment;
11290 }
11291 
11292 /// Diagnose an implicit copy operation for a class which is odr-used, but
11293 /// which is deprecated because the class has a user-declared copy constructor,
11294 /// copy assignment operator, or destructor.
11295 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11296   assert(CopyOp->isImplicit());
11297 
11298   CXXRecordDecl *RD = CopyOp->getParent();
11299   CXXMethodDecl *UserDeclaredOperation = nullptr;
11300 
11301   // In Microsoft mode, assignment operations don't affect constructors and
11302   // vice versa.
11303   if (RD->hasUserDeclaredDestructor()) {
11304     UserDeclaredOperation = RD->getDestructor();
11305   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11306              RD->hasUserDeclaredCopyConstructor() &&
11307              !S.getLangOpts().MSVCCompat) {
11308     // Find any user-declared copy constructor.
11309     for (auto *I : RD->ctors()) {
11310       if (I->isCopyConstructor()) {
11311         UserDeclaredOperation = I;
11312         break;
11313       }
11314     }
11315     assert(UserDeclaredOperation);
11316   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11317              RD->hasUserDeclaredCopyAssignment() &&
11318              !S.getLangOpts().MSVCCompat) {
11319     // Find any user-declared move assignment operator.
11320     for (auto *I : RD->methods()) {
11321       if (I->isCopyAssignmentOperator()) {
11322         UserDeclaredOperation = I;
11323         break;
11324       }
11325     }
11326     assert(UserDeclaredOperation);
11327   }
11328 
11329   if (UserDeclaredOperation) {
11330     S.Diag(UserDeclaredOperation->getLocation(),
11331          diag::warn_deprecated_copy_operation)
11332       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11333       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11334   }
11335 }
11336 
11337 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11338                                         CXXMethodDecl *CopyAssignOperator) {
11339   assert((CopyAssignOperator->isDefaulted() &&
11340           CopyAssignOperator->isOverloadedOperator() &&
11341           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11342           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11343           !CopyAssignOperator->isDeleted()) &&
11344          "DefineImplicitCopyAssignment called for wrong function");
11345   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11346     return;
11347 
11348   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11349   if (ClassDecl->isInvalidDecl()) {
11350     CopyAssignOperator->setInvalidDecl();
11351     return;
11352   }
11353 
11354   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11355 
11356   // The exception specification is needed because we are defining the
11357   // function.
11358   ResolveExceptionSpec(CurrentLocation,
11359                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11360 
11361   // Add a context note for diagnostics produced after this point.
11362   Scope.addContextNote(CurrentLocation);
11363 
11364   // C++11 [class.copy]p18:
11365   //   The [definition of an implicitly declared copy assignment operator] is
11366   //   deprecated if the class has a user-declared copy constructor or a
11367   //   user-declared destructor.
11368   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11369     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11370 
11371   // C++0x [class.copy]p30:
11372   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11373   //   for a non-union class X performs memberwise copy assignment of its
11374   //   subobjects. The direct base classes of X are assigned first, in the
11375   //   order of their declaration in the base-specifier-list, and then the
11376   //   immediate non-static data members of X are assigned, in the order in
11377   //   which they were declared in the class definition.
11378 
11379   // The statements that form the synthesized function body.
11380   SmallVector<Stmt*, 8> Statements;
11381 
11382   // The parameter for the "other" object, which we are copying from.
11383   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11384   Qualifiers OtherQuals = Other->getType().getQualifiers();
11385   QualType OtherRefType = Other->getType();
11386   if (const LValueReferenceType *OtherRef
11387                                 = OtherRefType->getAs<LValueReferenceType>()) {
11388     OtherRefType = OtherRef->getPointeeType();
11389     OtherQuals = OtherRefType.getQualifiers();
11390   }
11391 
11392   // Our location for everything implicitly-generated.
11393   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11394                            ? CopyAssignOperator->getLocEnd()
11395                            : CopyAssignOperator->getLocation();
11396 
11397   // Builds a DeclRefExpr for the "other" object.
11398   RefBuilder OtherRef(Other, OtherRefType);
11399 
11400   // Builds the "this" pointer.
11401   ThisBuilder This;
11402 
11403   // Assign base classes.
11404   bool Invalid = false;
11405   for (auto &Base : ClassDecl->bases()) {
11406     // Form the assignment:
11407     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11408     QualType BaseType = Base.getType().getUnqualifiedType();
11409     if (!BaseType->isRecordType()) {
11410       Invalid = true;
11411       continue;
11412     }
11413 
11414     CXXCastPath BasePath;
11415     BasePath.push_back(&Base);
11416 
11417     // Construct the "from" expression, which is an implicit cast to the
11418     // appropriately-qualified base type.
11419     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11420                      VK_LValue, BasePath);
11421 
11422     // Dereference "this".
11423     DerefBuilder DerefThis(This);
11424     CastBuilder To(DerefThis,
11425                    Context.getCVRQualifiedType(
11426                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11427                    VK_LValue, BasePath);
11428 
11429     // Build the copy.
11430     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11431                                             To, From,
11432                                             /*CopyingBaseSubobject=*/true,
11433                                             /*Copying=*/true);
11434     if (Copy.isInvalid()) {
11435       CopyAssignOperator->setInvalidDecl();
11436       return;
11437     }
11438 
11439     // Success! Record the copy.
11440     Statements.push_back(Copy.getAs<Expr>());
11441   }
11442 
11443   // Assign non-static members.
11444   for (auto *Field : ClassDecl->fields()) {
11445     // FIXME: We should form some kind of AST representation for the implied
11446     // memcpy in a union copy operation.
11447     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11448       continue;
11449 
11450     if (Field->isInvalidDecl()) {
11451       Invalid = true;
11452       continue;
11453     }
11454 
11455     // Check for members of reference type; we can't copy those.
11456     if (Field->getType()->isReferenceType()) {
11457       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11458         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11459       Diag(Field->getLocation(), diag::note_declared_at);
11460       Invalid = true;
11461       continue;
11462     }
11463 
11464     // Check for members of const-qualified, non-class type.
11465     QualType BaseType = Context.getBaseElementType(Field->getType());
11466     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11467       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11468         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11469       Diag(Field->getLocation(), diag::note_declared_at);
11470       Invalid = true;
11471       continue;
11472     }
11473 
11474     // Suppress assigning zero-width bitfields.
11475     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11476       continue;
11477 
11478     QualType FieldType = Field->getType().getNonReferenceType();
11479     if (FieldType->isIncompleteArrayType()) {
11480       assert(ClassDecl->hasFlexibleArrayMember() &&
11481              "Incomplete array type is not valid");
11482       continue;
11483     }
11484 
11485     // Build references to the field in the object we're copying from and to.
11486     CXXScopeSpec SS; // Intentionally empty
11487     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11488                               LookupMemberName);
11489     MemberLookup.addDecl(Field);
11490     MemberLookup.resolveKind();
11491 
11492     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11493 
11494     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11495 
11496     // Build the copy of this field.
11497     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11498                                             To, From,
11499                                             /*CopyingBaseSubobject=*/false,
11500                                             /*Copying=*/true);
11501     if (Copy.isInvalid()) {
11502       CopyAssignOperator->setInvalidDecl();
11503       return;
11504     }
11505 
11506     // Success! Record the copy.
11507     Statements.push_back(Copy.getAs<Stmt>());
11508   }
11509 
11510   if (!Invalid) {
11511     // Add a "return *this;"
11512     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11513 
11514     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11515     if (Return.isInvalid())
11516       Invalid = true;
11517     else
11518       Statements.push_back(Return.getAs<Stmt>());
11519   }
11520 
11521   if (Invalid) {
11522     CopyAssignOperator->setInvalidDecl();
11523     return;
11524   }
11525 
11526   StmtResult Body;
11527   {
11528     CompoundScopeRAII CompoundScope(*this);
11529     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11530                              /*isStmtExpr=*/false);
11531     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11532   }
11533   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11534   CopyAssignOperator->markUsed(Context);
11535 
11536   if (ASTMutationListener *L = getASTMutationListener()) {
11537     L->CompletedImplicitDefinition(CopyAssignOperator);
11538   }
11539 }
11540 
11541 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11542   assert(ClassDecl->needsImplicitMoveAssignment());
11543 
11544   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11545   if (DSM.isAlreadyBeingDeclared())
11546     return nullptr;
11547 
11548   // Note: The following rules are largely analoguous to the move
11549   // constructor rules.
11550 
11551   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11552   QualType RetType = Context.getLValueReferenceType(ArgType);
11553   ArgType = Context.getRValueReferenceType(ArgType);
11554 
11555   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11556                                                      CXXMoveAssignment,
11557                                                      false);
11558 
11559   //   An implicitly-declared move assignment operator is an inline public
11560   //   member of its class.
11561   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11562   SourceLocation ClassLoc = ClassDecl->getLocation();
11563   DeclarationNameInfo NameInfo(Name, ClassLoc);
11564   CXXMethodDecl *MoveAssignment =
11565       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11566                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11567                             /*isInline=*/true, Constexpr, SourceLocation());
11568   MoveAssignment->setAccess(AS_public);
11569   MoveAssignment->setDefaulted();
11570   MoveAssignment->setImplicit();
11571 
11572   if (getLangOpts().CUDA) {
11573     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11574                                             MoveAssignment,
11575                                             /* ConstRHS */ false,
11576                                             /* Diagnose */ false);
11577   }
11578 
11579   // Build an exception specification pointing back at this member.
11580   FunctionProtoType::ExtProtoInfo EPI =
11581       getImplicitMethodEPI(*this, MoveAssignment);
11582   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11583 
11584   // Add the parameter to the operator.
11585   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11586                                                ClassLoc, ClassLoc,
11587                                                /*Id=*/nullptr, ArgType,
11588                                                /*TInfo=*/nullptr, SC_None,
11589                                                nullptr);
11590   MoveAssignment->setParams(FromParam);
11591 
11592   MoveAssignment->setTrivial(
11593     ClassDecl->needsOverloadResolutionForMoveAssignment()
11594       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11595       : ClassDecl->hasTrivialMoveAssignment());
11596 
11597   // Note that we have added this copy-assignment operator.
11598   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11599 
11600   Scope *S = getScopeForContext(ClassDecl);
11601   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11602 
11603   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11604     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11605     SetDeclDeleted(MoveAssignment, ClassLoc);
11606   }
11607 
11608   if (S)
11609     PushOnScopeChains(MoveAssignment, S, false);
11610   ClassDecl->addDecl(MoveAssignment);
11611 
11612   return MoveAssignment;
11613 }
11614 
11615 /// Check if we're implicitly defining a move assignment operator for a class
11616 /// with virtual bases. Such a move assignment might move-assign the virtual
11617 /// base multiple times.
11618 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11619                                                SourceLocation CurrentLocation) {
11620   assert(!Class->isDependentContext() && "should not define dependent move");
11621 
11622   // Only a virtual base could get implicitly move-assigned multiple times.
11623   // Only a non-trivial move assignment can observe this. We only want to
11624   // diagnose if we implicitly define an assignment operator that assigns
11625   // two base classes, both of which move-assign the same virtual base.
11626   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11627       Class->getNumBases() < 2)
11628     return;
11629 
11630   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11631   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11632   VBaseMap VBases;
11633 
11634   for (auto &BI : Class->bases()) {
11635     Worklist.push_back(&BI);
11636     while (!Worklist.empty()) {
11637       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11638       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11639 
11640       // If the base has no non-trivial move assignment operators,
11641       // we don't care about moves from it.
11642       if (!Base->hasNonTrivialMoveAssignment())
11643         continue;
11644 
11645       // If there's nothing virtual here, skip it.
11646       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11647         continue;
11648 
11649       // If we're not actually going to call a move assignment for this base,
11650       // or the selected move assignment is trivial, skip it.
11651       Sema::SpecialMemberOverloadResult SMOR =
11652         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11653                               /*ConstArg*/false, /*VolatileArg*/false,
11654                               /*RValueThis*/true, /*ConstThis*/false,
11655                               /*VolatileThis*/false);
11656       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11657           !SMOR.getMethod()->isMoveAssignmentOperator())
11658         continue;
11659 
11660       if (BaseSpec->isVirtual()) {
11661         // We're going to move-assign this virtual base, and its move
11662         // assignment operator is not trivial. If this can happen for
11663         // multiple distinct direct bases of Class, diagnose it. (If it
11664         // only happens in one base, we'll diagnose it when synthesizing
11665         // that base class's move assignment operator.)
11666         CXXBaseSpecifier *&Existing =
11667             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11668                 .first->second;
11669         if (Existing && Existing != &BI) {
11670           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11671             << Class << Base;
11672           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11673             << (Base->getCanonicalDecl() ==
11674                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11675             << Base << Existing->getType() << Existing->getSourceRange();
11676           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11677             << (Base->getCanonicalDecl() ==
11678                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11679             << Base << BI.getType() << BaseSpec->getSourceRange();
11680 
11681           // Only diagnose each vbase once.
11682           Existing = nullptr;
11683         }
11684       } else {
11685         // Only walk over bases that have defaulted move assignment operators.
11686         // We assume that any user-provided move assignment operator handles
11687         // the multiple-moves-of-vbase case itself somehow.
11688         if (!SMOR.getMethod()->isDefaulted())
11689           continue;
11690 
11691         // We're going to move the base classes of Base. Add them to the list.
11692         for (auto &BI : Base->bases())
11693           Worklist.push_back(&BI);
11694       }
11695     }
11696   }
11697 }
11698 
11699 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11700                                         CXXMethodDecl *MoveAssignOperator) {
11701   assert((MoveAssignOperator->isDefaulted() &&
11702           MoveAssignOperator->isOverloadedOperator() &&
11703           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11704           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11705           !MoveAssignOperator->isDeleted()) &&
11706          "DefineImplicitMoveAssignment called for wrong function");
11707   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
11708     return;
11709 
11710   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11711   if (ClassDecl->isInvalidDecl()) {
11712     MoveAssignOperator->setInvalidDecl();
11713     return;
11714   }
11715 
11716   // C++0x [class.copy]p28:
11717   //   The implicitly-defined or move assignment operator for a non-union class
11718   //   X performs memberwise move assignment of its subobjects. The direct base
11719   //   classes of X are assigned first, in the order of their declaration in the
11720   //   base-specifier-list, and then the immediate non-static data members of X
11721   //   are assigned, in the order in which they were declared in the class
11722   //   definition.
11723 
11724   // Issue a warning if our implicit move assignment operator will move
11725   // from a virtual base more than once.
11726   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11727 
11728   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11729 
11730   // The exception specification is needed because we are defining the
11731   // function.
11732   ResolveExceptionSpec(CurrentLocation,
11733                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11734 
11735   // Add a context note for diagnostics produced after this point.
11736   Scope.addContextNote(CurrentLocation);
11737 
11738   // The statements that form the synthesized function body.
11739   SmallVector<Stmt*, 8> Statements;
11740 
11741   // The parameter for the "other" object, which we are move from.
11742   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11743   QualType OtherRefType = Other->getType()->
11744       getAs<RValueReferenceType>()->getPointeeType();
11745   assert(!OtherRefType.getQualifiers() &&
11746          "Bad argument type of defaulted move assignment");
11747 
11748   // Our location for everything implicitly-generated.
11749   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11750                            ? MoveAssignOperator->getLocEnd()
11751                            : MoveAssignOperator->getLocation();
11752 
11753   // Builds a reference to the "other" object.
11754   RefBuilder OtherRef(Other, OtherRefType);
11755   // Cast to rvalue.
11756   MoveCastBuilder MoveOther(OtherRef);
11757 
11758   // Builds the "this" pointer.
11759   ThisBuilder This;
11760 
11761   // Assign base classes.
11762   bool Invalid = false;
11763   for (auto &Base : ClassDecl->bases()) {
11764     // C++11 [class.copy]p28:
11765     //   It is unspecified whether subobjects representing virtual base classes
11766     //   are assigned more than once by the implicitly-defined copy assignment
11767     //   operator.
11768     // FIXME: Do not assign to a vbase that will be assigned by some other base
11769     // class. For a move-assignment, this can result in the vbase being moved
11770     // multiple times.
11771 
11772     // Form the assignment:
11773     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11774     QualType BaseType = Base.getType().getUnqualifiedType();
11775     if (!BaseType->isRecordType()) {
11776       Invalid = true;
11777       continue;
11778     }
11779 
11780     CXXCastPath BasePath;
11781     BasePath.push_back(&Base);
11782 
11783     // Construct the "from" expression, which is an implicit cast to the
11784     // appropriately-qualified base type.
11785     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11786 
11787     // Dereference "this".
11788     DerefBuilder DerefThis(This);
11789 
11790     // Implicitly cast "this" to the appropriately-qualified base type.
11791     CastBuilder To(DerefThis,
11792                    Context.getCVRQualifiedType(
11793                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11794                    VK_LValue, BasePath);
11795 
11796     // Build the move.
11797     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11798                                             To, From,
11799                                             /*CopyingBaseSubobject=*/true,
11800                                             /*Copying=*/false);
11801     if (Move.isInvalid()) {
11802       MoveAssignOperator->setInvalidDecl();
11803       return;
11804     }
11805 
11806     // Success! Record the move.
11807     Statements.push_back(Move.getAs<Expr>());
11808   }
11809 
11810   // Assign non-static members.
11811   for (auto *Field : ClassDecl->fields()) {
11812     // FIXME: We should form some kind of AST representation for the implied
11813     // memcpy in a union copy operation.
11814     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11815       continue;
11816 
11817     if (Field->isInvalidDecl()) {
11818       Invalid = true;
11819       continue;
11820     }
11821 
11822     // Check for members of reference type; we can't move those.
11823     if (Field->getType()->isReferenceType()) {
11824       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11825         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11826       Diag(Field->getLocation(), diag::note_declared_at);
11827       Invalid = true;
11828       continue;
11829     }
11830 
11831     // Check for members of const-qualified, non-class type.
11832     QualType BaseType = Context.getBaseElementType(Field->getType());
11833     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11834       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11835         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11836       Diag(Field->getLocation(), diag::note_declared_at);
11837       Invalid = true;
11838       continue;
11839     }
11840 
11841     // Suppress assigning zero-width bitfields.
11842     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11843       continue;
11844 
11845     QualType FieldType = Field->getType().getNonReferenceType();
11846     if (FieldType->isIncompleteArrayType()) {
11847       assert(ClassDecl->hasFlexibleArrayMember() &&
11848              "Incomplete array type is not valid");
11849       continue;
11850     }
11851 
11852     // Build references to the field in the object we're copying from and to.
11853     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11854                               LookupMemberName);
11855     MemberLookup.addDecl(Field);
11856     MemberLookup.resolveKind();
11857     MemberBuilder From(MoveOther, OtherRefType,
11858                        /*IsArrow=*/false, MemberLookup);
11859     MemberBuilder To(This, getCurrentThisType(),
11860                      /*IsArrow=*/true, MemberLookup);
11861 
11862     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11863         "Member reference with rvalue base must be rvalue except for reference "
11864         "members, which aren't allowed for move assignment.");
11865 
11866     // Build the move of this field.
11867     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11868                                             To, From,
11869                                             /*CopyingBaseSubobject=*/false,
11870                                             /*Copying=*/false);
11871     if (Move.isInvalid()) {
11872       MoveAssignOperator->setInvalidDecl();
11873       return;
11874     }
11875 
11876     // Success! Record the copy.
11877     Statements.push_back(Move.getAs<Stmt>());
11878   }
11879 
11880   if (!Invalid) {
11881     // Add a "return *this;"
11882     ExprResult ThisObj =
11883         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11884 
11885     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11886     if (Return.isInvalid())
11887       Invalid = true;
11888     else
11889       Statements.push_back(Return.getAs<Stmt>());
11890   }
11891 
11892   if (Invalid) {
11893     MoveAssignOperator->setInvalidDecl();
11894     return;
11895   }
11896 
11897   StmtResult Body;
11898   {
11899     CompoundScopeRAII CompoundScope(*this);
11900     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11901                              /*isStmtExpr=*/false);
11902     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11903   }
11904   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11905   MoveAssignOperator->markUsed(Context);
11906 
11907   if (ASTMutationListener *L = getASTMutationListener()) {
11908     L->CompletedImplicitDefinition(MoveAssignOperator);
11909   }
11910 }
11911 
11912 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11913                                                     CXXRecordDecl *ClassDecl) {
11914   // C++ [class.copy]p4:
11915   //   If the class definition does not explicitly declare a copy
11916   //   constructor, one is declared implicitly.
11917   assert(ClassDecl->needsImplicitCopyConstructor());
11918 
11919   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11920   if (DSM.isAlreadyBeingDeclared())
11921     return nullptr;
11922 
11923   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11924   QualType ArgType = ClassType;
11925   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11926   if (Const)
11927     ArgType = ArgType.withConst();
11928   ArgType = Context.getLValueReferenceType(ArgType);
11929 
11930   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11931                                                      CXXCopyConstructor,
11932                                                      Const);
11933 
11934   DeclarationName Name
11935     = Context.DeclarationNames.getCXXConstructorName(
11936                                            Context.getCanonicalType(ClassType));
11937   SourceLocation ClassLoc = ClassDecl->getLocation();
11938   DeclarationNameInfo NameInfo(Name, ClassLoc);
11939 
11940   //   An implicitly-declared copy constructor is an inline public
11941   //   member of its class.
11942   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11943       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11944       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11945       Constexpr);
11946   CopyConstructor->setAccess(AS_public);
11947   CopyConstructor->setDefaulted();
11948 
11949   if (getLangOpts().CUDA) {
11950     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11951                                             CopyConstructor,
11952                                             /* ConstRHS */ Const,
11953                                             /* Diagnose */ false);
11954   }
11955 
11956   // Build an exception specification pointing back at this member.
11957   FunctionProtoType::ExtProtoInfo EPI =
11958       getImplicitMethodEPI(*this, CopyConstructor);
11959   CopyConstructor->setType(
11960       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11961 
11962   // Add the parameter to the constructor.
11963   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11964                                                ClassLoc, ClassLoc,
11965                                                /*IdentifierInfo=*/nullptr,
11966                                                ArgType, /*TInfo=*/nullptr,
11967                                                SC_None, nullptr);
11968   CopyConstructor->setParams(FromParam);
11969 
11970   CopyConstructor->setTrivial(
11971     ClassDecl->needsOverloadResolutionForCopyConstructor()
11972       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11973       : ClassDecl->hasTrivialCopyConstructor());
11974 
11975   // Note that we have declared this constructor.
11976   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11977 
11978   Scope *S = getScopeForContext(ClassDecl);
11979   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11980 
11981   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
11982     ClassDecl->setImplicitCopyConstructorIsDeleted();
11983     SetDeclDeleted(CopyConstructor, ClassLoc);
11984   }
11985 
11986   if (S)
11987     PushOnScopeChains(CopyConstructor, S, false);
11988   ClassDecl->addDecl(CopyConstructor);
11989 
11990   return CopyConstructor;
11991 }
11992 
11993 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11994                                          CXXConstructorDecl *CopyConstructor) {
11995   assert((CopyConstructor->isDefaulted() &&
11996           CopyConstructor->isCopyConstructor() &&
11997           !CopyConstructor->doesThisDeclarationHaveABody() &&
11998           !CopyConstructor->isDeleted()) &&
11999          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12000   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12001     return;
12002 
12003   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12004   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12005 
12006   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12007 
12008   // The exception specification is needed because we are defining the
12009   // function.
12010   ResolveExceptionSpec(CurrentLocation,
12011                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12012   MarkVTableUsed(CurrentLocation, ClassDecl);
12013 
12014   // Add a context note for diagnostics produced after this point.
12015   Scope.addContextNote(CurrentLocation);
12016 
12017   // C++11 [class.copy]p7:
12018   //   The [definition of an implicitly declared copy constructor] is
12019   //   deprecated if the class has a user-declared copy assignment operator
12020   //   or a user-declared destructor.
12021   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12022     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12023 
12024   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12025     CopyConstructor->setInvalidDecl();
12026   }  else {
12027     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12028                              ? CopyConstructor->getLocEnd()
12029                              : CopyConstructor->getLocation();
12030     Sema::CompoundScopeRAII CompoundScope(*this);
12031     CopyConstructor->setBody(
12032         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12033     CopyConstructor->markUsed(Context);
12034   }
12035 
12036   if (ASTMutationListener *L = getASTMutationListener()) {
12037     L->CompletedImplicitDefinition(CopyConstructor);
12038   }
12039 }
12040 
12041 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12042                                                     CXXRecordDecl *ClassDecl) {
12043   assert(ClassDecl->needsImplicitMoveConstructor());
12044 
12045   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12046   if (DSM.isAlreadyBeingDeclared())
12047     return nullptr;
12048 
12049   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12050   QualType ArgType = Context.getRValueReferenceType(ClassType);
12051 
12052   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12053                                                      CXXMoveConstructor,
12054                                                      false);
12055 
12056   DeclarationName Name
12057     = Context.DeclarationNames.getCXXConstructorName(
12058                                            Context.getCanonicalType(ClassType));
12059   SourceLocation ClassLoc = ClassDecl->getLocation();
12060   DeclarationNameInfo NameInfo(Name, ClassLoc);
12061 
12062   // C++11 [class.copy]p11:
12063   //   An implicitly-declared copy/move constructor is an inline public
12064   //   member of its class.
12065   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12066       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12067       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12068       Constexpr);
12069   MoveConstructor->setAccess(AS_public);
12070   MoveConstructor->setDefaulted();
12071 
12072   if (getLangOpts().CUDA) {
12073     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12074                                             MoveConstructor,
12075                                             /* ConstRHS */ false,
12076                                             /* Diagnose */ false);
12077   }
12078 
12079   // Build an exception specification pointing back at this member.
12080   FunctionProtoType::ExtProtoInfo EPI =
12081       getImplicitMethodEPI(*this, MoveConstructor);
12082   MoveConstructor->setType(
12083       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12084 
12085   // Add the parameter to the constructor.
12086   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12087                                                ClassLoc, ClassLoc,
12088                                                /*IdentifierInfo=*/nullptr,
12089                                                ArgType, /*TInfo=*/nullptr,
12090                                                SC_None, nullptr);
12091   MoveConstructor->setParams(FromParam);
12092 
12093   MoveConstructor->setTrivial(
12094     ClassDecl->needsOverloadResolutionForMoveConstructor()
12095       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12096       : ClassDecl->hasTrivialMoveConstructor());
12097 
12098   // Note that we have declared this constructor.
12099   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12100 
12101   Scope *S = getScopeForContext(ClassDecl);
12102   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12103 
12104   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12105     ClassDecl->setImplicitMoveConstructorIsDeleted();
12106     SetDeclDeleted(MoveConstructor, ClassLoc);
12107   }
12108 
12109   if (S)
12110     PushOnScopeChains(MoveConstructor, S, false);
12111   ClassDecl->addDecl(MoveConstructor);
12112 
12113   return MoveConstructor;
12114 }
12115 
12116 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12117                                          CXXConstructorDecl *MoveConstructor) {
12118   assert((MoveConstructor->isDefaulted() &&
12119           MoveConstructor->isMoveConstructor() &&
12120           !MoveConstructor->doesThisDeclarationHaveABody() &&
12121           !MoveConstructor->isDeleted()) &&
12122          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12123   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12124     return;
12125 
12126   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12127   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12128 
12129   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12130 
12131   // The exception specification is needed because we are defining the
12132   // function.
12133   ResolveExceptionSpec(CurrentLocation,
12134                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12135   MarkVTableUsed(CurrentLocation, ClassDecl);
12136 
12137   // Add a context note for diagnostics produced after this point.
12138   Scope.addContextNote(CurrentLocation);
12139 
12140   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12141     MoveConstructor->setInvalidDecl();
12142   } else {
12143     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12144                              ? MoveConstructor->getLocEnd()
12145                              : MoveConstructor->getLocation();
12146     Sema::CompoundScopeRAII CompoundScope(*this);
12147     MoveConstructor->setBody(ActOnCompoundStmt(
12148         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12149     MoveConstructor->markUsed(Context);
12150   }
12151 
12152   if (ASTMutationListener *L = getASTMutationListener()) {
12153     L->CompletedImplicitDefinition(MoveConstructor);
12154   }
12155 }
12156 
12157 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12158   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12159 }
12160 
12161 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12162                             SourceLocation CurrentLocation,
12163                             CXXConversionDecl *Conv) {
12164   SynthesizedFunctionScope Scope(*this, Conv);
12165 
12166   CXXRecordDecl *Lambda = Conv->getParent();
12167   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12168   // If we are defining a specialization of a conversion to function-ptr
12169   // cache the deduced template arguments for this specialization
12170   // so that we can use them to retrieve the corresponding call-operator
12171   // and static-invoker.
12172   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12173 
12174   // Retrieve the corresponding call-operator specialization.
12175   if (Lambda->isGenericLambda()) {
12176     assert(Conv->isFunctionTemplateSpecialization());
12177     FunctionTemplateDecl *CallOpTemplate =
12178         CallOp->getDescribedFunctionTemplate();
12179     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12180     void *InsertPos = nullptr;
12181     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12182                                                 DeducedTemplateArgs->asArray(),
12183                                                 InsertPos);
12184     assert(CallOpSpec &&
12185           "Conversion operator must have a corresponding call operator");
12186     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12187   }
12188 
12189   // Mark the call operator referenced (and add to pending instantiations
12190   // if necessary).
12191   // For both the conversion and static-invoker template specializations
12192   // we construct their body's in this function, so no need to add them
12193   // to the PendingInstantiations.
12194   MarkFunctionReferenced(CurrentLocation, CallOp);
12195 
12196   // Retrieve the static invoker...
12197   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12198   // ... and get the corresponding specialization for a generic lambda.
12199   if (Lambda->isGenericLambda()) {
12200     assert(DeducedTemplateArgs &&
12201       "Must have deduced template arguments from Conversion Operator");
12202     FunctionTemplateDecl *InvokeTemplate =
12203                           Invoker->getDescribedFunctionTemplate();
12204     void *InsertPos = nullptr;
12205     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12206                                                 DeducedTemplateArgs->asArray(),
12207                                                 InsertPos);
12208     assert(InvokeSpec &&
12209       "Must have a corresponding static invoker specialization");
12210     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12211   }
12212   // Construct the body of the conversion function { return __invoke; }.
12213   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12214                                         VK_LValue, Conv->getLocation()).get();
12215    assert(FunctionRef && "Can't refer to __invoke function?");
12216    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12217    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12218                                             Conv->getLocation(),
12219                                             Conv->getLocation()));
12220 
12221   Conv->markUsed(Context);
12222   Conv->setReferenced();
12223 
12224   // Fill in the __invoke function with a dummy implementation. IR generation
12225   // will fill in the actual details.
12226   Invoker->markUsed(Context);
12227   Invoker->setReferenced();
12228   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12229 
12230   if (ASTMutationListener *L = getASTMutationListener()) {
12231     L->CompletedImplicitDefinition(Conv);
12232     L->CompletedImplicitDefinition(Invoker);
12233   }
12234 }
12235 
12236 
12237 
12238 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12239        SourceLocation CurrentLocation,
12240        CXXConversionDecl *Conv)
12241 {
12242   assert(!Conv->getParent()->isGenericLambda());
12243 
12244   SynthesizedFunctionScope Scope(*this, Conv);
12245 
12246   // Copy-initialize the lambda object as needed to capture it.
12247   Expr *This = ActOnCXXThis(CurrentLocation).get();
12248   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12249 
12250   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12251                                                         Conv->getLocation(),
12252                                                         Conv, DerefThis);
12253 
12254   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12255   // behavior.  Note that only the general conversion function does this
12256   // (since it's unusable otherwise); in the case where we inline the
12257   // block literal, it has block literal lifetime semantics.
12258   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12259     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12260                                           CK_CopyAndAutoreleaseBlockObject,
12261                                           BuildBlock.get(), nullptr, VK_RValue);
12262 
12263   if (BuildBlock.isInvalid()) {
12264     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12265     Conv->setInvalidDecl();
12266     return;
12267   }
12268 
12269   // Create the return statement that returns the block from the conversion
12270   // function.
12271   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12272   if (Return.isInvalid()) {
12273     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12274     Conv->setInvalidDecl();
12275     return;
12276   }
12277 
12278   // Set the body of the conversion function.
12279   Stmt *ReturnS = Return.get();
12280   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12281                                            Conv->getLocation(),
12282                                            Conv->getLocation()));
12283   Conv->markUsed(Context);
12284 
12285   // We're done; notify the mutation listener, if any.
12286   if (ASTMutationListener *L = getASTMutationListener()) {
12287     L->CompletedImplicitDefinition(Conv);
12288   }
12289 }
12290 
12291 /// \brief Determine whether the given list arguments contains exactly one
12292 /// "real" (non-default) argument.
12293 static bool hasOneRealArgument(MultiExprArg Args) {
12294   switch (Args.size()) {
12295   case 0:
12296     return false;
12297 
12298   default:
12299     if (!Args[1]->isDefaultArgument())
12300       return false;
12301 
12302     // fall through
12303   case 1:
12304     return !Args[0]->isDefaultArgument();
12305   }
12306 
12307   return false;
12308 }
12309 
12310 ExprResult
12311 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12312                             NamedDecl *FoundDecl,
12313                             CXXConstructorDecl *Constructor,
12314                             MultiExprArg ExprArgs,
12315                             bool HadMultipleCandidates,
12316                             bool IsListInitialization,
12317                             bool IsStdInitListInitialization,
12318                             bool RequiresZeroInit,
12319                             unsigned ConstructKind,
12320                             SourceRange ParenRange) {
12321   bool Elidable = false;
12322 
12323   // C++0x [class.copy]p34:
12324   //   When certain criteria are met, an implementation is allowed to
12325   //   omit the copy/move construction of a class object, even if the
12326   //   copy/move constructor and/or destructor for the object have
12327   //   side effects. [...]
12328   //     - when a temporary class object that has not been bound to a
12329   //       reference (12.2) would be copied/moved to a class object
12330   //       with the same cv-unqualified type, the copy/move operation
12331   //       can be omitted by constructing the temporary object
12332   //       directly into the target of the omitted copy/move
12333   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12334       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12335     Expr *SubExpr = ExprArgs[0];
12336     Elidable = SubExpr->isTemporaryObject(
12337         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12338   }
12339 
12340   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12341                                FoundDecl, Constructor,
12342                                Elidable, ExprArgs, HadMultipleCandidates,
12343                                IsListInitialization,
12344                                IsStdInitListInitialization, RequiresZeroInit,
12345                                ConstructKind, ParenRange);
12346 }
12347 
12348 ExprResult
12349 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12350                             NamedDecl *FoundDecl,
12351                             CXXConstructorDecl *Constructor,
12352                             bool Elidable,
12353                             MultiExprArg ExprArgs,
12354                             bool HadMultipleCandidates,
12355                             bool IsListInitialization,
12356                             bool IsStdInitListInitialization,
12357                             bool RequiresZeroInit,
12358                             unsigned ConstructKind,
12359                             SourceRange ParenRange) {
12360   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12361     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12362     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12363       return ExprError();
12364   }
12365 
12366   return BuildCXXConstructExpr(
12367       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12368       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12369       RequiresZeroInit, ConstructKind, ParenRange);
12370 }
12371 
12372 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12373 /// including handling of its default argument expressions.
12374 ExprResult
12375 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12376                             CXXConstructorDecl *Constructor,
12377                             bool Elidable,
12378                             MultiExprArg ExprArgs,
12379                             bool HadMultipleCandidates,
12380                             bool IsListInitialization,
12381                             bool IsStdInitListInitialization,
12382                             bool RequiresZeroInit,
12383                             unsigned ConstructKind,
12384                             SourceRange ParenRange) {
12385   assert(declaresSameEntity(
12386              Constructor->getParent(),
12387              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12388          "given constructor for wrong type");
12389   MarkFunctionReferenced(ConstructLoc, Constructor);
12390   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12391     return ExprError();
12392 
12393   return CXXConstructExpr::Create(
12394       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12395       ExprArgs, HadMultipleCandidates, IsListInitialization,
12396       IsStdInitListInitialization, RequiresZeroInit,
12397       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12398       ParenRange);
12399 }
12400 
12401 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12402   assert(Field->hasInClassInitializer());
12403 
12404   // If we already have the in-class initializer nothing needs to be done.
12405   if (Field->getInClassInitializer())
12406     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12407 
12408   // If we might have already tried and failed to instantiate, don't try again.
12409   if (Field->isInvalidDecl())
12410     return ExprError();
12411 
12412   // Maybe we haven't instantiated the in-class initializer. Go check the
12413   // pattern FieldDecl to see if it has one.
12414   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12415 
12416   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12417     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12418     DeclContext::lookup_result Lookup =
12419         ClassPattern->lookup(Field->getDeclName());
12420 
12421     // Lookup can return at most two results: the pattern for the field, or the
12422     // injected class name of the parent record. No other member can have the
12423     // same name as the field.
12424     // In modules mode, lookup can return multiple results (coming from
12425     // different modules).
12426     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12427            "more than two lookup results for field name");
12428     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12429     if (!Pattern) {
12430       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12431              "cannot have other non-field member with same name");
12432       for (auto L : Lookup)
12433         if (isa<FieldDecl>(L)) {
12434           Pattern = cast<FieldDecl>(L);
12435           break;
12436         }
12437       assert(Pattern && "We must have set the Pattern!");
12438     }
12439 
12440     if (!Pattern->hasInClassInitializer() ||
12441         InstantiateInClassInitializer(Loc, Field, Pattern,
12442                                       getTemplateInstantiationArgs(Field))) {
12443       // Don't diagnose this again.
12444       Field->setInvalidDecl();
12445       return ExprError();
12446     }
12447     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12448   }
12449 
12450   // DR1351:
12451   //   If the brace-or-equal-initializer of a non-static data member
12452   //   invokes a defaulted default constructor of its class or of an
12453   //   enclosing class in a potentially evaluated subexpression, the
12454   //   program is ill-formed.
12455   //
12456   // This resolution is unworkable: the exception specification of the
12457   // default constructor can be needed in an unevaluated context, in
12458   // particular, in the operand of a noexcept-expression, and we can be
12459   // unable to compute an exception specification for an enclosed class.
12460   //
12461   // Any attempt to resolve the exception specification of a defaulted default
12462   // constructor before the initializer is lexically complete will ultimately
12463   // come here at which point we can diagnose it.
12464   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12465   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12466       << OutermostClass << Field;
12467   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12468   // Recover by marking the field invalid, unless we're in a SFINAE context.
12469   if (!isSFINAEContext())
12470     Field->setInvalidDecl();
12471   return ExprError();
12472 }
12473 
12474 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12475   if (VD->isInvalidDecl()) return;
12476 
12477   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12478   if (ClassDecl->isInvalidDecl()) return;
12479   if (ClassDecl->hasIrrelevantDestructor()) return;
12480   if (ClassDecl->isDependentContext()) return;
12481 
12482   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12483   MarkFunctionReferenced(VD->getLocation(), Destructor);
12484   CheckDestructorAccess(VD->getLocation(), Destructor,
12485                         PDiag(diag::err_access_dtor_var)
12486                         << VD->getDeclName()
12487                         << VD->getType());
12488   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12489 
12490   if (Destructor->isTrivial()) return;
12491   if (!VD->hasGlobalStorage()) return;
12492 
12493   // Emit warning for non-trivial dtor in global scope (a real global,
12494   // class-static, function-static).
12495   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12496 
12497   // TODO: this should be re-enabled for static locals by !CXAAtExit
12498   if (!VD->isStaticLocal())
12499     Diag(VD->getLocation(), diag::warn_global_destructor);
12500 }
12501 
12502 /// \brief Given a constructor and the set of arguments provided for the
12503 /// constructor, convert the arguments and add any required default arguments
12504 /// to form a proper call to this constructor.
12505 ///
12506 /// \returns true if an error occurred, false otherwise.
12507 bool
12508 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12509                               MultiExprArg ArgsPtr,
12510                               SourceLocation Loc,
12511                               SmallVectorImpl<Expr*> &ConvertedArgs,
12512                               bool AllowExplicit,
12513                               bool IsListInitialization) {
12514   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12515   unsigned NumArgs = ArgsPtr.size();
12516   Expr **Args = ArgsPtr.data();
12517 
12518   const FunctionProtoType *Proto
12519     = Constructor->getType()->getAs<FunctionProtoType>();
12520   assert(Proto && "Constructor without a prototype?");
12521   unsigned NumParams = Proto->getNumParams();
12522 
12523   // If too few arguments are available, we'll fill in the rest with defaults.
12524   if (NumArgs < NumParams)
12525     ConvertedArgs.reserve(NumParams);
12526   else
12527     ConvertedArgs.reserve(NumArgs);
12528 
12529   VariadicCallType CallType =
12530     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12531   SmallVector<Expr *, 8> AllArgs;
12532   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12533                                         Proto, 0,
12534                                         llvm::makeArrayRef(Args, NumArgs),
12535                                         AllArgs,
12536                                         CallType, AllowExplicit,
12537                                         IsListInitialization);
12538   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12539 
12540   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12541 
12542   CheckConstructorCall(Constructor,
12543                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12544                        Proto, Loc);
12545 
12546   return Invalid;
12547 }
12548 
12549 static inline bool
12550 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12551                                        const FunctionDecl *FnDecl) {
12552   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12553   if (isa<NamespaceDecl>(DC)) {
12554     return SemaRef.Diag(FnDecl->getLocation(),
12555                         diag::err_operator_new_delete_declared_in_namespace)
12556       << FnDecl->getDeclName();
12557   }
12558 
12559   if (isa<TranslationUnitDecl>(DC) &&
12560       FnDecl->getStorageClass() == SC_Static) {
12561     return SemaRef.Diag(FnDecl->getLocation(),
12562                         diag::err_operator_new_delete_declared_static)
12563       << FnDecl->getDeclName();
12564   }
12565 
12566   return false;
12567 }
12568 
12569 static inline bool
12570 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12571                             CanQualType ExpectedResultType,
12572                             CanQualType ExpectedFirstParamType,
12573                             unsigned DependentParamTypeDiag,
12574                             unsigned InvalidParamTypeDiag) {
12575   QualType ResultType =
12576       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12577 
12578   // Check that the result type is not dependent.
12579   if (ResultType->isDependentType())
12580     return SemaRef.Diag(FnDecl->getLocation(),
12581                         diag::err_operator_new_delete_dependent_result_type)
12582     << FnDecl->getDeclName() << ExpectedResultType;
12583 
12584   // Check that the result type is what we expect.
12585   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12586     return SemaRef.Diag(FnDecl->getLocation(),
12587                         diag::err_operator_new_delete_invalid_result_type)
12588     << FnDecl->getDeclName() << ExpectedResultType;
12589 
12590   // A function template must have at least 2 parameters.
12591   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12592     return SemaRef.Diag(FnDecl->getLocation(),
12593                       diag::err_operator_new_delete_template_too_few_parameters)
12594         << FnDecl->getDeclName();
12595 
12596   // The function decl must have at least 1 parameter.
12597   if (FnDecl->getNumParams() == 0)
12598     return SemaRef.Diag(FnDecl->getLocation(),
12599                         diag::err_operator_new_delete_too_few_parameters)
12600       << FnDecl->getDeclName();
12601 
12602   // Check the first parameter type is not dependent.
12603   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12604   if (FirstParamType->isDependentType())
12605     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12606       << FnDecl->getDeclName() << ExpectedFirstParamType;
12607 
12608   // Check that the first parameter type is what we expect.
12609   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12610       ExpectedFirstParamType)
12611     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12612     << FnDecl->getDeclName() << ExpectedFirstParamType;
12613 
12614   return false;
12615 }
12616 
12617 static bool
12618 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12619   // C++ [basic.stc.dynamic.allocation]p1:
12620   //   A program is ill-formed if an allocation function is declared in a
12621   //   namespace scope other than global scope or declared static in global
12622   //   scope.
12623   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12624     return true;
12625 
12626   CanQualType SizeTy =
12627     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12628 
12629   // C++ [basic.stc.dynamic.allocation]p1:
12630   //  The return type shall be void*. The first parameter shall have type
12631   //  std::size_t.
12632   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12633                                   SizeTy,
12634                                   diag::err_operator_new_dependent_param_type,
12635                                   diag::err_operator_new_param_type))
12636     return true;
12637 
12638   // C++ [basic.stc.dynamic.allocation]p1:
12639   //  The first parameter shall not have an associated default argument.
12640   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12641     return SemaRef.Diag(FnDecl->getLocation(),
12642                         diag::err_operator_new_default_arg)
12643       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12644 
12645   return false;
12646 }
12647 
12648 static bool
12649 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12650   // C++ [basic.stc.dynamic.deallocation]p1:
12651   //   A program is ill-formed if deallocation functions are declared in a
12652   //   namespace scope other than global scope or declared static in global
12653   //   scope.
12654   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12655     return true;
12656 
12657   // C++ [basic.stc.dynamic.deallocation]p2:
12658   //   Each deallocation function shall return void and its first parameter
12659   //   shall be void*.
12660   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12661                                   SemaRef.Context.VoidPtrTy,
12662                                  diag::err_operator_delete_dependent_param_type,
12663                                  diag::err_operator_delete_param_type))
12664     return true;
12665 
12666   return false;
12667 }
12668 
12669 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12670 /// of this overloaded operator is well-formed. If so, returns false;
12671 /// otherwise, emits appropriate diagnostics and returns true.
12672 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12673   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12674          "Expected an overloaded operator declaration");
12675 
12676   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12677 
12678   // C++ [over.oper]p5:
12679   //   The allocation and deallocation functions, operator new,
12680   //   operator new[], operator delete and operator delete[], are
12681   //   described completely in 3.7.3. The attributes and restrictions
12682   //   found in the rest of this subclause do not apply to them unless
12683   //   explicitly stated in 3.7.3.
12684   if (Op == OO_Delete || Op == OO_Array_Delete)
12685     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12686 
12687   if (Op == OO_New || Op == OO_Array_New)
12688     return CheckOperatorNewDeclaration(*this, FnDecl);
12689 
12690   // C++ [over.oper]p6:
12691   //   An operator function shall either be a non-static member
12692   //   function or be a non-member function and have at least one
12693   //   parameter whose type is a class, a reference to a class, an
12694   //   enumeration, or a reference to an enumeration.
12695   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12696     if (MethodDecl->isStatic())
12697       return Diag(FnDecl->getLocation(),
12698                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12699   } else {
12700     bool ClassOrEnumParam = false;
12701     for (auto Param : FnDecl->parameters()) {
12702       QualType ParamType = Param->getType().getNonReferenceType();
12703       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12704           ParamType->isEnumeralType()) {
12705         ClassOrEnumParam = true;
12706         break;
12707       }
12708     }
12709 
12710     if (!ClassOrEnumParam)
12711       return Diag(FnDecl->getLocation(),
12712                   diag::err_operator_overload_needs_class_or_enum)
12713         << FnDecl->getDeclName();
12714   }
12715 
12716   // C++ [over.oper]p8:
12717   //   An operator function cannot have default arguments (8.3.6),
12718   //   except where explicitly stated below.
12719   //
12720   // Only the function-call operator allows default arguments
12721   // (C++ [over.call]p1).
12722   if (Op != OO_Call) {
12723     for (auto Param : FnDecl->parameters()) {
12724       if (Param->hasDefaultArg())
12725         return Diag(Param->getLocation(),
12726                     diag::err_operator_overload_default_arg)
12727           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12728     }
12729   }
12730 
12731   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12732     { false, false, false }
12733 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12734     , { Unary, Binary, MemberOnly }
12735 #include "clang/Basic/OperatorKinds.def"
12736   };
12737 
12738   bool CanBeUnaryOperator = OperatorUses[Op][0];
12739   bool CanBeBinaryOperator = OperatorUses[Op][1];
12740   bool MustBeMemberOperator = OperatorUses[Op][2];
12741 
12742   // C++ [over.oper]p8:
12743   //   [...] Operator functions cannot have more or fewer parameters
12744   //   than the number required for the corresponding operator, as
12745   //   described in the rest of this subclause.
12746   unsigned NumParams = FnDecl->getNumParams()
12747                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12748   if (Op != OO_Call &&
12749       ((NumParams == 1 && !CanBeUnaryOperator) ||
12750        (NumParams == 2 && !CanBeBinaryOperator) ||
12751        (NumParams < 1) || (NumParams > 2))) {
12752     // We have the wrong number of parameters.
12753     unsigned ErrorKind;
12754     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12755       ErrorKind = 2;  // 2 -> unary or binary.
12756     } else if (CanBeUnaryOperator) {
12757       ErrorKind = 0;  // 0 -> unary
12758     } else {
12759       assert(CanBeBinaryOperator &&
12760              "All non-call overloaded operators are unary or binary!");
12761       ErrorKind = 1;  // 1 -> binary
12762     }
12763 
12764     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12765       << FnDecl->getDeclName() << NumParams << ErrorKind;
12766   }
12767 
12768   // Overloaded operators other than operator() cannot be variadic.
12769   if (Op != OO_Call &&
12770       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12771     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12772       << FnDecl->getDeclName();
12773   }
12774 
12775   // Some operators must be non-static member functions.
12776   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12777     return Diag(FnDecl->getLocation(),
12778                 diag::err_operator_overload_must_be_member)
12779       << FnDecl->getDeclName();
12780   }
12781 
12782   // C++ [over.inc]p1:
12783   //   The user-defined function called operator++ implements the
12784   //   prefix and postfix ++ operator. If this function is a member
12785   //   function with no parameters, or a non-member function with one
12786   //   parameter of class or enumeration type, it defines the prefix
12787   //   increment operator ++ for objects of that type. If the function
12788   //   is a member function with one parameter (which shall be of type
12789   //   int) or a non-member function with two parameters (the second
12790   //   of which shall be of type int), it defines the postfix
12791   //   increment operator ++ for objects of that type.
12792   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12793     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12794     QualType ParamType = LastParam->getType();
12795 
12796     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12797         !ParamType->isDependentType())
12798       return Diag(LastParam->getLocation(),
12799                   diag::err_operator_overload_post_incdec_must_be_int)
12800         << LastParam->getType() << (Op == OO_MinusMinus);
12801   }
12802 
12803   return false;
12804 }
12805 
12806 static bool
12807 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12808                                           FunctionTemplateDecl *TpDecl) {
12809   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12810 
12811   // Must have one or two template parameters.
12812   if (TemplateParams->size() == 1) {
12813     NonTypeTemplateParmDecl *PmDecl =
12814         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12815 
12816     // The template parameter must be a char parameter pack.
12817     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12818         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12819       return false;
12820 
12821   } else if (TemplateParams->size() == 2) {
12822     TemplateTypeParmDecl *PmType =
12823         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12824     NonTypeTemplateParmDecl *PmArgs =
12825         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12826 
12827     // The second template parameter must be a parameter pack with the
12828     // first template parameter as its type.
12829     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12830         PmArgs->isTemplateParameterPack()) {
12831       const TemplateTypeParmType *TArgs =
12832           PmArgs->getType()->getAs<TemplateTypeParmType>();
12833       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12834           TArgs->getIndex() == PmType->getIndex()) {
12835         if (!SemaRef.inTemplateInstantiation())
12836           SemaRef.Diag(TpDecl->getLocation(),
12837                        diag::ext_string_literal_operator_template);
12838         return false;
12839       }
12840     }
12841   }
12842 
12843   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12844                diag::err_literal_operator_template)
12845       << TpDecl->getTemplateParameters()->getSourceRange();
12846   return true;
12847 }
12848 
12849 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12850 /// of this literal operator function is well-formed. If so, returns
12851 /// false; otherwise, emits appropriate diagnostics and returns true.
12852 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12853   if (isa<CXXMethodDecl>(FnDecl)) {
12854     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12855       << FnDecl->getDeclName();
12856     return true;
12857   }
12858 
12859   if (FnDecl->isExternC()) {
12860     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12861     if (const LinkageSpecDecl *LSD =
12862             FnDecl->getDeclContext()->getExternCContext())
12863       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
12864     return true;
12865   }
12866 
12867   // This might be the definition of a literal operator template.
12868   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12869 
12870   // This might be a specialization of a literal operator template.
12871   if (!TpDecl)
12872     TpDecl = FnDecl->getPrimaryTemplate();
12873 
12874   // template <char...> type operator "" name() and
12875   // template <class T, T...> type operator "" name() are the only valid
12876   // template signatures, and the only valid signatures with no parameters.
12877   if (TpDecl) {
12878     if (FnDecl->param_size() != 0) {
12879       Diag(FnDecl->getLocation(),
12880            diag::err_literal_operator_template_with_params);
12881       return true;
12882     }
12883 
12884     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12885       return true;
12886 
12887   } else if (FnDecl->param_size() == 1) {
12888     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12889 
12890     QualType ParamType = Param->getType().getUnqualifiedType();
12891 
12892     // Only unsigned long long int, long double, any character type, and const
12893     // char * are allowed as the only parameters.
12894     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12895         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12896         Context.hasSameType(ParamType, Context.CharTy) ||
12897         Context.hasSameType(ParamType, Context.WideCharTy) ||
12898         Context.hasSameType(ParamType, Context.Char16Ty) ||
12899         Context.hasSameType(ParamType, Context.Char32Ty)) {
12900     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12901       QualType InnerType = Ptr->getPointeeType();
12902 
12903       // Pointer parameter must be a const char *.
12904       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12905                                 Context.CharTy) &&
12906             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12907         Diag(Param->getSourceRange().getBegin(),
12908              diag::err_literal_operator_param)
12909             << ParamType << "'const char *'" << Param->getSourceRange();
12910         return true;
12911       }
12912 
12913     } else if (ParamType->isRealFloatingType()) {
12914       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12915           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12916       return true;
12917 
12918     } else if (ParamType->isIntegerType()) {
12919       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12920           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12921       return true;
12922 
12923     } else {
12924       Diag(Param->getSourceRange().getBegin(),
12925            diag::err_literal_operator_invalid_param)
12926           << ParamType << Param->getSourceRange();
12927       return true;
12928     }
12929 
12930   } else if (FnDecl->param_size() == 2) {
12931     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12932 
12933     // First, verify that the first parameter is correct.
12934 
12935     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12936 
12937     // Two parameter function must have a pointer to const as a
12938     // first parameter; let's strip those qualifiers.
12939     const PointerType *PT = FirstParamType->getAs<PointerType>();
12940 
12941     if (!PT) {
12942       Diag((*Param)->getSourceRange().getBegin(),
12943            diag::err_literal_operator_param)
12944           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12945       return true;
12946     }
12947 
12948     QualType PointeeType = PT->getPointeeType();
12949     // First parameter must be const
12950     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12951       Diag((*Param)->getSourceRange().getBegin(),
12952            diag::err_literal_operator_param)
12953           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12954       return true;
12955     }
12956 
12957     QualType InnerType = PointeeType.getUnqualifiedType();
12958     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12959     // are allowed as the first parameter to a two-parameter function
12960     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12961           Context.hasSameType(InnerType, Context.WideCharTy) ||
12962           Context.hasSameType(InnerType, Context.Char16Ty) ||
12963           Context.hasSameType(InnerType, Context.Char32Ty))) {
12964       Diag((*Param)->getSourceRange().getBegin(),
12965            diag::err_literal_operator_param)
12966           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12967       return true;
12968     }
12969 
12970     // Move on to the second and final parameter.
12971     ++Param;
12972 
12973     // The second parameter must be a std::size_t.
12974     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12975     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12976       Diag((*Param)->getSourceRange().getBegin(),
12977            diag::err_literal_operator_param)
12978           << SecondParamType << Context.getSizeType()
12979           << (*Param)->getSourceRange();
12980       return true;
12981     }
12982   } else {
12983     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12984     return true;
12985   }
12986 
12987   // Parameters are good.
12988 
12989   // A parameter-declaration-clause containing a default argument is not
12990   // equivalent to any of the permitted forms.
12991   for (auto Param : FnDecl->parameters()) {
12992     if (Param->hasDefaultArg()) {
12993       Diag(Param->getDefaultArgRange().getBegin(),
12994            diag::err_literal_operator_default_argument)
12995         << Param->getDefaultArgRange();
12996       break;
12997     }
12998   }
12999 
13000   StringRef LiteralName
13001     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13002   if (LiteralName[0] != '_') {
13003     // C++11 [usrlit.suffix]p1:
13004     //   Literal suffix identifiers that do not start with an underscore
13005     //   are reserved for future standardization.
13006     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13007       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13008   }
13009 
13010   return false;
13011 }
13012 
13013 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13014 /// linkage specification, including the language and (if present)
13015 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13016 /// language string literal. LBraceLoc, if valid, provides the location of
13017 /// the '{' brace. Otherwise, this linkage specification does not
13018 /// have any braces.
13019 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13020                                            Expr *LangStr,
13021                                            SourceLocation LBraceLoc) {
13022   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13023   if (!Lit->isAscii()) {
13024     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13025       << LangStr->getSourceRange();
13026     return nullptr;
13027   }
13028 
13029   StringRef Lang = Lit->getString();
13030   LinkageSpecDecl::LanguageIDs Language;
13031   if (Lang == "C")
13032     Language = LinkageSpecDecl::lang_c;
13033   else if (Lang == "C++")
13034     Language = LinkageSpecDecl::lang_cxx;
13035   else {
13036     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13037       << LangStr->getSourceRange();
13038     return nullptr;
13039   }
13040 
13041   // FIXME: Add all the various semantics of linkage specifications
13042 
13043   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13044                                                LangStr->getExprLoc(), Language,
13045                                                LBraceLoc.isValid());
13046   CurContext->addDecl(D);
13047   PushDeclContext(S, D);
13048   return D;
13049 }
13050 
13051 /// ActOnFinishLinkageSpecification - Complete the definition of
13052 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13053 /// valid, it's the position of the closing '}' brace in a linkage
13054 /// specification that uses braces.
13055 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13056                                             Decl *LinkageSpec,
13057                                             SourceLocation RBraceLoc) {
13058   if (RBraceLoc.isValid()) {
13059     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13060     LSDecl->setRBraceLoc(RBraceLoc);
13061   }
13062   PopDeclContext();
13063   return LinkageSpec;
13064 }
13065 
13066 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13067                                   AttributeList *AttrList,
13068                                   SourceLocation SemiLoc) {
13069   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13070   // Attribute declarations appertain to empty declaration so we handle
13071   // them here.
13072   if (AttrList)
13073     ProcessDeclAttributeList(S, ED, AttrList);
13074 
13075   CurContext->addDecl(ED);
13076   return ED;
13077 }
13078 
13079 /// \brief Perform semantic analysis for the variable declaration that
13080 /// occurs within a C++ catch clause, returning the newly-created
13081 /// variable.
13082 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13083                                          TypeSourceInfo *TInfo,
13084                                          SourceLocation StartLoc,
13085                                          SourceLocation Loc,
13086                                          IdentifierInfo *Name) {
13087   bool Invalid = false;
13088   QualType ExDeclType = TInfo->getType();
13089 
13090   // Arrays and functions decay.
13091   if (ExDeclType->isArrayType())
13092     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13093   else if (ExDeclType->isFunctionType())
13094     ExDeclType = Context.getPointerType(ExDeclType);
13095 
13096   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13097   // The exception-declaration shall not denote a pointer or reference to an
13098   // incomplete type, other than [cv] void*.
13099   // N2844 forbids rvalue references.
13100   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13101     Diag(Loc, diag::err_catch_rvalue_ref);
13102     Invalid = true;
13103   }
13104 
13105   if (ExDeclType->isVariablyModifiedType()) {
13106     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13107     Invalid = true;
13108   }
13109 
13110   QualType BaseType = ExDeclType;
13111   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13112   unsigned DK = diag::err_catch_incomplete;
13113   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13114     BaseType = Ptr->getPointeeType();
13115     Mode = 1;
13116     DK = diag::err_catch_incomplete_ptr;
13117   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13118     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13119     BaseType = Ref->getPointeeType();
13120     Mode = 2;
13121     DK = diag::err_catch_incomplete_ref;
13122   }
13123   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13124       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13125     Invalid = true;
13126 
13127   if (!Invalid && !ExDeclType->isDependentType() &&
13128       RequireNonAbstractType(Loc, ExDeclType,
13129                              diag::err_abstract_type_in_decl,
13130                              AbstractVariableType))
13131     Invalid = true;
13132 
13133   // Only the non-fragile NeXT runtime currently supports C++ catches
13134   // of ObjC types, and no runtime supports catching ObjC types by value.
13135   if (!Invalid && getLangOpts().ObjC1) {
13136     QualType T = ExDeclType;
13137     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13138       T = RT->getPointeeType();
13139 
13140     if (T->isObjCObjectType()) {
13141       Diag(Loc, diag::err_objc_object_catch);
13142       Invalid = true;
13143     } else if (T->isObjCObjectPointerType()) {
13144       // FIXME: should this be a test for macosx-fragile specifically?
13145       if (getLangOpts().ObjCRuntime.isFragile())
13146         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13147     }
13148   }
13149 
13150   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13151                                     ExDeclType, TInfo, SC_None);
13152   ExDecl->setExceptionVariable(true);
13153 
13154   // In ARC, infer 'retaining' for variables of retainable type.
13155   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13156     Invalid = true;
13157 
13158   if (!Invalid && !ExDeclType->isDependentType()) {
13159     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13160       // Insulate this from anything else we might currently be parsing.
13161       EnterExpressionEvaluationContext scope(
13162           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13163 
13164       // C++ [except.handle]p16:
13165       //   The object declared in an exception-declaration or, if the
13166       //   exception-declaration does not specify a name, a temporary (12.2) is
13167       //   copy-initialized (8.5) from the exception object. [...]
13168       //   The object is destroyed when the handler exits, after the destruction
13169       //   of any automatic objects initialized within the handler.
13170       //
13171       // We just pretend to initialize the object with itself, then make sure
13172       // it can be destroyed later.
13173       QualType initType = Context.getExceptionObjectType(ExDeclType);
13174 
13175       InitializedEntity entity =
13176         InitializedEntity::InitializeVariable(ExDecl);
13177       InitializationKind initKind =
13178         InitializationKind::CreateCopy(Loc, SourceLocation());
13179 
13180       Expr *opaqueValue =
13181         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13182       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13183       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13184       if (result.isInvalid())
13185         Invalid = true;
13186       else {
13187         // If the constructor used was non-trivial, set this as the
13188         // "initializer".
13189         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13190         if (!construct->getConstructor()->isTrivial()) {
13191           Expr *init = MaybeCreateExprWithCleanups(construct);
13192           ExDecl->setInit(init);
13193         }
13194 
13195         // And make sure it's destructable.
13196         FinalizeVarWithDestructor(ExDecl, recordType);
13197       }
13198     }
13199   }
13200 
13201   if (Invalid)
13202     ExDecl->setInvalidDecl();
13203 
13204   return ExDecl;
13205 }
13206 
13207 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13208 /// handler.
13209 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13210   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13211   bool Invalid = D.isInvalidType();
13212 
13213   // Check for unexpanded parameter packs.
13214   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13215                                       UPPC_ExceptionType)) {
13216     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13217                                              D.getIdentifierLoc());
13218     Invalid = true;
13219   }
13220 
13221   IdentifierInfo *II = D.getIdentifier();
13222   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13223                                              LookupOrdinaryName,
13224                                              ForRedeclaration)) {
13225     // The scope should be freshly made just for us. There is just no way
13226     // it contains any previous declaration, except for function parameters in
13227     // a function-try-block's catch statement.
13228     assert(!S->isDeclScope(PrevDecl));
13229     if (isDeclInScope(PrevDecl, CurContext, S)) {
13230       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13231         << D.getIdentifier();
13232       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13233       Invalid = true;
13234     } else if (PrevDecl->isTemplateParameter())
13235       // Maybe we will complain about the shadowed template parameter.
13236       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13237   }
13238 
13239   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13240     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13241       << D.getCXXScopeSpec().getRange();
13242     Invalid = true;
13243   }
13244 
13245   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13246                                               D.getLocStart(),
13247                                               D.getIdentifierLoc(),
13248                                               D.getIdentifier());
13249   if (Invalid)
13250     ExDecl->setInvalidDecl();
13251 
13252   // Add the exception declaration into this scope.
13253   if (II)
13254     PushOnScopeChains(ExDecl, S);
13255   else
13256     CurContext->addDecl(ExDecl);
13257 
13258   ProcessDeclAttributes(S, ExDecl, D);
13259   return ExDecl;
13260 }
13261 
13262 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13263                                          Expr *AssertExpr,
13264                                          Expr *AssertMessageExpr,
13265                                          SourceLocation RParenLoc) {
13266   StringLiteral *AssertMessage =
13267       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13268 
13269   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13270     return nullptr;
13271 
13272   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13273                                       AssertMessage, RParenLoc, false);
13274 }
13275 
13276 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13277                                          Expr *AssertExpr,
13278                                          StringLiteral *AssertMessage,
13279                                          SourceLocation RParenLoc,
13280                                          bool Failed) {
13281   assert(AssertExpr != nullptr && "Expected non-null condition");
13282   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13283       !Failed) {
13284     // In a static_assert-declaration, the constant-expression shall be a
13285     // constant expression that can be contextually converted to bool.
13286     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13287     if (Converted.isInvalid())
13288       Failed = true;
13289 
13290     llvm::APSInt Cond;
13291     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13292           diag::err_static_assert_expression_is_not_constant,
13293           /*AllowFold=*/false).isInvalid())
13294       Failed = true;
13295 
13296     if (!Failed && !Cond) {
13297       SmallString<256> MsgBuffer;
13298       llvm::raw_svector_ostream Msg(MsgBuffer);
13299       if (AssertMessage)
13300         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13301 
13302       Expr *InnerCond = nullptr;
13303       std::string InnerCondDescription;
13304       std::tie(InnerCond, InnerCondDescription) =
13305         findFailedBooleanCondition(Converted.get(),
13306                                    /*AllowTopLevelCond=*/false);
13307       if (InnerCond) {
13308         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13309           << InnerCondDescription << !AssertMessage
13310           << Msg.str() << InnerCond->getSourceRange();
13311       } else {
13312         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13313           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13314       }
13315       Failed = true;
13316     }
13317   }
13318 
13319   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13320                                                   /*DiscardedValue*/false,
13321                                                   /*IsConstexpr*/true);
13322   if (FullAssertExpr.isInvalid())
13323     Failed = true;
13324   else
13325     AssertExpr = FullAssertExpr.get();
13326 
13327   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13328                                         AssertExpr, AssertMessage, RParenLoc,
13329                                         Failed);
13330 
13331   CurContext->addDecl(Decl);
13332   return Decl;
13333 }
13334 
13335 /// \brief Perform semantic analysis of the given friend type declaration.
13336 ///
13337 /// \returns A friend declaration that.
13338 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13339                                       SourceLocation FriendLoc,
13340                                       TypeSourceInfo *TSInfo) {
13341   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13342 
13343   QualType T = TSInfo->getType();
13344   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13345 
13346   // C++03 [class.friend]p2:
13347   //   An elaborated-type-specifier shall be used in a friend declaration
13348   //   for a class.*
13349   //
13350   //   * The class-key of the elaborated-type-specifier is required.
13351   if (!CodeSynthesisContexts.empty()) {
13352     // Do not complain about the form of friend template types during any kind
13353     // of code synthesis. For template instantiation, we will have complained
13354     // when the template was defined.
13355   } else {
13356     if (!T->isElaboratedTypeSpecifier()) {
13357       // If we evaluated the type to a record type, suggest putting
13358       // a tag in front.
13359       if (const RecordType *RT = T->getAs<RecordType>()) {
13360         RecordDecl *RD = RT->getDecl();
13361 
13362         SmallString<16> InsertionText(" ");
13363         InsertionText += RD->getKindName();
13364 
13365         Diag(TypeRange.getBegin(),
13366              getLangOpts().CPlusPlus11 ?
13367                diag::warn_cxx98_compat_unelaborated_friend_type :
13368                diag::ext_unelaborated_friend_type)
13369           << (unsigned) RD->getTagKind()
13370           << T
13371           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13372                                         InsertionText);
13373       } else {
13374         Diag(FriendLoc,
13375              getLangOpts().CPlusPlus11 ?
13376                diag::warn_cxx98_compat_nonclass_type_friend :
13377                diag::ext_nonclass_type_friend)
13378           << T
13379           << TypeRange;
13380       }
13381     } else if (T->getAs<EnumType>()) {
13382       Diag(FriendLoc,
13383            getLangOpts().CPlusPlus11 ?
13384              diag::warn_cxx98_compat_enum_friend :
13385              diag::ext_enum_friend)
13386         << T
13387         << TypeRange;
13388     }
13389 
13390     // C++11 [class.friend]p3:
13391     //   A friend declaration that does not declare a function shall have one
13392     //   of the following forms:
13393     //     friend elaborated-type-specifier ;
13394     //     friend simple-type-specifier ;
13395     //     friend typename-specifier ;
13396     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13397       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13398   }
13399 
13400   //   If the type specifier in a friend declaration designates a (possibly
13401   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13402   //   the friend declaration is ignored.
13403   return FriendDecl::Create(Context, CurContext,
13404                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13405                             FriendLoc);
13406 }
13407 
13408 /// Handle a friend tag declaration where the scope specifier was
13409 /// templated.
13410 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13411                                     unsigned TagSpec, SourceLocation TagLoc,
13412                                     CXXScopeSpec &SS,
13413                                     IdentifierInfo *Name,
13414                                     SourceLocation NameLoc,
13415                                     AttributeList *Attr,
13416                                     MultiTemplateParamsArg TempParamLists) {
13417   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13418 
13419   bool IsMemberSpecialization = false;
13420   bool Invalid = false;
13421 
13422   if (TemplateParameterList *TemplateParams =
13423           MatchTemplateParametersToScopeSpecifier(
13424               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13425               IsMemberSpecialization, Invalid)) {
13426     if (TemplateParams->size() > 0) {
13427       // This is a declaration of a class template.
13428       if (Invalid)
13429         return nullptr;
13430 
13431       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13432                                 NameLoc, Attr, TemplateParams, AS_public,
13433                                 /*ModulePrivateLoc=*/SourceLocation(),
13434                                 FriendLoc, TempParamLists.size() - 1,
13435                                 TempParamLists.data()).get();
13436     } else {
13437       // The "template<>" header is extraneous.
13438       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13439         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13440       IsMemberSpecialization = true;
13441     }
13442   }
13443 
13444   if (Invalid) return nullptr;
13445 
13446   bool isAllExplicitSpecializations = true;
13447   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13448     if (TempParamLists[I]->size()) {
13449       isAllExplicitSpecializations = false;
13450       break;
13451     }
13452   }
13453 
13454   // FIXME: don't ignore attributes.
13455 
13456   // If it's explicit specializations all the way down, just forget
13457   // about the template header and build an appropriate non-templated
13458   // friend.  TODO: for source fidelity, remember the headers.
13459   if (isAllExplicitSpecializations) {
13460     if (SS.isEmpty()) {
13461       bool Owned = false;
13462       bool IsDependent = false;
13463       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13464                       Attr, AS_public,
13465                       /*ModulePrivateLoc=*/SourceLocation(),
13466                       MultiTemplateParamsArg(), Owned, IsDependent,
13467                       /*ScopedEnumKWLoc=*/SourceLocation(),
13468                       /*ScopedEnumUsesClassTag=*/false,
13469                       /*UnderlyingType=*/TypeResult(),
13470                       /*IsTypeSpecifier=*/false,
13471                       /*IsTemplateParamOrArg=*/false);
13472     }
13473 
13474     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13475     ElaboratedTypeKeyword Keyword
13476       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13477     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13478                                    *Name, NameLoc);
13479     if (T.isNull())
13480       return nullptr;
13481 
13482     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13483     if (isa<DependentNameType>(T)) {
13484       DependentNameTypeLoc TL =
13485           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13486       TL.setElaboratedKeywordLoc(TagLoc);
13487       TL.setQualifierLoc(QualifierLoc);
13488       TL.setNameLoc(NameLoc);
13489     } else {
13490       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13491       TL.setElaboratedKeywordLoc(TagLoc);
13492       TL.setQualifierLoc(QualifierLoc);
13493       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13494     }
13495 
13496     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13497                                             TSI, FriendLoc, TempParamLists);
13498     Friend->setAccess(AS_public);
13499     CurContext->addDecl(Friend);
13500     return Friend;
13501   }
13502 
13503   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13504 
13505 
13506 
13507   // Handle the case of a templated-scope friend class.  e.g.
13508   //   template <class T> class A<T>::B;
13509   // FIXME: we don't support these right now.
13510   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13511     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13512   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13513   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13514   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13515   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13516   TL.setElaboratedKeywordLoc(TagLoc);
13517   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13518   TL.setNameLoc(NameLoc);
13519 
13520   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13521                                           TSI, FriendLoc, TempParamLists);
13522   Friend->setAccess(AS_public);
13523   Friend->setUnsupportedFriend(true);
13524   CurContext->addDecl(Friend);
13525   return Friend;
13526 }
13527 
13528 
13529 /// Handle a friend type declaration.  This works in tandem with
13530 /// ActOnTag.
13531 ///
13532 /// Notes on friend class templates:
13533 ///
13534 /// We generally treat friend class declarations as if they were
13535 /// declaring a class.  So, for example, the elaborated type specifier
13536 /// in a friend declaration is required to obey the restrictions of a
13537 /// class-head (i.e. no typedefs in the scope chain), template
13538 /// parameters are required to match up with simple template-ids, &c.
13539 /// However, unlike when declaring a template specialization, it's
13540 /// okay to refer to a template specialization without an empty
13541 /// template parameter declaration, e.g.
13542 ///   friend class A<T>::B<unsigned>;
13543 /// We permit this as a special case; if there are any template
13544 /// parameters present at all, require proper matching, i.e.
13545 ///   template <> template \<class T> friend class A<int>::B;
13546 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13547                                 MultiTemplateParamsArg TempParams) {
13548   SourceLocation Loc = DS.getLocStart();
13549 
13550   assert(DS.isFriendSpecified());
13551   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13552 
13553   // Try to convert the decl specifier to a type.  This works for
13554   // friend templates because ActOnTag never produces a ClassTemplateDecl
13555   // for a TUK_Friend.
13556   Declarator TheDeclarator(DS, Declarator::MemberContext);
13557   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13558   QualType T = TSI->getType();
13559   if (TheDeclarator.isInvalidType())
13560     return nullptr;
13561 
13562   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13563     return nullptr;
13564 
13565   // This is definitely an error in C++98.  It's probably meant to
13566   // be forbidden in C++0x, too, but the specification is just
13567   // poorly written.
13568   //
13569   // The problem is with declarations like the following:
13570   //   template <T> friend A<T>::foo;
13571   // where deciding whether a class C is a friend or not now hinges
13572   // on whether there exists an instantiation of A that causes
13573   // 'foo' to equal C.  There are restrictions on class-heads
13574   // (which we declare (by fiat) elaborated friend declarations to
13575   // be) that makes this tractable.
13576   //
13577   // FIXME: handle "template <> friend class A<T>;", which
13578   // is possibly well-formed?  Who even knows?
13579   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13580     Diag(Loc, diag::err_tagless_friend_type_template)
13581       << DS.getSourceRange();
13582     return nullptr;
13583   }
13584 
13585   // C++98 [class.friend]p1: A friend of a class is a function
13586   //   or class that is not a member of the class . . .
13587   // This is fixed in DR77, which just barely didn't make the C++03
13588   // deadline.  It's also a very silly restriction that seriously
13589   // affects inner classes and which nobody else seems to implement;
13590   // thus we never diagnose it, not even in -pedantic.
13591   //
13592   // But note that we could warn about it: it's always useless to
13593   // friend one of your own members (it's not, however, worthless to
13594   // friend a member of an arbitrary specialization of your template).
13595 
13596   Decl *D;
13597   if (!TempParams.empty())
13598     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13599                                    TempParams,
13600                                    TSI,
13601                                    DS.getFriendSpecLoc());
13602   else
13603     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13604 
13605   if (!D)
13606     return nullptr;
13607 
13608   D->setAccess(AS_public);
13609   CurContext->addDecl(D);
13610 
13611   return D;
13612 }
13613 
13614 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13615                                         MultiTemplateParamsArg TemplateParams) {
13616   const DeclSpec &DS = D.getDeclSpec();
13617 
13618   assert(DS.isFriendSpecified());
13619   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13620 
13621   SourceLocation Loc = D.getIdentifierLoc();
13622   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13623 
13624   // C++ [class.friend]p1
13625   //   A friend of a class is a function or class....
13626   // Note that this sees through typedefs, which is intended.
13627   // It *doesn't* see through dependent types, which is correct
13628   // according to [temp.arg.type]p3:
13629   //   If a declaration acquires a function type through a
13630   //   type dependent on a template-parameter and this causes
13631   //   a declaration that does not use the syntactic form of a
13632   //   function declarator to have a function type, the program
13633   //   is ill-formed.
13634   if (!TInfo->getType()->isFunctionType()) {
13635     Diag(Loc, diag::err_unexpected_friend);
13636 
13637     // It might be worthwhile to try to recover by creating an
13638     // appropriate declaration.
13639     return nullptr;
13640   }
13641 
13642   // C++ [namespace.memdef]p3
13643   //  - If a friend declaration in a non-local class first declares a
13644   //    class or function, the friend class or function is a member
13645   //    of the innermost enclosing namespace.
13646   //  - The name of the friend is not found by simple name lookup
13647   //    until a matching declaration is provided in that namespace
13648   //    scope (either before or after the class declaration granting
13649   //    friendship).
13650   //  - If a friend function is called, its name may be found by the
13651   //    name lookup that considers functions from namespaces and
13652   //    classes associated with the types of the function arguments.
13653   //  - When looking for a prior declaration of a class or a function
13654   //    declared as a friend, scopes outside the innermost enclosing
13655   //    namespace scope are not considered.
13656 
13657   CXXScopeSpec &SS = D.getCXXScopeSpec();
13658   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13659   DeclarationName Name = NameInfo.getName();
13660   assert(Name);
13661 
13662   // Check for unexpanded parameter packs.
13663   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13664       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13665       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13666     return nullptr;
13667 
13668   // The context we found the declaration in, or in which we should
13669   // create the declaration.
13670   DeclContext *DC;
13671   Scope *DCScope = S;
13672   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13673                         ForRedeclaration);
13674 
13675   // There are five cases here.
13676   //   - There's no scope specifier and we're in a local class. Only look
13677   //     for functions declared in the immediately-enclosing block scope.
13678   // We recover from invalid scope qualifiers as if they just weren't there.
13679   FunctionDecl *FunctionContainingLocalClass = nullptr;
13680   if ((SS.isInvalid() || !SS.isSet()) &&
13681       (FunctionContainingLocalClass =
13682            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13683     // C++11 [class.friend]p11:
13684     //   If a friend declaration appears in a local class and the name
13685     //   specified is an unqualified name, a prior declaration is
13686     //   looked up without considering scopes that are outside the
13687     //   innermost enclosing non-class scope. For a friend function
13688     //   declaration, if there is no prior declaration, the program is
13689     //   ill-formed.
13690 
13691     // Find the innermost enclosing non-class scope. This is the block
13692     // scope containing the local class definition (or for a nested class,
13693     // the outer local class).
13694     DCScope = S->getFnParent();
13695 
13696     // Look up the function name in the scope.
13697     Previous.clear(LookupLocalFriendName);
13698     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13699 
13700     if (!Previous.empty()) {
13701       // All possible previous declarations must have the same context:
13702       // either they were declared at block scope or they are members of
13703       // one of the enclosing local classes.
13704       DC = Previous.getRepresentativeDecl()->getDeclContext();
13705     } else {
13706       // This is ill-formed, but provide the context that we would have
13707       // declared the function in, if we were permitted to, for error recovery.
13708       DC = FunctionContainingLocalClass;
13709     }
13710     adjustContextForLocalExternDecl(DC);
13711 
13712     // C++ [class.friend]p6:
13713     //   A function can be defined in a friend declaration of a class if and
13714     //   only if the class is a non-local class (9.8), the function name is
13715     //   unqualified, and the function has namespace scope.
13716     if (D.isFunctionDefinition()) {
13717       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13718     }
13719 
13720   //   - There's no scope specifier, in which case we just go to the
13721   //     appropriate scope and look for a function or function template
13722   //     there as appropriate.
13723   } else if (SS.isInvalid() || !SS.isSet()) {
13724     // C++11 [namespace.memdef]p3:
13725     //   If the name in a friend declaration is neither qualified nor
13726     //   a template-id and the declaration is a function or an
13727     //   elaborated-type-specifier, the lookup to determine whether
13728     //   the entity has been previously declared shall not consider
13729     //   any scopes outside the innermost enclosing namespace.
13730     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13731 
13732     // Find the appropriate context according to the above.
13733     DC = CurContext;
13734 
13735     // Skip class contexts.  If someone can cite chapter and verse
13736     // for this behavior, that would be nice --- it's what GCC and
13737     // EDG do, and it seems like a reasonable intent, but the spec
13738     // really only says that checks for unqualified existing
13739     // declarations should stop at the nearest enclosing namespace,
13740     // not that they should only consider the nearest enclosing
13741     // namespace.
13742     while (DC->isRecord())
13743       DC = DC->getParent();
13744 
13745     DeclContext *LookupDC = DC;
13746     while (LookupDC->isTransparentContext())
13747       LookupDC = LookupDC->getParent();
13748 
13749     while (true) {
13750       LookupQualifiedName(Previous, LookupDC);
13751 
13752       if (!Previous.empty()) {
13753         DC = LookupDC;
13754         break;
13755       }
13756 
13757       if (isTemplateId) {
13758         if (isa<TranslationUnitDecl>(LookupDC)) break;
13759       } else {
13760         if (LookupDC->isFileContext()) break;
13761       }
13762       LookupDC = LookupDC->getParent();
13763     }
13764 
13765     DCScope = getScopeForDeclContext(S, DC);
13766 
13767   //   - There's a non-dependent scope specifier, in which case we
13768   //     compute it and do a previous lookup there for a function
13769   //     or function template.
13770   } else if (!SS.getScopeRep()->isDependent()) {
13771     DC = computeDeclContext(SS);
13772     if (!DC) return nullptr;
13773 
13774     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13775 
13776     LookupQualifiedName(Previous, DC);
13777 
13778     // Ignore things found implicitly in the wrong scope.
13779     // TODO: better diagnostics for this case.  Suggesting the right
13780     // qualified scope would be nice...
13781     LookupResult::Filter F = Previous.makeFilter();
13782     while (F.hasNext()) {
13783       NamedDecl *D = F.next();
13784       if (!DC->InEnclosingNamespaceSetOf(
13785               D->getDeclContext()->getRedeclContext()))
13786         F.erase();
13787     }
13788     F.done();
13789 
13790     if (Previous.empty()) {
13791       D.setInvalidType();
13792       Diag(Loc, diag::err_qualified_friend_not_found)
13793           << Name << TInfo->getType();
13794       return nullptr;
13795     }
13796 
13797     // C++ [class.friend]p1: A friend of a class is a function or
13798     //   class that is not a member of the class . . .
13799     if (DC->Equals(CurContext))
13800       Diag(DS.getFriendSpecLoc(),
13801            getLangOpts().CPlusPlus11 ?
13802              diag::warn_cxx98_compat_friend_is_member :
13803              diag::err_friend_is_member);
13804 
13805     if (D.isFunctionDefinition()) {
13806       // C++ [class.friend]p6:
13807       //   A function can be defined in a friend declaration of a class if and
13808       //   only if the class is a non-local class (9.8), the function name is
13809       //   unqualified, and the function has namespace scope.
13810       SemaDiagnosticBuilder DB
13811         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13812 
13813       DB << SS.getScopeRep();
13814       if (DC->isFileContext())
13815         DB << FixItHint::CreateRemoval(SS.getRange());
13816       SS.clear();
13817     }
13818 
13819   //   - There's a scope specifier that does not match any template
13820   //     parameter lists, in which case we use some arbitrary context,
13821   //     create a method or method template, and wait for instantiation.
13822   //   - There's a scope specifier that does match some template
13823   //     parameter lists, which we don't handle right now.
13824   } else {
13825     if (D.isFunctionDefinition()) {
13826       // C++ [class.friend]p6:
13827       //   A function can be defined in a friend declaration of a class if and
13828       //   only if the class is a non-local class (9.8), the function name is
13829       //   unqualified, and the function has namespace scope.
13830       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13831         << SS.getScopeRep();
13832     }
13833 
13834     DC = CurContext;
13835     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13836   }
13837 
13838   if (!DC->isRecord()) {
13839     int DiagArg = -1;
13840     switch (D.getName().getKind()) {
13841     case UnqualifiedId::IK_ConstructorTemplateId:
13842     case UnqualifiedId::IK_ConstructorName:
13843       DiagArg = 0;
13844       break;
13845     case UnqualifiedId::IK_DestructorName:
13846       DiagArg = 1;
13847       break;
13848     case UnqualifiedId::IK_ConversionFunctionId:
13849       DiagArg = 2;
13850       break;
13851     case UnqualifiedId::IK_DeductionGuideName:
13852       DiagArg = 3;
13853       break;
13854     case UnqualifiedId::IK_Identifier:
13855     case UnqualifiedId::IK_ImplicitSelfParam:
13856     case UnqualifiedId::IK_LiteralOperatorId:
13857     case UnqualifiedId::IK_OperatorFunctionId:
13858     case UnqualifiedId::IK_TemplateId:
13859       break;
13860     }
13861     // This implies that it has to be an operator or function.
13862     if (DiagArg >= 0) {
13863       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13864       return nullptr;
13865     }
13866   }
13867 
13868   // FIXME: This is an egregious hack to cope with cases where the scope stack
13869   // does not contain the declaration context, i.e., in an out-of-line
13870   // definition of a class.
13871   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13872   if (!DCScope) {
13873     FakeDCScope.setEntity(DC);
13874     DCScope = &FakeDCScope;
13875   }
13876 
13877   bool AddToScope = true;
13878   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13879                                           TemplateParams, AddToScope);
13880   if (!ND) return nullptr;
13881 
13882   assert(ND->getLexicalDeclContext() == CurContext);
13883 
13884   // If we performed typo correction, we might have added a scope specifier
13885   // and changed the decl context.
13886   DC = ND->getDeclContext();
13887 
13888   // Add the function declaration to the appropriate lookup tables,
13889   // adjusting the redeclarations list as necessary.  We don't
13890   // want to do this yet if the friending class is dependent.
13891   //
13892   // Also update the scope-based lookup if the target context's
13893   // lookup context is in lexical scope.
13894   if (!CurContext->isDependentContext()) {
13895     DC = DC->getRedeclContext();
13896     DC->makeDeclVisibleInContext(ND);
13897     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13898       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13899   }
13900 
13901   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13902                                        D.getIdentifierLoc(), ND,
13903                                        DS.getFriendSpecLoc());
13904   FrD->setAccess(AS_public);
13905   CurContext->addDecl(FrD);
13906 
13907   if (ND->isInvalidDecl()) {
13908     FrD->setInvalidDecl();
13909   } else {
13910     if (DC->isRecord()) CheckFriendAccess(ND);
13911 
13912     FunctionDecl *FD;
13913     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13914       FD = FTD->getTemplatedDecl();
13915     else
13916       FD = cast<FunctionDecl>(ND);
13917 
13918     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13919     // default argument expression, that declaration shall be a definition
13920     // and shall be the only declaration of the function or function
13921     // template in the translation unit.
13922     if (functionDeclHasDefaultArgument(FD)) {
13923       // We can't look at FD->getPreviousDecl() because it may not have been set
13924       // if we're in a dependent context. If the function is known to be a
13925       // redeclaration, we will have narrowed Previous down to the right decl.
13926       if (D.isRedeclaration()) {
13927         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13928         Diag(Previous.getRepresentativeDecl()->getLocation(),
13929              diag::note_previous_declaration);
13930       } else if (!D.isFunctionDefinition())
13931         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13932     }
13933 
13934     // Mark templated-scope function declarations as unsupported.
13935     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13936       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13937         << SS.getScopeRep() << SS.getRange()
13938         << cast<CXXRecordDecl>(CurContext);
13939       FrD->setUnsupportedFriend(true);
13940     }
13941   }
13942 
13943   return ND;
13944 }
13945 
13946 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13947   AdjustDeclIfTemplate(Dcl);
13948 
13949   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13950   if (!Fn) {
13951     Diag(DelLoc, diag::err_deleted_non_function);
13952     return;
13953   }
13954 
13955   // Deleted function does not have a body.
13956   Fn->setWillHaveBody(false);
13957 
13958   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13959     // Don't consider the implicit declaration we generate for explicit
13960     // specializations. FIXME: Do not generate these implicit declarations.
13961     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13962          Prev->getPreviousDecl()) &&
13963         !Prev->isDefined()) {
13964       Diag(DelLoc, diag::err_deleted_decl_not_first);
13965       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13966            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13967                               : diag::note_previous_declaration);
13968     }
13969     // If the declaration wasn't the first, we delete the function anyway for
13970     // recovery.
13971     Fn = Fn->getCanonicalDecl();
13972   }
13973 
13974   // dllimport/dllexport cannot be deleted.
13975   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13976     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13977     Fn->setInvalidDecl();
13978   }
13979 
13980   if (Fn->isDeleted())
13981     return;
13982 
13983   // See if we're deleting a function which is already known to override a
13984   // non-deleted virtual function.
13985   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13986     bool IssuedDiagnostic = false;
13987     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13988                                         E = MD->end_overridden_methods();
13989          I != E; ++I) {
13990       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13991         if (!IssuedDiagnostic) {
13992           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13993           IssuedDiagnostic = true;
13994         }
13995         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13996       }
13997     }
13998     // If this function was implicitly deleted because it was defaulted,
13999     // explain why it was deleted.
14000     if (IssuedDiagnostic && MD->isDefaulted())
14001       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14002                                 /*Diagnose*/true);
14003   }
14004 
14005   // C++11 [basic.start.main]p3:
14006   //   A program that defines main as deleted [...] is ill-formed.
14007   if (Fn->isMain())
14008     Diag(DelLoc, diag::err_deleted_main);
14009 
14010   // C++11 [dcl.fct.def.delete]p4:
14011   //  A deleted function is implicitly inline.
14012   Fn->setImplicitlyInline();
14013   Fn->setDeletedAsWritten();
14014 }
14015 
14016 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14017   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14018 
14019   if (MD) {
14020     if (MD->getParent()->isDependentType()) {
14021       MD->setDefaulted();
14022       MD->setExplicitlyDefaulted();
14023       return;
14024     }
14025 
14026     CXXSpecialMember Member = getSpecialMember(MD);
14027     if (Member == CXXInvalid) {
14028       if (!MD->isInvalidDecl())
14029         Diag(DefaultLoc, diag::err_default_special_members);
14030       return;
14031     }
14032 
14033     MD->setDefaulted();
14034     MD->setExplicitlyDefaulted();
14035 
14036     // Unset that we will have a body for this function. We might not,
14037     // if it turns out to be trivial, and we don't need this marking now
14038     // that we've marked it as defaulted.
14039     MD->setWillHaveBody(false);
14040 
14041     // If this definition appears within the record, do the checking when
14042     // the record is complete.
14043     const FunctionDecl *Primary = MD;
14044     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14045       // Ask the template instantiation pattern that actually had the
14046       // '= default' on it.
14047       Primary = Pattern;
14048 
14049     // If the method was defaulted on its first declaration, we will have
14050     // already performed the checking in CheckCompletedCXXClass. Such a
14051     // declaration doesn't trigger an implicit definition.
14052     if (Primary->getCanonicalDecl()->isDefaulted())
14053       return;
14054 
14055     CheckExplicitlyDefaultedSpecialMember(MD);
14056 
14057     if (!MD->isInvalidDecl())
14058       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14059   } else {
14060     Diag(DefaultLoc, diag::err_default_special_members);
14061   }
14062 }
14063 
14064 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14065   for (Stmt *SubStmt : S->children()) {
14066     if (!SubStmt)
14067       continue;
14068     if (isa<ReturnStmt>(SubStmt))
14069       Self.Diag(SubStmt->getLocStart(),
14070            diag::err_return_in_constructor_handler);
14071     if (!isa<Expr>(SubStmt))
14072       SearchForReturnInStmt(Self, SubStmt);
14073   }
14074 }
14075 
14076 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14077   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14078     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14079     SearchForReturnInStmt(*this, Handler);
14080   }
14081 }
14082 
14083 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14084                                              const CXXMethodDecl *Old) {
14085   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14086   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14087 
14088   if (OldFT->hasExtParameterInfos()) {
14089     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14090       // A parameter of the overriding method should be annotated with noescape
14091       // if the corresponding parameter of the overridden method is annotated.
14092       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14093           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14094         Diag(New->getParamDecl(I)->getLocation(),
14095              diag::warn_overriding_method_missing_noescape);
14096         Diag(Old->getParamDecl(I)->getLocation(),
14097              diag::note_overridden_marked_noescape);
14098       }
14099   }
14100 
14101   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14102 
14103   // If the calling conventions match, everything is fine
14104   if (NewCC == OldCC)
14105     return false;
14106 
14107   // If the calling conventions mismatch because the new function is static,
14108   // suppress the calling convention mismatch error; the error about static
14109   // function override (err_static_overrides_virtual from
14110   // Sema::CheckFunctionDeclaration) is more clear.
14111   if (New->getStorageClass() == SC_Static)
14112     return false;
14113 
14114   Diag(New->getLocation(),
14115        diag::err_conflicting_overriding_cc_attributes)
14116     << New->getDeclName() << New->getType() << Old->getType();
14117   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14118   return true;
14119 }
14120 
14121 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14122                                              const CXXMethodDecl *Old) {
14123   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14124   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14125 
14126   if (Context.hasSameType(NewTy, OldTy) ||
14127       NewTy->isDependentType() || OldTy->isDependentType())
14128     return false;
14129 
14130   // Check if the return types are covariant
14131   QualType NewClassTy, OldClassTy;
14132 
14133   /// Both types must be pointers or references to classes.
14134   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14135     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14136       NewClassTy = NewPT->getPointeeType();
14137       OldClassTy = OldPT->getPointeeType();
14138     }
14139   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14140     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14141       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14142         NewClassTy = NewRT->getPointeeType();
14143         OldClassTy = OldRT->getPointeeType();
14144       }
14145     }
14146   }
14147 
14148   // The return types aren't either both pointers or references to a class type.
14149   if (NewClassTy.isNull()) {
14150     Diag(New->getLocation(),
14151          diag::err_different_return_type_for_overriding_virtual_function)
14152         << New->getDeclName() << NewTy << OldTy
14153         << New->getReturnTypeSourceRange();
14154     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14155         << Old->getReturnTypeSourceRange();
14156 
14157     return true;
14158   }
14159 
14160   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14161     // C++14 [class.virtual]p8:
14162     //   If the class type in the covariant return type of D::f differs from
14163     //   that of B::f, the class type in the return type of D::f shall be
14164     //   complete at the point of declaration of D::f or shall be the class
14165     //   type D.
14166     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14167       if (!RT->isBeingDefined() &&
14168           RequireCompleteType(New->getLocation(), NewClassTy,
14169                               diag::err_covariant_return_incomplete,
14170                               New->getDeclName()))
14171         return true;
14172     }
14173 
14174     // Check if the new class derives from the old class.
14175     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14176       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14177           << New->getDeclName() << NewTy << OldTy
14178           << New->getReturnTypeSourceRange();
14179       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14180           << Old->getReturnTypeSourceRange();
14181       return true;
14182     }
14183 
14184     // Check if we the conversion from derived to base is valid.
14185     if (CheckDerivedToBaseConversion(
14186             NewClassTy, OldClassTy,
14187             diag::err_covariant_return_inaccessible_base,
14188             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14189             New->getLocation(), New->getReturnTypeSourceRange(),
14190             New->getDeclName(), nullptr)) {
14191       // FIXME: this note won't trigger for delayed access control
14192       // diagnostics, and it's impossible to get an undelayed error
14193       // here from access control during the original parse because
14194       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14195       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14196           << Old->getReturnTypeSourceRange();
14197       return true;
14198     }
14199   }
14200 
14201   // The qualifiers of the return types must be the same.
14202   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14203     Diag(New->getLocation(),
14204          diag::err_covariant_return_type_different_qualifications)
14205         << New->getDeclName() << NewTy << OldTy
14206         << New->getReturnTypeSourceRange();
14207     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14208         << Old->getReturnTypeSourceRange();
14209     return true;
14210   }
14211 
14212 
14213   // The new class type must have the same or less qualifiers as the old type.
14214   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14215     Diag(New->getLocation(),
14216          diag::err_covariant_return_type_class_type_more_qualified)
14217         << New->getDeclName() << NewTy << OldTy
14218         << New->getReturnTypeSourceRange();
14219     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14220         << Old->getReturnTypeSourceRange();
14221     return true;
14222   }
14223 
14224   return false;
14225 }
14226 
14227 /// \brief Mark the given method pure.
14228 ///
14229 /// \param Method the method to be marked pure.
14230 ///
14231 /// \param InitRange the source range that covers the "0" initializer.
14232 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14233   SourceLocation EndLoc = InitRange.getEnd();
14234   if (EndLoc.isValid())
14235     Method->setRangeEnd(EndLoc);
14236 
14237   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14238     Method->setPure();
14239     return false;
14240   }
14241 
14242   if (!Method->isInvalidDecl())
14243     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14244       << Method->getDeclName() << InitRange;
14245   return true;
14246 }
14247 
14248 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14249   if (D->getFriendObjectKind())
14250     Diag(D->getLocation(), diag::err_pure_friend);
14251   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14252     CheckPureMethod(M, ZeroLoc);
14253   else
14254     Diag(D->getLocation(), diag::err_illegal_initializer);
14255 }
14256 
14257 /// \brief Determine whether the given declaration is a global variable or
14258 /// static data member.
14259 static bool isNonlocalVariable(const Decl *D) {
14260   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14261     return Var->hasGlobalStorage();
14262 
14263   return false;
14264 }
14265 
14266 /// Invoked when we are about to parse an initializer for the declaration
14267 /// 'Dcl'.
14268 ///
14269 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14270 /// static data member of class X, names should be looked up in the scope of
14271 /// class X. If the declaration had a scope specifier, a scope will have
14272 /// been created and passed in for this purpose. Otherwise, S will be null.
14273 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14274   // If there is no declaration, there was an error parsing it.
14275   if (!D || D->isInvalidDecl())
14276     return;
14277 
14278   // We will always have a nested name specifier here, but this declaration
14279   // might not be out of line if the specifier names the current namespace:
14280   //   extern int n;
14281   //   int ::n = 0;
14282   if (S && D->isOutOfLine())
14283     EnterDeclaratorContext(S, D->getDeclContext());
14284 
14285   // If we are parsing the initializer for a static data member, push a
14286   // new expression evaluation context that is associated with this static
14287   // data member.
14288   if (isNonlocalVariable(D))
14289     PushExpressionEvaluationContext(
14290         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14291 }
14292 
14293 /// Invoked after we are finished parsing an initializer for the declaration D.
14294 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14295   // If there is no declaration, there was an error parsing it.
14296   if (!D || D->isInvalidDecl())
14297     return;
14298 
14299   if (isNonlocalVariable(D))
14300     PopExpressionEvaluationContext();
14301 
14302   if (S && D->isOutOfLine())
14303     ExitDeclaratorContext(S);
14304 }
14305 
14306 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14307 /// C++ if/switch/while/for statement.
14308 /// e.g: "if (int x = f()) {...}"
14309 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14310   // C++ 6.4p2:
14311   // The declarator shall not specify a function or an array.
14312   // The type-specifier-seq shall not contain typedef and shall not declare a
14313   // new class or enumeration.
14314   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14315          "Parser allowed 'typedef' as storage class of condition decl.");
14316 
14317   Decl *Dcl = ActOnDeclarator(S, D);
14318   if (!Dcl)
14319     return true;
14320 
14321   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14322     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14323       << D.getSourceRange();
14324     return true;
14325   }
14326 
14327   return Dcl;
14328 }
14329 
14330 void Sema::LoadExternalVTableUses() {
14331   if (!ExternalSource)
14332     return;
14333 
14334   SmallVector<ExternalVTableUse, 4> VTables;
14335   ExternalSource->ReadUsedVTables(VTables);
14336   SmallVector<VTableUse, 4> NewUses;
14337   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14338     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14339       = VTablesUsed.find(VTables[I].Record);
14340     // Even if a definition wasn't required before, it may be required now.
14341     if (Pos != VTablesUsed.end()) {
14342       if (!Pos->second && VTables[I].DefinitionRequired)
14343         Pos->second = true;
14344       continue;
14345     }
14346 
14347     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14348     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14349   }
14350 
14351   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14352 }
14353 
14354 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14355                           bool DefinitionRequired) {
14356   // Ignore any vtable uses in unevaluated operands or for classes that do
14357   // not have a vtable.
14358   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14359       CurContext->isDependentContext() || isUnevaluatedContext())
14360     return;
14361 
14362   // Try to insert this class into the map.
14363   LoadExternalVTableUses();
14364   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14365   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14366     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14367   if (!Pos.second) {
14368     // If we already had an entry, check to see if we are promoting this vtable
14369     // to require a definition. If so, we need to reappend to the VTableUses
14370     // list, since we may have already processed the first entry.
14371     if (DefinitionRequired && !Pos.first->second) {
14372       Pos.first->second = true;
14373     } else {
14374       // Otherwise, we can early exit.
14375       return;
14376     }
14377   } else {
14378     // The Microsoft ABI requires that we perform the destructor body
14379     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14380     // the deleting destructor is emitted with the vtable, not with the
14381     // destructor definition as in the Itanium ABI.
14382     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14383       CXXDestructorDecl *DD = Class->getDestructor();
14384       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14385         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14386           // If this is an out-of-line declaration, marking it referenced will
14387           // not do anything. Manually call CheckDestructor to look up operator
14388           // delete().
14389           ContextRAII SavedContext(*this, DD);
14390           CheckDestructor(DD);
14391         } else {
14392           MarkFunctionReferenced(Loc, Class->getDestructor());
14393         }
14394       }
14395     }
14396   }
14397 
14398   // Local classes need to have their virtual members marked
14399   // immediately. For all other classes, we mark their virtual members
14400   // at the end of the translation unit.
14401   if (Class->isLocalClass())
14402     MarkVirtualMembersReferenced(Loc, Class);
14403   else
14404     VTableUses.push_back(std::make_pair(Class, Loc));
14405 }
14406 
14407 bool Sema::DefineUsedVTables() {
14408   LoadExternalVTableUses();
14409   if (VTableUses.empty())
14410     return false;
14411 
14412   // Note: The VTableUses vector could grow as a result of marking
14413   // the members of a class as "used", so we check the size each
14414   // time through the loop and prefer indices (which are stable) to
14415   // iterators (which are not).
14416   bool DefinedAnything = false;
14417   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14418     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14419     if (!Class)
14420       continue;
14421     TemplateSpecializationKind ClassTSK =
14422         Class->getTemplateSpecializationKind();
14423 
14424     SourceLocation Loc = VTableUses[I].second;
14425 
14426     bool DefineVTable = true;
14427 
14428     // If this class has a key function, but that key function is
14429     // defined in another translation unit, we don't need to emit the
14430     // vtable even though we're using it.
14431     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14432     if (KeyFunction && !KeyFunction->hasBody()) {
14433       // The key function is in another translation unit.
14434       DefineVTable = false;
14435       TemplateSpecializationKind TSK =
14436           KeyFunction->getTemplateSpecializationKind();
14437       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14438              TSK != TSK_ImplicitInstantiation &&
14439              "Instantiations don't have key functions");
14440       (void)TSK;
14441     } else if (!KeyFunction) {
14442       // If we have a class with no key function that is the subject
14443       // of an explicit instantiation declaration, suppress the
14444       // vtable; it will live with the explicit instantiation
14445       // definition.
14446       bool IsExplicitInstantiationDeclaration =
14447           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14448       for (auto R : Class->redecls()) {
14449         TemplateSpecializationKind TSK
14450           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14451         if (TSK == TSK_ExplicitInstantiationDeclaration)
14452           IsExplicitInstantiationDeclaration = true;
14453         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14454           IsExplicitInstantiationDeclaration = false;
14455           break;
14456         }
14457       }
14458 
14459       if (IsExplicitInstantiationDeclaration)
14460         DefineVTable = false;
14461     }
14462 
14463     // The exception specifications for all virtual members may be needed even
14464     // if we are not providing an authoritative form of the vtable in this TU.
14465     // We may choose to emit it available_externally anyway.
14466     if (!DefineVTable) {
14467       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14468       continue;
14469     }
14470 
14471     // Mark all of the virtual members of this class as referenced, so
14472     // that we can build a vtable. Then, tell the AST consumer that a
14473     // vtable for this class is required.
14474     DefinedAnything = true;
14475     MarkVirtualMembersReferenced(Loc, Class);
14476     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14477     if (VTablesUsed[Canonical])
14478       Consumer.HandleVTable(Class);
14479 
14480     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14481     // no key function or the key function is inlined. Don't warn in C++ ABIs
14482     // that lack key functions, since the user won't be able to make one.
14483     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14484         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14485       const FunctionDecl *KeyFunctionDef = nullptr;
14486       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14487                            KeyFunctionDef->isInlined())) {
14488         Diag(Class->getLocation(),
14489              ClassTSK == TSK_ExplicitInstantiationDefinition
14490                  ? diag::warn_weak_template_vtable
14491                  : diag::warn_weak_vtable)
14492             << Class;
14493       }
14494     }
14495   }
14496   VTableUses.clear();
14497 
14498   return DefinedAnything;
14499 }
14500 
14501 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14502                                                  const CXXRecordDecl *RD) {
14503   for (const auto *I : RD->methods())
14504     if (I->isVirtual() && !I->isPure())
14505       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14506 }
14507 
14508 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14509                                         const CXXRecordDecl *RD) {
14510   // Mark all functions which will appear in RD's vtable as used.
14511   CXXFinalOverriderMap FinalOverriders;
14512   RD->getFinalOverriders(FinalOverriders);
14513   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14514                                             E = FinalOverriders.end();
14515        I != E; ++I) {
14516     for (OverridingMethods::const_iterator OI = I->second.begin(),
14517                                            OE = I->second.end();
14518          OI != OE; ++OI) {
14519       assert(OI->second.size() > 0 && "no final overrider");
14520       CXXMethodDecl *Overrider = OI->second.front().Method;
14521 
14522       // C++ [basic.def.odr]p2:
14523       //   [...] A virtual member function is used if it is not pure. [...]
14524       if (!Overrider->isPure())
14525         MarkFunctionReferenced(Loc, Overrider);
14526     }
14527   }
14528 
14529   // Only classes that have virtual bases need a VTT.
14530   if (RD->getNumVBases() == 0)
14531     return;
14532 
14533   for (const auto &I : RD->bases()) {
14534     const CXXRecordDecl *Base =
14535         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14536     if (Base->getNumVBases() == 0)
14537       continue;
14538     MarkVirtualMembersReferenced(Loc, Base);
14539   }
14540 }
14541 
14542 /// SetIvarInitializers - This routine builds initialization ASTs for the
14543 /// Objective-C implementation whose ivars need be initialized.
14544 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14545   if (!getLangOpts().CPlusPlus)
14546     return;
14547   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14548     SmallVector<ObjCIvarDecl*, 8> ivars;
14549     CollectIvarsToConstructOrDestruct(OID, ivars);
14550     if (ivars.empty())
14551       return;
14552     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14553     for (unsigned i = 0; i < ivars.size(); i++) {
14554       FieldDecl *Field = ivars[i];
14555       if (Field->isInvalidDecl())
14556         continue;
14557 
14558       CXXCtorInitializer *Member;
14559       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14560       InitializationKind InitKind =
14561         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14562 
14563       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14564       ExprResult MemberInit =
14565         InitSeq.Perform(*this, InitEntity, InitKind, None);
14566       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14567       // Note, MemberInit could actually come back empty if no initialization
14568       // is required (e.g., because it would call a trivial default constructor)
14569       if (!MemberInit.get() || MemberInit.isInvalid())
14570         continue;
14571 
14572       Member =
14573         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14574                                          SourceLocation(),
14575                                          MemberInit.getAs<Expr>(),
14576                                          SourceLocation());
14577       AllToInit.push_back(Member);
14578 
14579       // Be sure that the destructor is accessible and is marked as referenced.
14580       if (const RecordType *RecordTy =
14581               Context.getBaseElementType(Field->getType())
14582                   ->getAs<RecordType>()) {
14583         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14584         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14585           MarkFunctionReferenced(Field->getLocation(), Destructor);
14586           CheckDestructorAccess(Field->getLocation(), Destructor,
14587                             PDiag(diag::err_access_dtor_ivar)
14588                               << Context.getBaseElementType(Field->getType()));
14589         }
14590       }
14591     }
14592     ObjCImplementation->setIvarInitializers(Context,
14593                                             AllToInit.data(), AllToInit.size());
14594   }
14595 }
14596 
14597 static
14598 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14599                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14600                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14601                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14602                            Sema &S) {
14603   if (Ctor->isInvalidDecl())
14604     return;
14605 
14606   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14607 
14608   // Target may not be determinable yet, for instance if this is a dependent
14609   // call in an uninstantiated template.
14610   if (Target) {
14611     const FunctionDecl *FNTarget = nullptr;
14612     (void)Target->hasBody(FNTarget);
14613     Target = const_cast<CXXConstructorDecl*>(
14614       cast_or_null<CXXConstructorDecl>(FNTarget));
14615   }
14616 
14617   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14618                      // Avoid dereferencing a null pointer here.
14619                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14620 
14621   if (!Current.insert(Canonical).second)
14622     return;
14623 
14624   // We know that beyond here, we aren't chaining into a cycle.
14625   if (!Target || !Target->isDelegatingConstructor() ||
14626       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14627     Valid.insert(Current.begin(), Current.end());
14628     Current.clear();
14629   // We've hit a cycle.
14630   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14631              Current.count(TCanonical)) {
14632     // If we haven't diagnosed this cycle yet, do so now.
14633     if (!Invalid.count(TCanonical)) {
14634       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14635              diag::warn_delegating_ctor_cycle)
14636         << Ctor;
14637 
14638       // Don't add a note for a function delegating directly to itself.
14639       if (TCanonical != Canonical)
14640         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14641 
14642       CXXConstructorDecl *C = Target;
14643       while (C->getCanonicalDecl() != Canonical) {
14644         const FunctionDecl *FNTarget = nullptr;
14645         (void)C->getTargetConstructor()->hasBody(FNTarget);
14646         assert(FNTarget && "Ctor cycle through bodiless function");
14647 
14648         C = const_cast<CXXConstructorDecl*>(
14649           cast<CXXConstructorDecl>(FNTarget));
14650         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14651       }
14652     }
14653 
14654     Invalid.insert(Current.begin(), Current.end());
14655     Current.clear();
14656   } else {
14657     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14658   }
14659 }
14660 
14661 
14662 void Sema::CheckDelegatingCtorCycles() {
14663   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14664 
14665   for (DelegatingCtorDeclsType::iterator
14666          I = DelegatingCtorDecls.begin(ExternalSource),
14667          E = DelegatingCtorDecls.end();
14668        I != E; ++I)
14669     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14670 
14671   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14672                                                          CE = Invalid.end();
14673        CI != CE; ++CI)
14674     (*CI)->setInvalidDecl();
14675 }
14676 
14677 namespace {
14678   /// \brief AST visitor that finds references to the 'this' expression.
14679   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14680     Sema &S;
14681 
14682   public:
14683     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14684 
14685     bool VisitCXXThisExpr(CXXThisExpr *E) {
14686       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14687         << E->isImplicit();
14688       return false;
14689     }
14690   };
14691 }
14692 
14693 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14694   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14695   if (!TSInfo)
14696     return false;
14697 
14698   TypeLoc TL = TSInfo->getTypeLoc();
14699   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14700   if (!ProtoTL)
14701     return false;
14702 
14703   // C++11 [expr.prim.general]p3:
14704   //   [The expression this] shall not appear before the optional
14705   //   cv-qualifier-seq and it shall not appear within the declaration of a
14706   //   static member function (although its type and value category are defined
14707   //   within a static member function as they are within a non-static member
14708   //   function). [ Note: this is because declaration matching does not occur
14709   //  until the complete declarator is known. - end note ]
14710   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14711   FindCXXThisExpr Finder(*this);
14712 
14713   // If the return type came after the cv-qualifier-seq, check it now.
14714   if (Proto->hasTrailingReturn() &&
14715       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14716     return true;
14717 
14718   // Check the exception specification.
14719   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14720     return true;
14721 
14722   return checkThisInStaticMemberFunctionAttributes(Method);
14723 }
14724 
14725 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14726   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14727   if (!TSInfo)
14728     return false;
14729 
14730   TypeLoc TL = TSInfo->getTypeLoc();
14731   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14732   if (!ProtoTL)
14733     return false;
14734 
14735   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14736   FindCXXThisExpr Finder(*this);
14737 
14738   switch (Proto->getExceptionSpecType()) {
14739   case EST_Unparsed:
14740   case EST_Uninstantiated:
14741   case EST_Unevaluated:
14742   case EST_BasicNoexcept:
14743   case EST_DynamicNone:
14744   case EST_MSAny:
14745   case EST_None:
14746     break;
14747 
14748   case EST_ComputedNoexcept:
14749     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14750       return true;
14751     LLVM_FALLTHROUGH;
14752 
14753   case EST_Dynamic:
14754     for (const auto &E : Proto->exceptions()) {
14755       if (!Finder.TraverseType(E))
14756         return true;
14757     }
14758     break;
14759   }
14760 
14761   return false;
14762 }
14763 
14764 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14765   FindCXXThisExpr Finder(*this);
14766 
14767   // Check attributes.
14768   for (const auto *A : Method->attrs()) {
14769     // FIXME: This should be emitted by tblgen.
14770     Expr *Arg = nullptr;
14771     ArrayRef<Expr *> Args;
14772     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14773       Arg = G->getArg();
14774     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14775       Arg = G->getArg();
14776     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14777       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14778     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14779       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14780     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14781       Arg = ETLF->getSuccessValue();
14782       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14783     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14784       Arg = STLF->getSuccessValue();
14785       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14786     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14787       Arg = LR->getArg();
14788     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14789       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14790     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14791       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14792     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14793       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14794     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14795       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14796     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14797       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14798 
14799     if (Arg && !Finder.TraverseStmt(Arg))
14800       return true;
14801 
14802     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14803       if (!Finder.TraverseStmt(Args[I]))
14804         return true;
14805     }
14806   }
14807 
14808   return false;
14809 }
14810 
14811 void Sema::checkExceptionSpecification(
14812     bool IsTopLevel, ExceptionSpecificationType EST,
14813     ArrayRef<ParsedType> DynamicExceptions,
14814     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14815     SmallVectorImpl<QualType> &Exceptions,
14816     FunctionProtoType::ExceptionSpecInfo &ESI) {
14817   Exceptions.clear();
14818   ESI.Type = EST;
14819   if (EST == EST_Dynamic) {
14820     Exceptions.reserve(DynamicExceptions.size());
14821     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14822       // FIXME: Preserve type source info.
14823       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14824 
14825       if (IsTopLevel) {
14826         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14827         collectUnexpandedParameterPacks(ET, Unexpanded);
14828         if (!Unexpanded.empty()) {
14829           DiagnoseUnexpandedParameterPacks(
14830               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14831               Unexpanded);
14832           continue;
14833         }
14834       }
14835 
14836       // Check that the type is valid for an exception spec, and
14837       // drop it if not.
14838       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14839         Exceptions.push_back(ET);
14840     }
14841     ESI.Exceptions = Exceptions;
14842     return;
14843   }
14844 
14845   if (EST == EST_ComputedNoexcept) {
14846     // If an error occurred, there's no expression here.
14847     if (NoexceptExpr) {
14848       assert((NoexceptExpr->isTypeDependent() ||
14849               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14850               Context.BoolTy) &&
14851              "Parser should have made sure that the expression is boolean");
14852       if (IsTopLevel && NoexceptExpr &&
14853           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14854         ESI.Type = EST_BasicNoexcept;
14855         return;
14856       }
14857 
14858       if (!NoexceptExpr->isValueDependent())
14859         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14860                          diag::err_noexcept_needs_constant_expression,
14861                          /*AllowFold*/ false).get();
14862       ESI.NoexceptExpr = NoexceptExpr;
14863     }
14864     return;
14865   }
14866 }
14867 
14868 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14869              ExceptionSpecificationType EST,
14870              SourceRange SpecificationRange,
14871              ArrayRef<ParsedType> DynamicExceptions,
14872              ArrayRef<SourceRange> DynamicExceptionRanges,
14873              Expr *NoexceptExpr) {
14874   if (!MethodD)
14875     return;
14876 
14877   // Dig out the method we're referring to.
14878   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14879     MethodD = FunTmpl->getTemplatedDecl();
14880 
14881   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14882   if (!Method)
14883     return;
14884 
14885   // Check the exception specification.
14886   llvm::SmallVector<QualType, 4> Exceptions;
14887   FunctionProtoType::ExceptionSpecInfo ESI;
14888   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14889                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14890                               ESI);
14891 
14892   // Update the exception specification on the function type.
14893   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14894 
14895   if (Method->isStatic())
14896     checkThisInStaticMemberFunctionExceptionSpec(Method);
14897 
14898   if (Method->isVirtual()) {
14899     // Check overrides, which we previously had to delay.
14900     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14901                                      OEnd = Method->end_overridden_methods();
14902          O != OEnd; ++O)
14903       CheckOverridingFunctionExceptionSpec(Method, *O);
14904   }
14905 }
14906 
14907 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14908 ///
14909 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14910                                        SourceLocation DeclStart,
14911                                        Declarator &D, Expr *BitWidth,
14912                                        InClassInitStyle InitStyle,
14913                                        AccessSpecifier AS,
14914                                        AttributeList *MSPropertyAttr) {
14915   IdentifierInfo *II = D.getIdentifier();
14916   if (!II) {
14917     Diag(DeclStart, diag::err_anonymous_property);
14918     return nullptr;
14919   }
14920   SourceLocation Loc = D.getIdentifierLoc();
14921 
14922   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14923   QualType T = TInfo->getType();
14924   if (getLangOpts().CPlusPlus) {
14925     CheckExtraCXXDefaultArguments(D);
14926 
14927     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14928                                         UPPC_DataMemberType)) {
14929       D.setInvalidType();
14930       T = Context.IntTy;
14931       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14932     }
14933   }
14934 
14935   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14936 
14937   if (D.getDeclSpec().isInlineSpecified())
14938     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14939         << getLangOpts().CPlusPlus1z;
14940   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14941     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14942          diag::err_invalid_thread)
14943       << DeclSpec::getSpecifierName(TSCS);
14944 
14945   // Check to see if this name was declared as a member previously
14946   NamedDecl *PrevDecl = nullptr;
14947   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14948   LookupName(Previous, S);
14949   switch (Previous.getResultKind()) {
14950   case LookupResult::Found:
14951   case LookupResult::FoundUnresolvedValue:
14952     PrevDecl = Previous.getAsSingle<NamedDecl>();
14953     break;
14954 
14955   case LookupResult::FoundOverloaded:
14956     PrevDecl = Previous.getRepresentativeDecl();
14957     break;
14958 
14959   case LookupResult::NotFound:
14960   case LookupResult::NotFoundInCurrentInstantiation:
14961   case LookupResult::Ambiguous:
14962     break;
14963   }
14964 
14965   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14966     // Maybe we will complain about the shadowed template parameter.
14967     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14968     // Just pretend that we didn't see the previous declaration.
14969     PrevDecl = nullptr;
14970   }
14971 
14972   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14973     PrevDecl = nullptr;
14974 
14975   SourceLocation TSSL = D.getLocStart();
14976   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14977   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14978       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14979   ProcessDeclAttributes(TUScope, NewPD, D);
14980   NewPD->setAccess(AS);
14981 
14982   if (NewPD->isInvalidDecl())
14983     Record->setInvalidDecl();
14984 
14985   if (D.getDeclSpec().isModulePrivateSpecified())
14986     NewPD->setModulePrivate();
14987 
14988   if (NewPD->isInvalidDecl() && PrevDecl) {
14989     // Don't introduce NewFD into scope; there's already something
14990     // with the same name in the same scope.
14991   } else if (II) {
14992     PushOnScopeChains(NewPD, S);
14993   } else
14994     Record->addDecl(NewPD);
14995 
14996   return NewPD;
14997 }
14998