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   // a for-range-declaration, or a condition in Clang, but we parse it in more
697   // cases than that.
698   if (!D.mayHaveDecompositionDeclarator()) {
699     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
700       << Decomp.getSourceRange();
701     return nullptr;
702   }
703 
704   if (!TemplateParamLists.empty()) {
705     // FIXME: There's no rule against this, but there are also no rules that
706     // would actually make it usable, so we reject it for now.
707     Diag(TemplateParamLists.front()->getTemplateLoc(),
708          diag::err_decomp_decl_template);
709     return nullptr;
710   }
711 
712   Diag(Decomp.getLSquareLoc(),
713        !getLangOpts().CPlusPlus17
714            ? diag::ext_decomp_decl
715            : D.getContext() == DeclaratorContext::ConditionContext
716                  ? diag::ext_decomp_decl_cond
717                  : diag::warn_cxx14_compat_decomp_decl)
718       << Decomp.getSourceRange();
719 
720   // The semantic context is always just the current context.
721   DeclContext *const DC = CurContext;
722 
723   // C++1z [dcl.dcl]/8:
724   //   The decl-specifier-seq shall contain only the type-specifier auto
725   //   and cv-qualifiers.
726   auto &DS = D.getDeclSpec();
727   {
728     SmallVector<StringRef, 8> BadSpecifiers;
729     SmallVector<SourceLocation, 8> BadSpecifierLocs;
730     if (auto SCS = DS.getStorageClassSpec()) {
731       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
732       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
733     }
734     if (auto TSCS = DS.getThreadStorageClassSpec()) {
735       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
736       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
737     }
738     if (DS.isConstexprSpecified()) {
739       BadSpecifiers.push_back("constexpr");
740       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
741     }
742     if (DS.isInlineSpecified()) {
743       BadSpecifiers.push_back("inline");
744       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
745     }
746     if (!BadSpecifiers.empty()) {
747       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
748       Err << (int)BadSpecifiers.size()
749           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
750       // Don't add FixItHints to remove the specifiers; we do still respect
751       // them when building the underlying variable.
752       for (auto Loc : BadSpecifierLocs)
753         Err << SourceRange(Loc, Loc);
754     }
755     // We can't recover from it being declared as a typedef.
756     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
757       return nullptr;
758   }
759 
760   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
761   QualType R = TInfo->getType();
762 
763   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
764                                       UPPC_DeclarationType))
765     D.setInvalidType();
766 
767   // The syntax only allows a single ref-qualifier prior to the decomposition
768   // declarator. No other declarator chunks are permitted. Also check the type
769   // specifier here.
770   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
771       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
772       (D.getNumTypeObjects() == 1 &&
773        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
774     Diag(Decomp.getLSquareLoc(),
775          (D.hasGroupingParens() ||
776           (D.getNumTypeObjects() &&
777            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
778              ? diag::err_decomp_decl_parens
779              : diag::err_decomp_decl_type)
780         << R;
781 
782     // In most cases, there's no actual problem with an explicitly-specified
783     // type, but a function type won't work here, and ActOnVariableDeclarator
784     // shouldn't be called for such a type.
785     if (R->isFunctionType())
786       D.setInvalidType();
787   }
788 
789   // Build the BindingDecls.
790   SmallVector<BindingDecl*, 8> Bindings;
791 
792   // Build the BindingDecls.
793   for (auto &B : D.getDecompositionDeclarator().bindings()) {
794     // Check for name conflicts.
795     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
796     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
797                           ForVisibleRedeclaration);
798     LookupName(Previous, S,
799                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
800 
801     // It's not permitted to shadow a template parameter name.
802     if (Previous.isSingleResult() &&
803         Previous.getFoundDecl()->isTemplateParameter()) {
804       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
805                                       Previous.getFoundDecl());
806       Previous.clear();
807     }
808 
809     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
810                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
811     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
812                          /*AllowInlineNamespace*/false);
813     if (!Previous.empty()) {
814       auto *Old = Previous.getRepresentativeDecl();
815       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
816       Diag(Old->getLocation(), diag::note_previous_definition);
817     }
818 
819     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
820     PushOnScopeChains(BD, S, true);
821     Bindings.push_back(BD);
822     ParsingInitForAutoVars.insert(BD);
823   }
824 
825   // There are no prior lookup results for the variable itself, because it
826   // is unnamed.
827   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
828                                Decomp.getLSquareLoc());
829   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
830                         ForVisibleRedeclaration);
831 
832   // Build the variable that holds the non-decomposed object.
833   bool AddToScope = true;
834   NamedDecl *New =
835       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
836                               MultiTemplateParamsArg(), AddToScope, Bindings);
837   if (AddToScope) {
838     S->AddDecl(New);
839     CurContext->addHiddenDecl(New);
840   }
841 
842   if (isInOpenMPDeclareTargetContext())
843     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
844 
845   return New;
846 }
847 
848 static bool checkSimpleDecomposition(
849     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
850     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
851     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
852   if ((int64_t)Bindings.size() != NumElems) {
853     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
854         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
855         << (NumElems < Bindings.size());
856     return true;
857   }
858 
859   unsigned I = 0;
860   for (auto *B : Bindings) {
861     SourceLocation Loc = B->getLocation();
862     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
863     if (E.isInvalid())
864       return true;
865     E = GetInit(Loc, E.get(), I++);
866     if (E.isInvalid())
867       return true;
868     B->setBinding(ElemType, E.get());
869   }
870 
871   return false;
872 }
873 
874 static bool checkArrayLikeDecomposition(Sema &S,
875                                         ArrayRef<BindingDecl *> Bindings,
876                                         ValueDecl *Src, QualType DecompType,
877                                         const llvm::APSInt &NumElems,
878                                         QualType ElemType) {
879   return checkSimpleDecomposition(
880       S, Bindings, Src, DecompType, NumElems, ElemType,
881       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
882         ExprResult E = S.ActOnIntegerConstant(Loc, I);
883         if (E.isInvalid())
884           return ExprError();
885         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
886       });
887 }
888 
889 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
890                                     ValueDecl *Src, QualType DecompType,
891                                     const ConstantArrayType *CAT) {
892   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
893                                      llvm::APSInt(CAT->getSize()),
894                                      CAT->getElementType());
895 }
896 
897 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
898                                      ValueDecl *Src, QualType DecompType,
899                                      const VectorType *VT) {
900   return checkArrayLikeDecomposition(
901       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
902       S.Context.getQualifiedType(VT->getElementType(),
903                                  DecompType.getQualifiers()));
904 }
905 
906 static bool checkComplexDecomposition(Sema &S,
907                                       ArrayRef<BindingDecl *> Bindings,
908                                       ValueDecl *Src, QualType DecompType,
909                                       const ComplexType *CT) {
910   return checkSimpleDecomposition(
911       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
912       S.Context.getQualifiedType(CT->getElementType(),
913                                  DecompType.getQualifiers()),
914       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
915         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
916       });
917 }
918 
919 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
920                                      TemplateArgumentListInfo &Args) {
921   SmallString<128> SS;
922   llvm::raw_svector_ostream OS(SS);
923   bool First = true;
924   for (auto &Arg : Args.arguments()) {
925     if (!First)
926       OS << ", ";
927     Arg.getArgument().print(PrintingPolicy, OS);
928     First = false;
929   }
930   return OS.str();
931 }
932 
933 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
934                                      SourceLocation Loc, StringRef Trait,
935                                      TemplateArgumentListInfo &Args,
936                                      unsigned DiagID) {
937   auto DiagnoseMissing = [&] {
938     if (DiagID)
939       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
940                                                Args);
941     return true;
942   };
943 
944   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
945   NamespaceDecl *Std = S.getStdNamespace();
946   if (!Std)
947     return DiagnoseMissing();
948 
949   // Look up the trait itself, within namespace std. We can diagnose various
950   // problems with this lookup even if we've been asked to not diagnose a
951   // missing specialization, because this can only fail if the user has been
952   // declaring their own names in namespace std or we don't support the
953   // standard library implementation in use.
954   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
955                       Loc, Sema::LookupOrdinaryName);
956   if (!S.LookupQualifiedName(Result, Std))
957     return DiagnoseMissing();
958   if (Result.isAmbiguous())
959     return true;
960 
961   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
962   if (!TraitTD) {
963     Result.suppressDiagnostics();
964     NamedDecl *Found = *Result.begin();
965     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
966     S.Diag(Found->getLocation(), diag::note_declared_at);
967     return true;
968   }
969 
970   // Build the template-id.
971   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
972   if (TraitTy.isNull())
973     return true;
974   if (!S.isCompleteType(Loc, TraitTy)) {
975     if (DiagID)
976       S.RequireCompleteType(
977           Loc, TraitTy, DiagID,
978           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
979     return true;
980   }
981 
982   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
983   assert(RD && "specialization of class template is not a class?");
984 
985   // Look up the member of the trait type.
986   S.LookupQualifiedName(TraitMemberLookup, RD);
987   return TraitMemberLookup.isAmbiguous();
988 }
989 
990 static TemplateArgumentLoc
991 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
992                                    uint64_t I) {
993   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
994   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
995 }
996 
997 static TemplateArgumentLoc
998 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
999   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1000 }
1001 
1002 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1003 
1004 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1005                                llvm::APSInt &Size) {
1006   EnterExpressionEvaluationContext ContextRAII(
1007       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1008 
1009   DeclarationName Value = S.PP.getIdentifierInfo("value");
1010   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1011 
1012   // Form template argument list for tuple_size<T>.
1013   TemplateArgumentListInfo Args(Loc, Loc);
1014   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1015 
1016   // If there's no tuple_size specialization, it's not tuple-like.
1017   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1018     return IsTupleLike::NotTupleLike;
1019 
1020   // If we get this far, we've committed to the tuple interpretation, but
1021   // we can still fail if there actually isn't a usable ::value.
1022 
1023   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1024     LookupResult &R;
1025     TemplateArgumentListInfo &Args;
1026     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1027         : R(R), Args(Args) {}
1028     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1029       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1030           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1031     }
1032   } Diagnoser(R, Args);
1033 
1034   if (R.empty()) {
1035     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1036     return IsTupleLike::Error;
1037   }
1038 
1039   ExprResult E =
1040       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1041   if (E.isInvalid())
1042     return IsTupleLike::Error;
1043 
1044   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1045   if (E.isInvalid())
1046     return IsTupleLike::Error;
1047 
1048   return IsTupleLike::TupleLike;
1049 }
1050 
1051 /// \return std::tuple_element<I, T>::type.
1052 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1053                                         unsigned I, QualType T) {
1054   // Form template argument list for tuple_element<I, T>.
1055   TemplateArgumentListInfo Args(Loc, Loc);
1056   Args.addArgument(
1057       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1058   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1059 
1060   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1061   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1062   if (lookupStdTypeTraitMember(
1063           S, R, Loc, "tuple_element", Args,
1064           diag::err_decomp_decl_std_tuple_element_not_specialized))
1065     return QualType();
1066 
1067   auto *TD = R.getAsSingle<TypeDecl>();
1068   if (!TD) {
1069     R.suppressDiagnostics();
1070     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1071       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1072     if (!R.empty())
1073       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1074     return QualType();
1075   }
1076 
1077   return S.Context.getTypeDeclType(TD);
1078 }
1079 
1080 namespace {
1081 struct BindingDiagnosticTrap {
1082   Sema &S;
1083   DiagnosticErrorTrap Trap;
1084   BindingDecl *BD;
1085 
1086   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1087       : S(S), Trap(S.Diags), BD(BD) {}
1088   ~BindingDiagnosticTrap() {
1089     if (Trap.hasErrorOccurred())
1090       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1091   }
1092 };
1093 }
1094 
1095 static bool checkTupleLikeDecomposition(Sema &S,
1096                                         ArrayRef<BindingDecl *> Bindings,
1097                                         VarDecl *Src, QualType DecompType,
1098                                         const llvm::APSInt &TupleSize) {
1099   if ((int64_t)Bindings.size() != TupleSize) {
1100     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1101         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1102         << (TupleSize < Bindings.size());
1103     return true;
1104   }
1105 
1106   if (Bindings.empty())
1107     return false;
1108 
1109   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1110 
1111   // [dcl.decomp]p3:
1112   //   The unqualified-id get is looked up in the scope of E by class member
1113   //   access lookup
1114   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1115   bool UseMemberGet = false;
1116   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1117     if (auto *RD = DecompType->getAsCXXRecordDecl())
1118       S.LookupQualifiedName(MemberGet, RD);
1119     if (MemberGet.isAmbiguous())
1120       return true;
1121     UseMemberGet = !MemberGet.empty();
1122     S.FilterAcceptableTemplateNames(MemberGet);
1123   }
1124 
1125   unsigned I = 0;
1126   for (auto *B : Bindings) {
1127     BindingDiagnosticTrap Trap(S, B);
1128     SourceLocation Loc = B->getLocation();
1129 
1130     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1131     if (E.isInvalid())
1132       return true;
1133 
1134     //   e is an lvalue if the type of the entity is an lvalue reference and
1135     //   an xvalue otherwise
1136     if (!Src->getType()->isLValueReferenceType())
1137       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1138                                    E.get(), nullptr, VK_XValue);
1139 
1140     TemplateArgumentListInfo Args(Loc, Loc);
1141     Args.addArgument(
1142         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1143 
1144     if (UseMemberGet) {
1145       //   if [lookup of member get] finds at least one declaration, the
1146       //   initializer is e.get<i-1>().
1147       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1148                                      CXXScopeSpec(), SourceLocation(), nullptr,
1149                                      MemberGet, &Args, nullptr);
1150       if (E.isInvalid())
1151         return true;
1152 
1153       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1154     } else {
1155       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1156       //   in the associated namespaces.
1157       Expr *Get = UnresolvedLookupExpr::Create(
1158           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1159           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1160           UnresolvedSetIterator(), UnresolvedSetIterator());
1161 
1162       Expr *Arg = E.get();
1163       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1164     }
1165     if (E.isInvalid())
1166       return true;
1167     Expr *Init = E.get();
1168 
1169     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1170     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1171     if (T.isNull())
1172       return true;
1173 
1174     //   each vi is a variable of type "reference to T" initialized with the
1175     //   initializer, where the reference is an lvalue reference if the
1176     //   initializer is an lvalue and an rvalue reference otherwise
1177     QualType RefType =
1178         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1179     if (RefType.isNull())
1180       return true;
1181     auto *RefVD = VarDecl::Create(
1182         S.Context, Src->getDeclContext(), Loc, Loc,
1183         B->getDeclName().getAsIdentifierInfo(), RefType,
1184         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1185     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1186     RefVD->setTSCSpec(Src->getTSCSpec());
1187     RefVD->setImplicit();
1188     if (Src->isInlineSpecified())
1189       RefVD->setInlineSpecified();
1190     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1191 
1192     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1193     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1194     InitializationSequence Seq(S, Entity, Kind, Init);
1195     E = Seq.Perform(S, Entity, Kind, Init);
1196     if (E.isInvalid())
1197       return true;
1198     E = S.ActOnFinishFullExpr(E.get(), Loc);
1199     if (E.isInvalid())
1200       return true;
1201     RefVD->setInit(E.get());
1202     RefVD->checkInitIsICE();
1203 
1204     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1205                                    DeclarationNameInfo(B->getDeclName(), Loc),
1206                                    RefVD);
1207     if (E.isInvalid())
1208       return true;
1209 
1210     B->setBinding(T, E.get());
1211     I++;
1212   }
1213 
1214   return false;
1215 }
1216 
1217 /// Find the base class to decompose in a built-in decomposition of a class type.
1218 /// This base class search is, unfortunately, not quite like any other that we
1219 /// perform anywhere else in C++.
1220 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1221                                                       SourceLocation Loc,
1222                                                       const CXXRecordDecl *RD,
1223                                                       CXXCastPath &BasePath) {
1224   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1225                           CXXBasePath &Path) {
1226     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1227   };
1228 
1229   const CXXRecordDecl *ClassWithFields = nullptr;
1230   if (RD->hasDirectFields())
1231     // [dcl.decomp]p4:
1232     //   Otherwise, all of E's non-static data members shall be public direct
1233     //   members of E ...
1234     ClassWithFields = RD;
1235   else {
1236     //   ... or of ...
1237     CXXBasePaths Paths;
1238     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1239     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1240       // If no classes have fields, just decompose RD itself. (This will work
1241       // if and only if zero bindings were provided.)
1242       return RD;
1243     }
1244 
1245     CXXBasePath *BestPath = nullptr;
1246     for (auto &P : Paths) {
1247       if (!BestPath)
1248         BestPath = &P;
1249       else if (!S.Context.hasSameType(P.back().Base->getType(),
1250                                       BestPath->back().Base->getType())) {
1251         //   ... the same ...
1252         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1253           << false << RD << BestPath->back().Base->getType()
1254           << P.back().Base->getType();
1255         return nullptr;
1256       } else if (P.Access < BestPath->Access) {
1257         BestPath = &P;
1258       }
1259     }
1260 
1261     //   ... unambiguous ...
1262     QualType BaseType = BestPath->back().Base->getType();
1263     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1264       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1265         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1266       return nullptr;
1267     }
1268 
1269     //   ... public base class of E.
1270     if (BestPath->Access != AS_public) {
1271       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1272         << RD << BaseType;
1273       for (auto &BS : *BestPath) {
1274         if (BS.Base->getAccessSpecifier() != AS_public) {
1275           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1276             << (BS.Base->getAccessSpecifier() == AS_protected)
1277             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1278           break;
1279         }
1280       }
1281       return nullptr;
1282     }
1283 
1284     ClassWithFields = BaseType->getAsCXXRecordDecl();
1285     S.BuildBasePathArray(Paths, BasePath);
1286   }
1287 
1288   // The above search did not check whether the selected class itself has base
1289   // classes with fields, so check that now.
1290   CXXBasePaths Paths;
1291   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293       << (ClassWithFields == RD) << RD << ClassWithFields
1294       << Paths.front().back().Base->getType();
1295     return nullptr;
1296   }
1297 
1298   return ClassWithFields;
1299 }
1300 
1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1302                                      ValueDecl *Src, QualType DecompType,
1303                                      const CXXRecordDecl *RD) {
1304   CXXCastPath BasePath;
1305   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1306   if (!RD)
1307     return true;
1308   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1309                                                  DecompType.getQualifiers());
1310 
1311   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1312     unsigned NumFields =
1313         std::count_if(RD->field_begin(), RD->field_end(),
1314                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1315     assert(Bindings.size() != NumFields);
1316     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1317         << DecompType << (unsigned)Bindings.size() << NumFields
1318         << (NumFields < Bindings.size());
1319     return true;
1320   };
1321 
1322   //   all of E's non-static data members shall be public [...] members,
1323   //   E shall not have an anonymous union member, ...
1324   unsigned I = 0;
1325   for (auto *FD : RD->fields()) {
1326     if (FD->isUnnamedBitfield())
1327       continue;
1328 
1329     if (FD->isAnonymousStructOrUnion()) {
1330       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1331         << DecompType << FD->getType()->isUnionType();
1332       S.Diag(FD->getLocation(), diag::note_declared_at);
1333       return true;
1334     }
1335 
1336     // We have a real field to bind.
1337     if (I >= Bindings.size())
1338       return DiagnoseBadNumberOfBindings();
1339     auto *B = Bindings[I++];
1340 
1341     SourceLocation Loc = B->getLocation();
1342     if (FD->getAccess() != AS_public) {
1343       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1344 
1345       // Determine whether the access specifier was explicit.
1346       bool Implicit = true;
1347       for (const auto *D : RD->decls()) {
1348         if (declaresSameEntity(D, FD))
1349           break;
1350         if (isa<AccessSpecDecl>(D)) {
1351           Implicit = false;
1352           break;
1353         }
1354       }
1355 
1356       S.Diag(FD->getLocation(), diag::note_access_natural)
1357         << (FD->getAccess() == AS_protected) << Implicit;
1358       return true;
1359     }
1360 
1361     // Initialize the binding to Src.FD.
1362     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1363     if (E.isInvalid())
1364       return true;
1365     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1366                             VK_LValue, &BasePath);
1367     if (E.isInvalid())
1368       return true;
1369     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1370                                   CXXScopeSpec(), FD,
1371                                   DeclAccessPair::make(FD, FD->getAccess()),
1372                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1373     if (E.isInvalid())
1374       return true;
1375 
1376     // If the type of the member is T, the referenced type is cv T, where cv is
1377     // the cv-qualification of the decomposition expression.
1378     //
1379     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1380     // 'const' to the type of the field.
1381     Qualifiers Q = DecompType.getQualifiers();
1382     if (FD->isMutable())
1383       Q.removeConst();
1384     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1385   }
1386 
1387   if (I != Bindings.size())
1388     return DiagnoseBadNumberOfBindings();
1389 
1390   return false;
1391 }
1392 
1393 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1394   QualType DecompType = DD->getType();
1395 
1396   // If the type of the decomposition is dependent, then so is the type of
1397   // each binding.
1398   if (DecompType->isDependentType()) {
1399     for (auto *B : DD->bindings())
1400       B->setType(Context.DependentTy);
1401     return;
1402   }
1403 
1404   DecompType = DecompType.getNonReferenceType();
1405   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1406 
1407   // C++1z [dcl.decomp]/2:
1408   //   If E is an array type [...]
1409   // As an extension, we also support decomposition of built-in complex and
1410   // vector types.
1411   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1412     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1413       DD->setInvalidDecl();
1414     return;
1415   }
1416   if (auto *VT = DecompType->getAs<VectorType>()) {
1417     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1418       DD->setInvalidDecl();
1419     return;
1420   }
1421   if (auto *CT = DecompType->getAs<ComplexType>()) {
1422     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1423       DD->setInvalidDecl();
1424     return;
1425   }
1426 
1427   // C++1z [dcl.decomp]/3:
1428   //   if the expression std::tuple_size<E>::value is a well-formed integral
1429   //   constant expression, [...]
1430   llvm::APSInt TupleSize(32);
1431   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1432   case IsTupleLike::Error:
1433     DD->setInvalidDecl();
1434     return;
1435 
1436   case IsTupleLike::TupleLike:
1437     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1438       DD->setInvalidDecl();
1439     return;
1440 
1441   case IsTupleLike::NotTupleLike:
1442     break;
1443   }
1444 
1445   // C++1z [dcl.dcl]/8:
1446   //   [E shall be of array or non-union class type]
1447   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1448   if (!RD || RD->isUnion()) {
1449     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1450         << DD << !RD << DecompType;
1451     DD->setInvalidDecl();
1452     return;
1453   }
1454 
1455   // C++1z [dcl.decomp]/4:
1456   //   all of E's non-static data members shall be [...] direct members of
1457   //   E or of the same unambiguous public base class of E, ...
1458   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1459     DD->setInvalidDecl();
1460 }
1461 
1462 /// \brief Merge the exception specifications of two variable declarations.
1463 ///
1464 /// This is called when there's a redeclaration of a VarDecl. The function
1465 /// checks if the redeclaration might have an exception specification and
1466 /// validates compatibility and merges the specs if necessary.
1467 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1468   // Shortcut if exceptions are disabled.
1469   if (!getLangOpts().CXXExceptions)
1470     return;
1471 
1472   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1473          "Should only be called if types are otherwise the same.");
1474 
1475   QualType NewType = New->getType();
1476   QualType OldType = Old->getType();
1477 
1478   // We're only interested in pointers and references to functions, as well
1479   // as pointers to member functions.
1480   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1481     NewType = R->getPointeeType();
1482     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1483   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1484     NewType = P->getPointeeType();
1485     OldType = OldType->getAs<PointerType>()->getPointeeType();
1486   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1487     NewType = M->getPointeeType();
1488     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1489   }
1490 
1491   if (!NewType->isFunctionProtoType())
1492     return;
1493 
1494   // There's lots of special cases for functions. For function pointers, system
1495   // libraries are hopefully not as broken so that we don't need these
1496   // workarounds.
1497   if (CheckEquivalentExceptionSpec(
1498         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1499         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1500     New->setInvalidDecl();
1501   }
1502 }
1503 
1504 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1505 /// function declaration are well-formed according to C++
1506 /// [dcl.fct.default].
1507 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1508   unsigned NumParams = FD->getNumParams();
1509   unsigned p;
1510 
1511   // Find first parameter with a default argument
1512   for (p = 0; p < NumParams; ++p) {
1513     ParmVarDecl *Param = FD->getParamDecl(p);
1514     if (Param->hasDefaultArg())
1515       break;
1516   }
1517 
1518   // C++11 [dcl.fct.default]p4:
1519   //   In a given function declaration, each parameter subsequent to a parameter
1520   //   with a default argument shall have a default argument supplied in this or
1521   //   a previous declaration or shall be a function parameter pack. A default
1522   //   argument shall not be redefined by a later declaration (not even to the
1523   //   same value).
1524   unsigned LastMissingDefaultArg = 0;
1525   for (; p < NumParams; ++p) {
1526     ParmVarDecl *Param = FD->getParamDecl(p);
1527     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1528       if (Param->isInvalidDecl())
1529         /* We already complained about this parameter. */;
1530       else if (Param->getIdentifier())
1531         Diag(Param->getLocation(),
1532              diag::err_param_default_argument_missing_name)
1533           << Param->getIdentifier();
1534       else
1535         Diag(Param->getLocation(),
1536              diag::err_param_default_argument_missing);
1537 
1538       LastMissingDefaultArg = p;
1539     }
1540   }
1541 
1542   if (LastMissingDefaultArg > 0) {
1543     // Some default arguments were missing. Clear out all of the
1544     // default arguments up to (and including) the last missing
1545     // default argument, so that we leave the function parameters
1546     // in a semantically valid state.
1547     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1548       ParmVarDecl *Param = FD->getParamDecl(p);
1549       if (Param->hasDefaultArg()) {
1550         Param->setDefaultArg(nullptr);
1551       }
1552     }
1553   }
1554 }
1555 
1556 // CheckConstexprParameterTypes - Check whether a function's parameter types
1557 // are all literal types. If so, return true. If not, produce a suitable
1558 // diagnostic and return false.
1559 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1560                                          const FunctionDecl *FD) {
1561   unsigned ArgIndex = 0;
1562   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1563   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1564                                               e = FT->param_type_end();
1565        i != e; ++i, ++ArgIndex) {
1566     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1567     SourceLocation ParamLoc = PD->getLocation();
1568     if (!(*i)->isDependentType() &&
1569         SemaRef.RequireLiteralType(ParamLoc, *i,
1570                                    diag::err_constexpr_non_literal_param,
1571                                    ArgIndex+1, PD->getSourceRange(),
1572                                    isa<CXXConstructorDecl>(FD)))
1573       return false;
1574   }
1575   return true;
1576 }
1577 
1578 /// \brief Get diagnostic %select index for tag kind for
1579 /// record diagnostic message.
1580 /// WARNING: Indexes apply to particular diagnostics only!
1581 ///
1582 /// \returns diagnostic %select index.
1583 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1584   switch (Tag) {
1585   case TTK_Struct: return 0;
1586   case TTK_Interface: return 1;
1587   case TTK_Class:  return 2;
1588   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1589   }
1590 }
1591 
1592 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1593 // the requirements of a constexpr function definition or a constexpr
1594 // constructor definition. If so, return true. If not, produce appropriate
1595 // diagnostics and return false.
1596 //
1597 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1598 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1599   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1600   if (MD && MD->isInstance()) {
1601     // C++11 [dcl.constexpr]p4:
1602     //  The definition of a constexpr constructor shall satisfy the following
1603     //  constraints:
1604     //  - the class shall not have any virtual base classes;
1605     const CXXRecordDecl *RD = MD->getParent();
1606     if (RD->getNumVBases()) {
1607       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1608         << isa<CXXConstructorDecl>(NewFD)
1609         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1610       for (const auto &I : RD->vbases())
1611         Diag(I.getLocStart(),
1612              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1613       return false;
1614     }
1615   }
1616 
1617   if (!isa<CXXConstructorDecl>(NewFD)) {
1618     // C++11 [dcl.constexpr]p3:
1619     //  The definition of a constexpr function shall satisfy the following
1620     //  constraints:
1621     // - it shall not be virtual;
1622     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1623     if (Method && Method->isVirtual()) {
1624       Method = Method->getCanonicalDecl();
1625       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1626 
1627       // If it's not obvious why this function is virtual, find an overridden
1628       // function which uses the 'virtual' keyword.
1629       const CXXMethodDecl *WrittenVirtual = Method;
1630       while (!WrittenVirtual->isVirtualAsWritten())
1631         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1632       if (WrittenVirtual != Method)
1633         Diag(WrittenVirtual->getLocation(),
1634              diag::note_overridden_virtual_function);
1635       return false;
1636     }
1637 
1638     // - its return type shall be a literal type;
1639     QualType RT = NewFD->getReturnType();
1640     if (!RT->isDependentType() &&
1641         RequireLiteralType(NewFD->getLocation(), RT,
1642                            diag::err_constexpr_non_literal_return))
1643       return false;
1644   }
1645 
1646   // - each of its parameter types shall be a literal type;
1647   if (!CheckConstexprParameterTypes(*this, NewFD))
1648     return false;
1649 
1650   return true;
1651 }
1652 
1653 /// Check the given declaration statement is legal within a constexpr function
1654 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1655 ///
1656 /// \return true if the body is OK (maybe only as an extension), false if we
1657 ///         have diagnosed a problem.
1658 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1659                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1660   // C++11 [dcl.constexpr]p3 and p4:
1661   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1662   //  contain only
1663   for (const auto *DclIt : DS->decls()) {
1664     switch (DclIt->getKind()) {
1665     case Decl::StaticAssert:
1666     case Decl::Using:
1667     case Decl::UsingShadow:
1668     case Decl::UsingDirective:
1669     case Decl::UnresolvedUsingTypename:
1670     case Decl::UnresolvedUsingValue:
1671       //   - static_assert-declarations
1672       //   - using-declarations,
1673       //   - using-directives,
1674       continue;
1675 
1676     case Decl::Typedef:
1677     case Decl::TypeAlias: {
1678       //   - typedef declarations and alias-declarations that do not define
1679       //     classes or enumerations,
1680       const auto *TN = cast<TypedefNameDecl>(DclIt);
1681       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1682         // Don't allow variably-modified types in constexpr functions.
1683         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1684         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1685           << TL.getSourceRange() << TL.getType()
1686           << isa<CXXConstructorDecl>(Dcl);
1687         return false;
1688       }
1689       continue;
1690     }
1691 
1692     case Decl::Enum:
1693     case Decl::CXXRecord:
1694       // C++1y allows types to be defined, not just declared.
1695       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1696         SemaRef.Diag(DS->getLocStart(),
1697                      SemaRef.getLangOpts().CPlusPlus14
1698                        ? diag::warn_cxx11_compat_constexpr_type_definition
1699                        : diag::ext_constexpr_type_definition)
1700           << isa<CXXConstructorDecl>(Dcl);
1701       continue;
1702 
1703     case Decl::EnumConstant:
1704     case Decl::IndirectField:
1705     case Decl::ParmVar:
1706       // These can only appear with other declarations which are banned in
1707       // C++11 and permitted in C++1y, so ignore them.
1708       continue;
1709 
1710     case Decl::Var:
1711     case Decl::Decomposition: {
1712       // C++1y [dcl.constexpr]p3 allows anything except:
1713       //   a definition of a variable of non-literal type or of static or
1714       //   thread storage duration or for which no initialization is performed.
1715       const auto *VD = cast<VarDecl>(DclIt);
1716       if (VD->isThisDeclarationADefinition()) {
1717         if (VD->isStaticLocal()) {
1718           SemaRef.Diag(VD->getLocation(),
1719                        diag::err_constexpr_local_var_static)
1720             << isa<CXXConstructorDecl>(Dcl)
1721             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1722           return false;
1723         }
1724         if (!VD->getType()->isDependentType() &&
1725             SemaRef.RequireLiteralType(
1726               VD->getLocation(), VD->getType(),
1727               diag::err_constexpr_local_var_non_literal_type,
1728               isa<CXXConstructorDecl>(Dcl)))
1729           return false;
1730         if (!VD->getType()->isDependentType() &&
1731             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1732           SemaRef.Diag(VD->getLocation(),
1733                        diag::err_constexpr_local_var_no_init)
1734             << isa<CXXConstructorDecl>(Dcl);
1735           return false;
1736         }
1737       }
1738       SemaRef.Diag(VD->getLocation(),
1739                    SemaRef.getLangOpts().CPlusPlus14
1740                     ? diag::warn_cxx11_compat_constexpr_local_var
1741                     : diag::ext_constexpr_local_var)
1742         << isa<CXXConstructorDecl>(Dcl);
1743       continue;
1744     }
1745 
1746     case Decl::NamespaceAlias:
1747     case Decl::Function:
1748       // These are disallowed in C++11 and permitted in C++1y. Allow them
1749       // everywhere as an extension.
1750       if (!Cxx1yLoc.isValid())
1751         Cxx1yLoc = DS->getLocStart();
1752       continue;
1753 
1754     default:
1755       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1756         << isa<CXXConstructorDecl>(Dcl);
1757       return false;
1758     }
1759   }
1760 
1761   return true;
1762 }
1763 
1764 /// Check that the given field is initialized within a constexpr constructor.
1765 ///
1766 /// \param Dcl The constexpr constructor being checked.
1767 /// \param Field The field being checked. This may be a member of an anonymous
1768 ///        struct or union nested within the class being checked.
1769 /// \param Inits All declarations, including anonymous struct/union members and
1770 ///        indirect members, for which any initialization was provided.
1771 /// \param Diagnosed Set to true if an error is produced.
1772 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1773                                           const FunctionDecl *Dcl,
1774                                           FieldDecl *Field,
1775                                           llvm::SmallSet<Decl*, 16> &Inits,
1776                                           bool &Diagnosed) {
1777   if (Field->isInvalidDecl())
1778     return;
1779 
1780   if (Field->isUnnamedBitfield())
1781     return;
1782 
1783   // Anonymous unions with no variant members and empty anonymous structs do not
1784   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1785   // indirect fields don't need initializing.
1786   if (Field->isAnonymousStructOrUnion() &&
1787       (Field->getType()->isUnionType()
1788            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1789            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1790     return;
1791 
1792   if (!Inits.count(Field)) {
1793     if (!Diagnosed) {
1794       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1795       Diagnosed = true;
1796     }
1797     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1798   } else if (Field->isAnonymousStructOrUnion()) {
1799     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1800     for (auto *I : RD->fields())
1801       // If an anonymous union contains an anonymous struct of which any member
1802       // is initialized, all members must be initialized.
1803       if (!RD->isUnion() || Inits.count(I))
1804         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1805   }
1806 }
1807 
1808 /// Check the provided statement is allowed in a constexpr function
1809 /// definition.
1810 static bool
1811 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1812                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1813                            SourceLocation &Cxx1yLoc) {
1814   // - its function-body shall be [...] a compound-statement that contains only
1815   switch (S->getStmtClass()) {
1816   case Stmt::NullStmtClass:
1817     //   - null statements,
1818     return true;
1819 
1820   case Stmt::DeclStmtClass:
1821     //   - static_assert-declarations
1822     //   - using-declarations,
1823     //   - using-directives,
1824     //   - typedef declarations and alias-declarations that do not define
1825     //     classes or enumerations,
1826     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1827       return false;
1828     return true;
1829 
1830   case Stmt::ReturnStmtClass:
1831     //   - and exactly one return statement;
1832     if (isa<CXXConstructorDecl>(Dcl)) {
1833       // C++1y allows return statements in constexpr constructors.
1834       if (!Cxx1yLoc.isValid())
1835         Cxx1yLoc = S->getLocStart();
1836       return true;
1837     }
1838 
1839     ReturnStmts.push_back(S->getLocStart());
1840     return true;
1841 
1842   case Stmt::CompoundStmtClass: {
1843     // C++1y allows compound-statements.
1844     if (!Cxx1yLoc.isValid())
1845       Cxx1yLoc = S->getLocStart();
1846 
1847     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1848     for (auto *BodyIt : CompStmt->body()) {
1849       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1850                                       Cxx1yLoc))
1851         return false;
1852     }
1853     return true;
1854   }
1855 
1856   case Stmt::AttributedStmtClass:
1857     if (!Cxx1yLoc.isValid())
1858       Cxx1yLoc = S->getLocStart();
1859     return true;
1860 
1861   case Stmt::IfStmtClass: {
1862     // C++1y allows if-statements.
1863     if (!Cxx1yLoc.isValid())
1864       Cxx1yLoc = S->getLocStart();
1865 
1866     IfStmt *If = cast<IfStmt>(S);
1867     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1868                                     Cxx1yLoc))
1869       return false;
1870     if (If->getElse() &&
1871         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1872                                     Cxx1yLoc))
1873       return false;
1874     return true;
1875   }
1876 
1877   case Stmt::WhileStmtClass:
1878   case Stmt::DoStmtClass:
1879   case Stmt::ForStmtClass:
1880   case Stmt::CXXForRangeStmtClass:
1881   case Stmt::ContinueStmtClass:
1882     // C++1y allows all of these. We don't allow them as extensions in C++11,
1883     // because they don't make sense without variable mutation.
1884     if (!SemaRef.getLangOpts().CPlusPlus14)
1885       break;
1886     if (!Cxx1yLoc.isValid())
1887       Cxx1yLoc = S->getLocStart();
1888     for (Stmt *SubStmt : S->children())
1889       if (SubStmt &&
1890           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1891                                       Cxx1yLoc))
1892         return false;
1893     return true;
1894 
1895   case Stmt::SwitchStmtClass:
1896   case Stmt::CaseStmtClass:
1897   case Stmt::DefaultStmtClass:
1898   case Stmt::BreakStmtClass:
1899     // C++1y allows switch-statements, and since they don't need variable
1900     // mutation, we can reasonably allow them in C++11 as an extension.
1901     if (!Cxx1yLoc.isValid())
1902       Cxx1yLoc = S->getLocStart();
1903     for (Stmt *SubStmt : S->children())
1904       if (SubStmt &&
1905           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1906                                       Cxx1yLoc))
1907         return false;
1908     return true;
1909 
1910   default:
1911     if (!isa<Expr>(S))
1912       break;
1913 
1914     // C++1y allows expression-statements.
1915     if (!Cxx1yLoc.isValid())
1916       Cxx1yLoc = S->getLocStart();
1917     return true;
1918   }
1919 
1920   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1921     << isa<CXXConstructorDecl>(Dcl);
1922   return false;
1923 }
1924 
1925 /// Check the body for the given constexpr function declaration only contains
1926 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1927 ///
1928 /// \return true if the body is OK, false if we have diagnosed a problem.
1929 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1930   if (isa<CXXTryStmt>(Body)) {
1931     // C++11 [dcl.constexpr]p3:
1932     //  The definition of a constexpr function shall satisfy the following
1933     //  constraints: [...]
1934     // - its function-body shall be = delete, = default, or a
1935     //   compound-statement
1936     //
1937     // C++11 [dcl.constexpr]p4:
1938     //  In the definition of a constexpr constructor, [...]
1939     // - its function-body shall not be a function-try-block;
1940     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1941       << isa<CXXConstructorDecl>(Dcl);
1942     return false;
1943   }
1944 
1945   SmallVector<SourceLocation, 4> ReturnStmts;
1946 
1947   // - its function-body shall be [...] a compound-statement that contains only
1948   //   [... list of cases ...]
1949   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1950   SourceLocation Cxx1yLoc;
1951   for (auto *BodyIt : CompBody->body()) {
1952     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1953       return false;
1954   }
1955 
1956   if (Cxx1yLoc.isValid())
1957     Diag(Cxx1yLoc,
1958          getLangOpts().CPlusPlus14
1959            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1960            : diag::ext_constexpr_body_invalid_stmt)
1961       << isa<CXXConstructorDecl>(Dcl);
1962 
1963   if (const CXXConstructorDecl *Constructor
1964         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1965     const CXXRecordDecl *RD = Constructor->getParent();
1966     // DR1359:
1967     // - every non-variant non-static data member and base class sub-object
1968     //   shall be initialized;
1969     // DR1460:
1970     // - if the class is a union having variant members, exactly one of them
1971     //   shall be initialized;
1972     if (RD->isUnion()) {
1973       if (Constructor->getNumCtorInitializers() == 0 &&
1974           RD->hasVariantMembers()) {
1975         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1976         return false;
1977       }
1978     } else if (!Constructor->isDependentContext() &&
1979                !Constructor->isDelegatingConstructor()) {
1980       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1981 
1982       // Skip detailed checking if we have enough initializers, and we would
1983       // allow at most one initializer per member.
1984       bool AnyAnonStructUnionMembers = false;
1985       unsigned Fields = 0;
1986       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1987            E = RD->field_end(); I != E; ++I, ++Fields) {
1988         if (I->isAnonymousStructOrUnion()) {
1989           AnyAnonStructUnionMembers = true;
1990           break;
1991         }
1992       }
1993       // DR1460:
1994       // - if the class is a union-like class, but is not a union, for each of
1995       //   its anonymous union members having variant members, exactly one of
1996       //   them shall be initialized;
1997       if (AnyAnonStructUnionMembers ||
1998           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1999         // Check initialization of non-static data members. Base classes are
2000         // always initialized so do not need to be checked. Dependent bases
2001         // might not have initializers in the member initializer list.
2002         llvm::SmallSet<Decl*, 16> Inits;
2003         for (const auto *I: Constructor->inits()) {
2004           if (FieldDecl *FD = I->getMember())
2005             Inits.insert(FD);
2006           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2007             Inits.insert(ID->chain_begin(), ID->chain_end());
2008         }
2009 
2010         bool Diagnosed = false;
2011         for (auto *I : RD->fields())
2012           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2013         if (Diagnosed)
2014           return false;
2015       }
2016     }
2017   } else {
2018     if (ReturnStmts.empty()) {
2019       // C++1y doesn't require constexpr functions to contain a 'return'
2020       // statement. We still do, unless the return type might be void, because
2021       // otherwise if there's no return statement, the function cannot
2022       // be used in a core constant expression.
2023       bool OK = getLangOpts().CPlusPlus14 &&
2024                 (Dcl->getReturnType()->isVoidType() ||
2025                  Dcl->getReturnType()->isDependentType());
2026       Diag(Dcl->getLocation(),
2027            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2028               : diag::err_constexpr_body_no_return);
2029       if (!OK)
2030         return false;
2031     } else if (ReturnStmts.size() > 1) {
2032       Diag(ReturnStmts.back(),
2033            getLangOpts().CPlusPlus14
2034              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2035              : diag::ext_constexpr_body_multiple_return);
2036       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2037         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2038     }
2039   }
2040 
2041   // C++11 [dcl.constexpr]p5:
2042   //   if no function argument values exist such that the function invocation
2043   //   substitution would produce a constant expression, the program is
2044   //   ill-formed; no diagnostic required.
2045   // C++11 [dcl.constexpr]p3:
2046   //   - every constructor call and implicit conversion used in initializing the
2047   //     return value shall be one of those allowed in a constant expression.
2048   // C++11 [dcl.constexpr]p4:
2049   //   - every constructor involved in initializing non-static data members and
2050   //     base class sub-objects shall be a constexpr constructor.
2051   SmallVector<PartialDiagnosticAt, 8> Diags;
2052   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2053     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2054       << isa<CXXConstructorDecl>(Dcl);
2055     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2056       Diag(Diags[I].first, Diags[I].second);
2057     // Don't return false here: we allow this for compatibility in
2058     // system headers.
2059   }
2060 
2061   return true;
2062 }
2063 
2064 /// isCurrentClassName - Determine whether the identifier II is the
2065 /// name of the class type currently being defined. In the case of
2066 /// nested classes, this will only return true if II is the name of
2067 /// the innermost class.
2068 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2069                               const CXXScopeSpec *SS) {
2070   assert(getLangOpts().CPlusPlus && "No class names in C!");
2071 
2072   CXXRecordDecl *CurDecl;
2073   if (SS && SS->isSet() && !SS->isInvalid()) {
2074     DeclContext *DC = computeDeclContext(*SS, true);
2075     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2076   } else
2077     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2078 
2079   if (CurDecl && CurDecl->getIdentifier())
2080     return &II == CurDecl->getIdentifier();
2081   return false;
2082 }
2083 
2084 /// \brief Determine whether the identifier II is a typo for the name of
2085 /// the class type currently being defined. If so, update it to the identifier
2086 /// that should have been used.
2087 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2088   assert(getLangOpts().CPlusPlus && "No class names in C!");
2089 
2090   if (!getLangOpts().SpellChecking)
2091     return false;
2092 
2093   CXXRecordDecl *CurDecl;
2094   if (SS && SS->isSet() && !SS->isInvalid()) {
2095     DeclContext *DC = computeDeclContext(*SS, true);
2096     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2097   } else
2098     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2099 
2100   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2101       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2102           < II->getLength()) {
2103     II = CurDecl->getIdentifier();
2104     return true;
2105   }
2106 
2107   return false;
2108 }
2109 
2110 /// \brief Determine whether the given class is a base class of the given
2111 /// class, including looking at dependent bases.
2112 static bool findCircularInheritance(const CXXRecordDecl *Class,
2113                                     const CXXRecordDecl *Current) {
2114   SmallVector<const CXXRecordDecl*, 8> Queue;
2115 
2116   Class = Class->getCanonicalDecl();
2117   while (true) {
2118     for (const auto &I : Current->bases()) {
2119       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2120       if (!Base)
2121         continue;
2122 
2123       Base = Base->getDefinition();
2124       if (!Base)
2125         continue;
2126 
2127       if (Base->getCanonicalDecl() == Class)
2128         return true;
2129 
2130       Queue.push_back(Base);
2131     }
2132 
2133     if (Queue.empty())
2134       return false;
2135 
2136     Current = Queue.pop_back_val();
2137   }
2138 
2139   return false;
2140 }
2141 
2142 /// \brief Check the validity of a C++ base class specifier.
2143 ///
2144 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2145 /// and returns NULL otherwise.
2146 CXXBaseSpecifier *
2147 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2148                          SourceRange SpecifierRange,
2149                          bool Virtual, AccessSpecifier Access,
2150                          TypeSourceInfo *TInfo,
2151                          SourceLocation EllipsisLoc) {
2152   QualType BaseType = TInfo->getType();
2153 
2154   // C++ [class.union]p1:
2155   //   A union shall not have base classes.
2156   if (Class->isUnion()) {
2157     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2158       << SpecifierRange;
2159     return nullptr;
2160   }
2161 
2162   if (EllipsisLoc.isValid() &&
2163       !TInfo->getType()->containsUnexpandedParameterPack()) {
2164     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2165       << TInfo->getTypeLoc().getSourceRange();
2166     EllipsisLoc = SourceLocation();
2167   }
2168 
2169   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2170 
2171   if (BaseType->isDependentType()) {
2172     // Make sure that we don't have circular inheritance among our dependent
2173     // bases. For non-dependent bases, the check for completeness below handles
2174     // this.
2175     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2176       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2177           ((BaseDecl = BaseDecl->getDefinition()) &&
2178            findCircularInheritance(Class, BaseDecl))) {
2179         Diag(BaseLoc, diag::err_circular_inheritance)
2180           << BaseType << Context.getTypeDeclType(Class);
2181 
2182         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2183           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2184             << BaseType;
2185 
2186         return nullptr;
2187       }
2188     }
2189 
2190     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2191                                           Class->getTagKind() == TTK_Class,
2192                                           Access, TInfo, EllipsisLoc);
2193   }
2194 
2195   // Base specifiers must be record types.
2196   if (!BaseType->isRecordType()) {
2197     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2198     return nullptr;
2199   }
2200 
2201   // C++ [class.union]p1:
2202   //   A union shall not be used as a base class.
2203   if (BaseType->isUnionType()) {
2204     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2205     return nullptr;
2206   }
2207 
2208   // For the MS ABI, propagate DLL attributes to base class templates.
2209   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2210     if (Attr *ClassAttr = getDLLAttr(Class)) {
2211       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2212               BaseType->getAsCXXRecordDecl())) {
2213         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2214                                             BaseLoc);
2215       }
2216     }
2217   }
2218 
2219   // C++ [class.derived]p2:
2220   //   The class-name in a base-specifier shall not be an incompletely
2221   //   defined class.
2222   if (RequireCompleteType(BaseLoc, BaseType,
2223                           diag::err_incomplete_base_class, SpecifierRange)) {
2224     Class->setInvalidDecl();
2225     return nullptr;
2226   }
2227 
2228   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2229   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2230   assert(BaseDecl && "Record type has no declaration");
2231   BaseDecl = BaseDecl->getDefinition();
2232   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2233   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2234   assert(CXXBaseDecl && "Base type is not a C++ type");
2235 
2236   // A class which contains a flexible array member is not suitable for use as a
2237   // base class:
2238   //   - If the layout determines that a base comes before another base,
2239   //     the flexible array member would index into the subsequent base.
2240   //   - If the layout determines that base comes before the derived class,
2241   //     the flexible array member would index into the derived class.
2242   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2243     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2244       << CXXBaseDecl->getDeclName();
2245     return nullptr;
2246   }
2247 
2248   // C++ [class]p3:
2249   //   If a class is marked final and it appears as a base-type-specifier in
2250   //   base-clause, the program is ill-formed.
2251   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2252     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2253       << CXXBaseDecl->getDeclName()
2254       << FA->isSpelledAsSealed();
2255     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2256         << CXXBaseDecl->getDeclName() << FA->getRange();
2257     return nullptr;
2258   }
2259 
2260   if (BaseDecl->isInvalidDecl())
2261     Class->setInvalidDecl();
2262 
2263   // Create the base specifier.
2264   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2265                                         Class->getTagKind() == TTK_Class,
2266                                         Access, TInfo, EllipsisLoc);
2267 }
2268 
2269 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2270 /// one entry in the base class list of a class specifier, for
2271 /// example:
2272 ///    class foo : public bar, virtual private baz {
2273 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2274 BaseResult
2275 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2276                          ParsedAttributes &Attributes,
2277                          bool Virtual, AccessSpecifier Access,
2278                          ParsedType basetype, SourceLocation BaseLoc,
2279                          SourceLocation EllipsisLoc) {
2280   if (!classdecl)
2281     return true;
2282 
2283   AdjustDeclIfTemplate(classdecl);
2284   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2285   if (!Class)
2286     return true;
2287 
2288   // We haven't yet attached the base specifiers.
2289   Class->setIsParsingBaseSpecifiers();
2290 
2291   // We do not support any C++11 attributes on base-specifiers yet.
2292   // Diagnose any attributes we see.
2293   if (!Attributes.empty()) {
2294     for (AttributeList *Attr = Attributes.getList(); Attr;
2295          Attr = Attr->getNext()) {
2296       if (Attr->isInvalid() ||
2297           Attr->getKind() == AttributeList::IgnoredAttribute)
2298         continue;
2299       Diag(Attr->getLoc(),
2300            Attr->getKind() == AttributeList::UnknownAttribute
2301              ? diag::warn_unknown_attribute_ignored
2302              : diag::err_base_specifier_attribute)
2303         << Attr->getName();
2304     }
2305   }
2306 
2307   TypeSourceInfo *TInfo = nullptr;
2308   GetTypeFromParser(basetype, &TInfo);
2309 
2310   if (EllipsisLoc.isInvalid() &&
2311       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2312                                       UPPC_BaseType))
2313     return true;
2314 
2315   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2316                                                       Virtual, Access, TInfo,
2317                                                       EllipsisLoc))
2318     return BaseSpec;
2319   else
2320     Class->setInvalidDecl();
2321 
2322   return true;
2323 }
2324 
2325 /// Use small set to collect indirect bases.  As this is only used
2326 /// locally, there's no need to abstract the small size parameter.
2327 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2328 
2329 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2330 static void
2331 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2332                   const QualType &Type)
2333 {
2334   // Even though the incoming type is a base, it might not be
2335   // a class -- it could be a template parm, for instance.
2336   if (auto Rec = Type->getAs<RecordType>()) {
2337     auto Decl = Rec->getAsCXXRecordDecl();
2338 
2339     // Iterate over its bases.
2340     for (const auto &BaseSpec : Decl->bases()) {
2341       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2342         .getUnqualifiedType();
2343       if (Set.insert(Base).second)
2344         // If we've not already seen it, recurse.
2345         NoteIndirectBases(Context, Set, Base);
2346     }
2347   }
2348 }
2349 
2350 /// \brief Performs the actual work of attaching the given base class
2351 /// specifiers to a C++ class.
2352 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2353                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2354  if (Bases.empty())
2355     return false;
2356 
2357   // Used to keep track of which base types we have already seen, so
2358   // that we can properly diagnose redundant direct base types. Note
2359   // that the key is always the unqualified canonical type of the base
2360   // class.
2361   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2362 
2363   // Used to track indirect bases so we can see if a direct base is
2364   // ambiguous.
2365   IndirectBaseSet IndirectBaseTypes;
2366 
2367   // Copy non-redundant base specifiers into permanent storage.
2368   unsigned NumGoodBases = 0;
2369   bool Invalid = false;
2370   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2371     QualType NewBaseType
2372       = Context.getCanonicalType(Bases[idx]->getType());
2373     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2374 
2375     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2376     if (KnownBase) {
2377       // C++ [class.mi]p3:
2378       //   A class shall not be specified as a direct base class of a
2379       //   derived class more than once.
2380       Diag(Bases[idx]->getLocStart(),
2381            diag::err_duplicate_base_class)
2382         << KnownBase->getType()
2383         << Bases[idx]->getSourceRange();
2384 
2385       // Delete the duplicate base class specifier; we're going to
2386       // overwrite its pointer later.
2387       Context.Deallocate(Bases[idx]);
2388 
2389       Invalid = true;
2390     } else {
2391       // Okay, add this new base class.
2392       KnownBase = Bases[idx];
2393       Bases[NumGoodBases++] = Bases[idx];
2394 
2395       // Note this base's direct & indirect bases, if there could be ambiguity.
2396       if (Bases.size() > 1)
2397         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2398 
2399       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2400         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2401         if (Class->isInterface() &&
2402               (!RD->isInterfaceLike() ||
2403                KnownBase->getAccessSpecifier() != AS_public)) {
2404           // The Microsoft extension __interface does not permit bases that
2405           // are not themselves public interfaces.
2406           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2407             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2408             << RD->getSourceRange();
2409           Invalid = true;
2410         }
2411         if (RD->hasAttr<WeakAttr>())
2412           Class->addAttr(WeakAttr::CreateImplicit(Context));
2413       }
2414     }
2415   }
2416 
2417   // Attach the remaining base class specifiers to the derived class.
2418   Class->setBases(Bases.data(), NumGoodBases);
2419 
2420   // Check that the only base classes that are duplicate are virtual.
2421   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2422     // Check whether this direct base is inaccessible due to ambiguity.
2423     QualType BaseType = Bases[idx]->getType();
2424 
2425     // Skip all dependent types in templates being used as base specifiers.
2426     // Checks below assume that the base specifier is a CXXRecord.
2427     if (BaseType->isDependentType())
2428       continue;
2429 
2430     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2431       .getUnqualifiedType();
2432 
2433     if (IndirectBaseTypes.count(CanonicalBase)) {
2434       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2435                          /*DetectVirtual=*/true);
2436       bool found
2437         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2438       assert(found);
2439       (void)found;
2440 
2441       if (Paths.isAmbiguous(CanonicalBase))
2442         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2443           << BaseType << getAmbiguousPathsDisplayString(Paths)
2444           << Bases[idx]->getSourceRange();
2445       else
2446         assert(Bases[idx]->isVirtual());
2447     }
2448 
2449     // Delete the base class specifier, since its data has been copied
2450     // into the CXXRecordDecl.
2451     Context.Deallocate(Bases[idx]);
2452   }
2453 
2454   return Invalid;
2455 }
2456 
2457 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2458 /// class, after checking whether there are any duplicate base
2459 /// classes.
2460 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2461                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2462   if (!ClassDecl || Bases.empty())
2463     return;
2464 
2465   AdjustDeclIfTemplate(ClassDecl);
2466   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2467 }
2468 
2469 /// \brief Determine whether the type \p Derived is a C++ class that is
2470 /// derived from the type \p Base.
2471 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2472   if (!getLangOpts().CPlusPlus)
2473     return false;
2474 
2475   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2476   if (!DerivedRD)
2477     return false;
2478 
2479   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2480   if (!BaseRD)
2481     return false;
2482 
2483   // If either the base or the derived type is invalid, don't try to
2484   // check whether one is derived from the other.
2485   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2486     return false;
2487 
2488   // FIXME: In a modules build, do we need the entire path to be visible for us
2489   // to be able to use the inheritance relationship?
2490   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2491     return false;
2492 
2493   return DerivedRD->isDerivedFrom(BaseRD);
2494 }
2495 
2496 /// \brief Determine whether the type \p Derived is a C++ class that is
2497 /// derived from the type \p Base.
2498 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2499                          CXXBasePaths &Paths) {
2500   if (!getLangOpts().CPlusPlus)
2501     return false;
2502 
2503   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2504   if (!DerivedRD)
2505     return false;
2506 
2507   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2508   if (!BaseRD)
2509     return false;
2510 
2511   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2512     return false;
2513 
2514   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2515 }
2516 
2517 static void BuildBasePathArray(const CXXBasePath &Path,
2518                                CXXCastPath &BasePathArray) {
2519   // We first go backward and check if we have a virtual base.
2520   // FIXME: It would be better if CXXBasePath had the base specifier for
2521   // the nearest virtual base.
2522   unsigned Start = 0;
2523   for (unsigned I = Path.size(); I != 0; --I) {
2524     if (Path[I - 1].Base->isVirtual()) {
2525       Start = I - 1;
2526       break;
2527     }
2528   }
2529 
2530   // Now add all bases.
2531   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2532     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2533 }
2534 
2535 
2536 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2537                               CXXCastPath &BasePathArray) {
2538   assert(BasePathArray.empty() && "Base path array must be empty!");
2539   assert(Paths.isRecordingPaths() && "Must record paths!");
2540   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2541 }
2542 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2543 /// conversion (where Derived and Base are class types) is
2544 /// well-formed, meaning that the conversion is unambiguous (and
2545 /// that all of the base classes are accessible). Returns true
2546 /// and emits a diagnostic if the code is ill-formed, returns false
2547 /// otherwise. Loc is the location where this routine should point to
2548 /// if there is an error, and Range is the source range to highlight
2549 /// if there is an error.
2550 ///
2551 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2552 /// diagnostic for the respective type of error will be suppressed, but the
2553 /// check for ill-formed code will still be performed.
2554 bool
2555 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2556                                    unsigned InaccessibleBaseID,
2557                                    unsigned AmbigiousBaseConvID,
2558                                    SourceLocation Loc, SourceRange Range,
2559                                    DeclarationName Name,
2560                                    CXXCastPath *BasePath,
2561                                    bool IgnoreAccess) {
2562   // First, determine whether the path from Derived to Base is
2563   // ambiguous. This is slightly more expensive than checking whether
2564   // the Derived to Base conversion exists, because here we need to
2565   // explore multiple paths to determine if there is an ambiguity.
2566   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2567                      /*DetectVirtual=*/false);
2568   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2569   if (!DerivationOkay)
2570     return true;
2571 
2572   const CXXBasePath *Path = nullptr;
2573   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2574     Path = &Paths.front();
2575 
2576   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2577   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2578   // user to access such bases.
2579   if (!Path && getLangOpts().MSVCCompat) {
2580     for (const CXXBasePath &PossiblePath : Paths) {
2581       if (PossiblePath.size() == 1) {
2582         Path = &PossiblePath;
2583         if (AmbigiousBaseConvID)
2584           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2585               << Base << Derived << Range;
2586         break;
2587       }
2588     }
2589   }
2590 
2591   if (Path) {
2592     if (!IgnoreAccess) {
2593       // Check that the base class can be accessed.
2594       switch (
2595           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2596       case AR_inaccessible:
2597         return true;
2598       case AR_accessible:
2599       case AR_dependent:
2600       case AR_delayed:
2601         break;
2602       }
2603     }
2604 
2605     // Build a base path if necessary.
2606     if (BasePath)
2607       ::BuildBasePathArray(*Path, *BasePath);
2608     return false;
2609   }
2610 
2611   if (AmbigiousBaseConvID) {
2612     // We know that the derived-to-base conversion is ambiguous, and
2613     // we're going to produce a diagnostic. Perform the derived-to-base
2614     // search just one more time to compute all of the possible paths so
2615     // that we can print them out. This is more expensive than any of
2616     // the previous derived-to-base checks we've done, but at this point
2617     // performance isn't as much of an issue.
2618     Paths.clear();
2619     Paths.setRecordingPaths(true);
2620     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2621     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2622     (void)StillOkay;
2623 
2624     // Build up a textual representation of the ambiguous paths, e.g.,
2625     // D -> B -> A, that will be used to illustrate the ambiguous
2626     // conversions in the diagnostic. We only print one of the paths
2627     // to each base class subobject.
2628     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2629 
2630     Diag(Loc, AmbigiousBaseConvID)
2631     << Derived << Base << PathDisplayStr << Range << Name;
2632   }
2633   return true;
2634 }
2635 
2636 bool
2637 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2638                                    SourceLocation Loc, SourceRange Range,
2639                                    CXXCastPath *BasePath,
2640                                    bool IgnoreAccess) {
2641   return CheckDerivedToBaseConversion(
2642       Derived, Base, diag::err_upcast_to_inaccessible_base,
2643       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2644       BasePath, IgnoreAccess);
2645 }
2646 
2647 
2648 /// @brief Builds a string representing ambiguous paths from a
2649 /// specific derived class to different subobjects of the same base
2650 /// class.
2651 ///
2652 /// This function builds a string that can be used in error messages
2653 /// to show the different paths that one can take through the
2654 /// inheritance hierarchy to go from the derived class to different
2655 /// subobjects of a base class. The result looks something like this:
2656 /// @code
2657 /// struct D -> struct B -> struct A
2658 /// struct D -> struct C -> struct A
2659 /// @endcode
2660 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2661   std::string PathDisplayStr;
2662   std::set<unsigned> DisplayedPaths;
2663   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2664        Path != Paths.end(); ++Path) {
2665     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2666       // We haven't displayed a path to this particular base
2667       // class subobject yet.
2668       PathDisplayStr += "\n    ";
2669       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2670       for (CXXBasePath::const_iterator Element = Path->begin();
2671            Element != Path->end(); ++Element)
2672         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2673     }
2674   }
2675 
2676   return PathDisplayStr;
2677 }
2678 
2679 //===----------------------------------------------------------------------===//
2680 // C++ class member Handling
2681 //===----------------------------------------------------------------------===//
2682 
2683 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2684 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2685                                 SourceLocation ASLoc,
2686                                 SourceLocation ColonLoc,
2687                                 AttributeList *Attrs) {
2688   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2689   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2690                                                   ASLoc, ColonLoc);
2691   CurContext->addHiddenDecl(ASDecl);
2692   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2693 }
2694 
2695 /// CheckOverrideControl - Check C++11 override control semantics.
2696 void Sema::CheckOverrideControl(NamedDecl *D) {
2697   if (D->isInvalidDecl())
2698     return;
2699 
2700   // We only care about "override" and "final" declarations.
2701   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2702     return;
2703 
2704   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2705 
2706   // We can't check dependent instance methods.
2707   if (MD && MD->isInstance() &&
2708       (MD->getParent()->hasAnyDependentBases() ||
2709        MD->getType()->isDependentType()))
2710     return;
2711 
2712   if (MD && !MD->isVirtual()) {
2713     // If we have a non-virtual method, check if if hides a virtual method.
2714     // (In that case, it's most likely the method has the wrong type.)
2715     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2716     FindHiddenVirtualMethods(MD, OverloadedMethods);
2717 
2718     if (!OverloadedMethods.empty()) {
2719       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2720         Diag(OA->getLocation(),
2721              diag::override_keyword_hides_virtual_member_function)
2722           << "override" << (OverloadedMethods.size() > 1);
2723       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2724         Diag(FA->getLocation(),
2725              diag::override_keyword_hides_virtual_member_function)
2726           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2727           << (OverloadedMethods.size() > 1);
2728       }
2729       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2730       MD->setInvalidDecl();
2731       return;
2732     }
2733     // Fall through into the general case diagnostic.
2734     // FIXME: We might want to attempt typo correction here.
2735   }
2736 
2737   if (!MD || !MD->isVirtual()) {
2738     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2739       Diag(OA->getLocation(),
2740            diag::override_keyword_only_allowed_on_virtual_member_functions)
2741         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2742       D->dropAttr<OverrideAttr>();
2743     }
2744     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2745       Diag(FA->getLocation(),
2746            diag::override_keyword_only_allowed_on_virtual_member_functions)
2747         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2748         << FixItHint::CreateRemoval(FA->getLocation());
2749       D->dropAttr<FinalAttr>();
2750     }
2751     return;
2752   }
2753 
2754   // C++11 [class.virtual]p5:
2755   //   If a function is marked with the virt-specifier override and
2756   //   does not override a member function of a base class, the program is
2757   //   ill-formed.
2758   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2759   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2760     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2761       << MD->getDeclName();
2762 }
2763 
2764 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2765   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2766     return;
2767   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2768   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2769     return;
2770 
2771   SourceLocation Loc = MD->getLocation();
2772   SourceLocation SpellingLoc = Loc;
2773   if (getSourceManager().isMacroArgExpansion(Loc))
2774     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2775   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2776   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2777       return;
2778 
2779   if (MD->size_overridden_methods() > 0) {
2780     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2781                           ? diag::warn_destructor_marked_not_override_overriding
2782                           : diag::warn_function_marked_not_override_overriding;
2783     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2784     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2785     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2786   }
2787 }
2788 
2789 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2790 /// function overrides a virtual member function marked 'final', according to
2791 /// C++11 [class.virtual]p4.
2792 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2793                                                   const CXXMethodDecl *Old) {
2794   FinalAttr *FA = Old->getAttr<FinalAttr>();
2795   if (!FA)
2796     return false;
2797 
2798   Diag(New->getLocation(), diag::err_final_function_overridden)
2799     << New->getDeclName()
2800     << FA->isSpelledAsSealed();
2801   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2802   return true;
2803 }
2804 
2805 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2806   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2807   // FIXME: Destruction of ObjC lifetime types has side-effects.
2808   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2809     return !RD->isCompleteDefinition() ||
2810            !RD->hasTrivialDefaultConstructor() ||
2811            !RD->hasTrivialDestructor();
2812   return false;
2813 }
2814 
2815 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2816   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2817     if (it->isDeclspecPropertyAttribute())
2818       return it;
2819   return nullptr;
2820 }
2821 
2822 // Check if there is a field shadowing.
2823 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2824                                       DeclarationName FieldName,
2825                                       const CXXRecordDecl *RD) {
2826   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2827     return;
2828 
2829   // To record a shadowed field in a base
2830   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2831   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2832                            CXXBasePath &Path) {
2833     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2834     // Record an ambiguous path directly
2835     if (Bases.find(Base) != Bases.end())
2836       return true;
2837     for (const auto Field : Base->lookup(FieldName)) {
2838       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2839           Field->getAccess() != AS_private) {
2840         assert(Field->getAccess() != AS_none);
2841         assert(Bases.find(Base) == Bases.end());
2842         Bases[Base] = Field;
2843         return true;
2844       }
2845     }
2846     return false;
2847   };
2848 
2849   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2850                      /*DetectVirtual=*/true);
2851   if (!RD->lookupInBases(FieldShadowed, Paths))
2852     return;
2853 
2854   for (const auto &P : Paths) {
2855     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2856     auto It = Bases.find(Base);
2857     // Skip duplicated bases
2858     if (It == Bases.end())
2859       continue;
2860     auto BaseField = It->second;
2861     assert(BaseField->getAccess() != AS_private);
2862     if (AS_none !=
2863         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2864       Diag(Loc, diag::warn_shadow_field)
2865         << FieldName.getAsString() << RD->getName() << Base->getName();
2866       Diag(BaseField->getLocation(), diag::note_shadow_field);
2867       Bases.erase(It);
2868     }
2869   }
2870 }
2871 
2872 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2873 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2874 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2875 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2876 /// present (but parsing it has been deferred).
2877 NamedDecl *
2878 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2879                                MultiTemplateParamsArg TemplateParameterLists,
2880                                Expr *BW, const VirtSpecifiers &VS,
2881                                InClassInitStyle InitStyle) {
2882   const DeclSpec &DS = D.getDeclSpec();
2883   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2884   DeclarationName Name = NameInfo.getName();
2885   SourceLocation Loc = NameInfo.getLoc();
2886 
2887   // For anonymous bitfields, the location should point to the type.
2888   if (Loc.isInvalid())
2889     Loc = D.getLocStart();
2890 
2891   Expr *BitWidth = static_cast<Expr*>(BW);
2892 
2893   assert(isa<CXXRecordDecl>(CurContext));
2894   assert(!DS.isFriendSpecified());
2895 
2896   bool isFunc = D.isDeclarationOfFunction();
2897   AttributeList *MSPropertyAttr =
2898       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2899 
2900   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2901     // The Microsoft extension __interface only permits public member functions
2902     // and prohibits constructors, destructors, operators, non-public member
2903     // functions, static methods and data members.
2904     unsigned InvalidDecl;
2905     bool ShowDeclName = true;
2906     if (!isFunc &&
2907         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2908       InvalidDecl = 0;
2909     else if (!isFunc)
2910       InvalidDecl = 1;
2911     else if (AS != AS_public)
2912       InvalidDecl = 2;
2913     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2914       InvalidDecl = 3;
2915     else switch (Name.getNameKind()) {
2916       case DeclarationName::CXXConstructorName:
2917         InvalidDecl = 4;
2918         ShowDeclName = false;
2919         break;
2920 
2921       case DeclarationName::CXXDestructorName:
2922         InvalidDecl = 5;
2923         ShowDeclName = false;
2924         break;
2925 
2926       case DeclarationName::CXXOperatorName:
2927       case DeclarationName::CXXConversionFunctionName:
2928         InvalidDecl = 6;
2929         break;
2930 
2931       default:
2932         InvalidDecl = 0;
2933         break;
2934     }
2935 
2936     if (InvalidDecl) {
2937       if (ShowDeclName)
2938         Diag(Loc, diag::err_invalid_member_in_interface)
2939           << (InvalidDecl-1) << Name;
2940       else
2941         Diag(Loc, diag::err_invalid_member_in_interface)
2942           << (InvalidDecl-1) << "";
2943       return nullptr;
2944     }
2945   }
2946 
2947   // C++ 9.2p6: A member shall not be declared to have automatic storage
2948   // duration (auto, register) or with the extern storage-class-specifier.
2949   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2950   // data members and cannot be applied to names declared const or static,
2951   // and cannot be applied to reference members.
2952   switch (DS.getStorageClassSpec()) {
2953   case DeclSpec::SCS_unspecified:
2954   case DeclSpec::SCS_typedef:
2955   case DeclSpec::SCS_static:
2956     break;
2957   case DeclSpec::SCS_mutable:
2958     if (isFunc) {
2959       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2960 
2961       // FIXME: It would be nicer if the keyword was ignored only for this
2962       // declarator. Otherwise we could get follow-up errors.
2963       D.getMutableDeclSpec().ClearStorageClassSpecs();
2964     }
2965     break;
2966   default:
2967     Diag(DS.getStorageClassSpecLoc(),
2968          diag::err_storageclass_invalid_for_member);
2969     D.getMutableDeclSpec().ClearStorageClassSpecs();
2970     break;
2971   }
2972 
2973   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2974                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2975                       !isFunc);
2976 
2977   if (DS.isConstexprSpecified() && isInstField) {
2978     SemaDiagnosticBuilder B =
2979         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2980     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2981     if (InitStyle == ICIS_NoInit) {
2982       B << 0 << 0;
2983       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2984         B << FixItHint::CreateRemoval(ConstexprLoc);
2985       else {
2986         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2987         D.getMutableDeclSpec().ClearConstexprSpec();
2988         const char *PrevSpec;
2989         unsigned DiagID;
2990         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2991             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2992         (void)Failed;
2993         assert(!Failed && "Making a constexpr member const shouldn't fail");
2994       }
2995     } else {
2996       B << 1;
2997       const char *PrevSpec;
2998       unsigned DiagID;
2999       if (D.getMutableDeclSpec().SetStorageClassSpec(
3000           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3001           Context.getPrintingPolicy())) {
3002         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3003                "This is the only DeclSpec that should fail to be applied");
3004         B << 1;
3005       } else {
3006         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3007         isInstField = false;
3008       }
3009     }
3010   }
3011 
3012   NamedDecl *Member;
3013   if (isInstField) {
3014     CXXScopeSpec &SS = D.getCXXScopeSpec();
3015 
3016     // Data members must have identifiers for names.
3017     if (!Name.isIdentifier()) {
3018       Diag(Loc, diag::err_bad_variable_name)
3019         << Name;
3020       return nullptr;
3021     }
3022 
3023     IdentifierInfo *II = Name.getAsIdentifierInfo();
3024 
3025     // Member field could not be with "template" keyword.
3026     // So TemplateParameterLists should be empty in this case.
3027     if (TemplateParameterLists.size()) {
3028       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3029       if (TemplateParams->size()) {
3030         // There is no such thing as a member field template.
3031         Diag(D.getIdentifierLoc(), diag::err_template_member)
3032             << II
3033             << SourceRange(TemplateParams->getTemplateLoc(),
3034                 TemplateParams->getRAngleLoc());
3035       } else {
3036         // There is an extraneous 'template<>' for this member.
3037         Diag(TemplateParams->getTemplateLoc(),
3038             diag::err_template_member_noparams)
3039             << II
3040             << SourceRange(TemplateParams->getTemplateLoc(),
3041                 TemplateParams->getRAngleLoc());
3042       }
3043       return nullptr;
3044     }
3045 
3046     if (SS.isSet() && !SS.isInvalid()) {
3047       // The user provided a superfluous scope specifier inside a class
3048       // definition:
3049       //
3050       // class X {
3051       //   int X::member;
3052       // };
3053       if (DeclContext *DC = computeDeclContext(SS, false))
3054         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
3055       else
3056         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3057           << Name << SS.getRange();
3058 
3059       SS.clear();
3060     }
3061 
3062     if (MSPropertyAttr) {
3063       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3064                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3065       if (!Member)
3066         return nullptr;
3067       isInstField = false;
3068     } else {
3069       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3070                                 BitWidth, InitStyle, AS);
3071       if (!Member)
3072         return nullptr;
3073     }
3074 
3075     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3076   } else {
3077     Member = HandleDeclarator(S, D, TemplateParameterLists);
3078     if (!Member)
3079       return nullptr;
3080 
3081     // Non-instance-fields can't have a bitfield.
3082     if (BitWidth) {
3083       if (Member->isInvalidDecl()) {
3084         // don't emit another diagnostic.
3085       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3086         // C++ 9.6p3: A bit-field shall not be a static member.
3087         // "static member 'A' cannot be a bit-field"
3088         Diag(Loc, diag::err_static_not_bitfield)
3089           << Name << BitWidth->getSourceRange();
3090       } else if (isa<TypedefDecl>(Member)) {
3091         // "typedef member 'x' cannot be a bit-field"
3092         Diag(Loc, diag::err_typedef_not_bitfield)
3093           << Name << BitWidth->getSourceRange();
3094       } else {
3095         // A function typedef ("typedef int f(); f a;").
3096         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3097         Diag(Loc, diag::err_not_integral_type_bitfield)
3098           << Name << cast<ValueDecl>(Member)->getType()
3099           << BitWidth->getSourceRange();
3100       }
3101 
3102       BitWidth = nullptr;
3103       Member->setInvalidDecl();
3104     }
3105 
3106     Member->setAccess(AS);
3107 
3108     // If we have declared a member function template or static data member
3109     // template, set the access of the templated declaration as well.
3110     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3111       FunTmpl->getTemplatedDecl()->setAccess(AS);
3112     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3113       VarTmpl->getTemplatedDecl()->setAccess(AS);
3114   }
3115 
3116   if (VS.isOverrideSpecified())
3117     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3118   if (VS.isFinalSpecified())
3119     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3120                                             VS.isFinalSpelledSealed()));
3121 
3122   if (VS.getLastLocation().isValid()) {
3123     // Update the end location of a method that has a virt-specifiers.
3124     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3125       MD->setRangeEnd(VS.getLastLocation());
3126   }
3127 
3128   CheckOverrideControl(Member);
3129 
3130   assert((Name || isInstField) && "No identifier for non-field ?");
3131 
3132   if (isInstField) {
3133     FieldDecl *FD = cast<FieldDecl>(Member);
3134     FieldCollector->Add(FD);
3135 
3136     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3137       // Remember all explicit private FieldDecls that have a name, no side
3138       // effects and are not part of a dependent type declaration.
3139       if (!FD->isImplicit() && FD->getDeclName() &&
3140           FD->getAccess() == AS_private &&
3141           !FD->hasAttr<UnusedAttr>() &&
3142           !FD->getParent()->isDependentContext() &&
3143           !InitializationHasSideEffects(*FD))
3144         UnusedPrivateFields.insert(FD);
3145     }
3146   }
3147 
3148   return Member;
3149 }
3150 
3151 namespace {
3152   class UninitializedFieldVisitor
3153       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3154     Sema &S;
3155     // List of Decls to generate a warning on.  Also remove Decls that become
3156     // initialized.
3157     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3158     // List of base classes of the record.  Classes are removed after their
3159     // initializers.
3160     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3161     // Vector of decls to be removed from the Decl set prior to visiting the
3162     // nodes.  These Decls may have been initialized in the prior initializer.
3163     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3164     // If non-null, add a note to the warning pointing back to the constructor.
3165     const CXXConstructorDecl *Constructor;
3166     // Variables to hold state when processing an initializer list.  When
3167     // InitList is true, special case initialization of FieldDecls matching
3168     // InitListFieldDecl.
3169     bool InitList;
3170     FieldDecl *InitListFieldDecl;
3171     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3172 
3173   public:
3174     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3175     UninitializedFieldVisitor(Sema &S,
3176                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3177                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3178       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3179         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3180 
3181     // Returns true if the use of ME is not an uninitialized use.
3182     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3183                                          bool CheckReferenceOnly) {
3184       llvm::SmallVector<FieldDecl*, 4> Fields;
3185       bool ReferenceField = false;
3186       while (ME) {
3187         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3188         if (!FD)
3189           return false;
3190         Fields.push_back(FD);
3191         if (FD->getType()->isReferenceType())
3192           ReferenceField = true;
3193         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3194       }
3195 
3196       // Binding a reference to an unintialized field is not an
3197       // uninitialized use.
3198       if (CheckReferenceOnly && !ReferenceField)
3199         return true;
3200 
3201       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3202       // Discard the first field since it is the field decl that is being
3203       // initialized.
3204       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3205         UsedFieldIndex.push_back((*I)->getFieldIndex());
3206       }
3207 
3208       for (auto UsedIter = UsedFieldIndex.begin(),
3209                 UsedEnd = UsedFieldIndex.end(),
3210                 OrigIter = InitFieldIndex.begin(),
3211                 OrigEnd = InitFieldIndex.end();
3212            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3213         if (*UsedIter < *OrigIter)
3214           return true;
3215         if (*UsedIter > *OrigIter)
3216           break;
3217       }
3218 
3219       return false;
3220     }
3221 
3222     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3223                           bool AddressOf) {
3224       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3225         return;
3226 
3227       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3228       // or union.
3229       MemberExpr *FieldME = ME;
3230 
3231       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3232 
3233       Expr *Base = ME;
3234       while (MemberExpr *SubME =
3235                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3236 
3237         if (isa<VarDecl>(SubME->getMemberDecl()))
3238           return;
3239 
3240         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3241           if (!FD->isAnonymousStructOrUnion())
3242             FieldME = SubME;
3243 
3244         if (!FieldME->getType().isPODType(S.Context))
3245           AllPODFields = false;
3246 
3247         Base = SubME->getBase();
3248       }
3249 
3250       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3251         return;
3252 
3253       if (AddressOf && AllPODFields)
3254         return;
3255 
3256       ValueDecl* FoundVD = FieldME->getMemberDecl();
3257 
3258       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3259         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3260           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3261         }
3262 
3263         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3264           QualType T = BaseCast->getType();
3265           if (T->isPointerType() &&
3266               BaseClasses.count(T->getPointeeType())) {
3267             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3268                 << T->getPointeeType() << FoundVD;
3269           }
3270         }
3271       }
3272 
3273       if (!Decls.count(FoundVD))
3274         return;
3275 
3276       const bool IsReference = FoundVD->getType()->isReferenceType();
3277 
3278       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3279         // Special checking for initializer lists.
3280         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3281           return;
3282         }
3283       } else {
3284         // Prevent double warnings on use of unbounded references.
3285         if (CheckReferenceOnly && !IsReference)
3286           return;
3287       }
3288 
3289       unsigned diag = IsReference
3290           ? diag::warn_reference_field_is_uninit
3291           : diag::warn_field_is_uninit;
3292       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3293       if (Constructor)
3294         S.Diag(Constructor->getLocation(),
3295                diag::note_uninit_in_this_constructor)
3296           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3297 
3298     }
3299 
3300     void HandleValue(Expr *E, bool AddressOf) {
3301       E = E->IgnoreParens();
3302 
3303       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3304         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3305                          AddressOf /*AddressOf*/);
3306         return;
3307       }
3308 
3309       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3310         Visit(CO->getCond());
3311         HandleValue(CO->getTrueExpr(), AddressOf);
3312         HandleValue(CO->getFalseExpr(), AddressOf);
3313         return;
3314       }
3315 
3316       if (BinaryConditionalOperator *BCO =
3317               dyn_cast<BinaryConditionalOperator>(E)) {
3318         Visit(BCO->getCond());
3319         HandleValue(BCO->getFalseExpr(), AddressOf);
3320         return;
3321       }
3322 
3323       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3324         HandleValue(OVE->getSourceExpr(), AddressOf);
3325         return;
3326       }
3327 
3328       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3329         switch (BO->getOpcode()) {
3330         default:
3331           break;
3332         case(BO_PtrMemD):
3333         case(BO_PtrMemI):
3334           HandleValue(BO->getLHS(), AddressOf);
3335           Visit(BO->getRHS());
3336           return;
3337         case(BO_Comma):
3338           Visit(BO->getLHS());
3339           HandleValue(BO->getRHS(), AddressOf);
3340           return;
3341         }
3342       }
3343 
3344       Visit(E);
3345     }
3346 
3347     void CheckInitListExpr(InitListExpr *ILE) {
3348       InitFieldIndex.push_back(0);
3349       for (auto Child : ILE->children()) {
3350         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3351           CheckInitListExpr(SubList);
3352         } else {
3353           Visit(Child);
3354         }
3355         ++InitFieldIndex.back();
3356       }
3357       InitFieldIndex.pop_back();
3358     }
3359 
3360     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3361                           FieldDecl *Field, const Type *BaseClass) {
3362       // Remove Decls that may have been initialized in the previous
3363       // initializer.
3364       for (ValueDecl* VD : DeclsToRemove)
3365         Decls.erase(VD);
3366       DeclsToRemove.clear();
3367 
3368       Constructor = FieldConstructor;
3369       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3370 
3371       if (ILE && Field) {
3372         InitList = true;
3373         InitListFieldDecl = Field;
3374         InitFieldIndex.clear();
3375         CheckInitListExpr(ILE);
3376       } else {
3377         InitList = false;
3378         Visit(E);
3379       }
3380 
3381       if (Field)
3382         Decls.erase(Field);
3383       if (BaseClass)
3384         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3385     }
3386 
3387     void VisitMemberExpr(MemberExpr *ME) {
3388       // All uses of unbounded reference fields will warn.
3389       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3390     }
3391 
3392     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3393       if (E->getCastKind() == CK_LValueToRValue) {
3394         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3395         return;
3396       }
3397 
3398       Inherited::VisitImplicitCastExpr(E);
3399     }
3400 
3401     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3402       if (E->getConstructor()->isCopyConstructor()) {
3403         Expr *ArgExpr = E->getArg(0);
3404         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3405           if (ILE->getNumInits() == 1)
3406             ArgExpr = ILE->getInit(0);
3407         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3408           if (ICE->getCastKind() == CK_NoOp)
3409             ArgExpr = ICE->getSubExpr();
3410         HandleValue(ArgExpr, false /*AddressOf*/);
3411         return;
3412       }
3413       Inherited::VisitCXXConstructExpr(E);
3414     }
3415 
3416     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3417       Expr *Callee = E->getCallee();
3418       if (isa<MemberExpr>(Callee)) {
3419         HandleValue(Callee, false /*AddressOf*/);
3420         for (auto Arg : E->arguments())
3421           Visit(Arg);
3422         return;
3423       }
3424 
3425       Inherited::VisitCXXMemberCallExpr(E);
3426     }
3427 
3428     void VisitCallExpr(CallExpr *E) {
3429       // Treat std::move as a use.
3430       if (E->isCallToStdMove()) {
3431         HandleValue(E->getArg(0), /*AddressOf=*/false);
3432         return;
3433       }
3434 
3435       Inherited::VisitCallExpr(E);
3436     }
3437 
3438     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3439       Expr *Callee = E->getCallee();
3440 
3441       if (isa<UnresolvedLookupExpr>(Callee))
3442         return Inherited::VisitCXXOperatorCallExpr(E);
3443 
3444       Visit(Callee);
3445       for (auto Arg : E->arguments())
3446         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3447     }
3448 
3449     void VisitBinaryOperator(BinaryOperator *E) {
3450       // If a field assignment is detected, remove the field from the
3451       // uninitiailized field set.
3452       if (E->getOpcode() == BO_Assign)
3453         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3454           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3455             if (!FD->getType()->isReferenceType())
3456               DeclsToRemove.push_back(FD);
3457 
3458       if (E->isCompoundAssignmentOp()) {
3459         HandleValue(E->getLHS(), false /*AddressOf*/);
3460         Visit(E->getRHS());
3461         return;
3462       }
3463 
3464       Inherited::VisitBinaryOperator(E);
3465     }
3466 
3467     void VisitUnaryOperator(UnaryOperator *E) {
3468       if (E->isIncrementDecrementOp()) {
3469         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3470         return;
3471       }
3472       if (E->getOpcode() == UO_AddrOf) {
3473         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3474           HandleValue(ME->getBase(), true /*AddressOf*/);
3475           return;
3476         }
3477       }
3478 
3479       Inherited::VisitUnaryOperator(E);
3480     }
3481   };
3482 
3483   // Diagnose value-uses of fields to initialize themselves, e.g.
3484   //   foo(foo)
3485   // where foo is not also a parameter to the constructor.
3486   // Also diagnose across field uninitialized use such as
3487   //   x(y), y(x)
3488   // TODO: implement -Wuninitialized and fold this into that framework.
3489   static void DiagnoseUninitializedFields(
3490       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3491 
3492     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3493                                            Constructor->getLocation())) {
3494       return;
3495     }
3496 
3497     if (Constructor->isInvalidDecl())
3498       return;
3499 
3500     const CXXRecordDecl *RD = Constructor->getParent();
3501 
3502     if (RD->getDescribedClassTemplate())
3503       return;
3504 
3505     // Holds fields that are uninitialized.
3506     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3507 
3508     // At the beginning, all fields are uninitialized.
3509     for (auto *I : RD->decls()) {
3510       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3511         UninitializedFields.insert(FD);
3512       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3513         UninitializedFields.insert(IFD->getAnonField());
3514       }
3515     }
3516 
3517     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3518     for (auto I : RD->bases())
3519       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3520 
3521     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3522       return;
3523 
3524     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3525                                                    UninitializedFields,
3526                                                    UninitializedBaseClasses);
3527 
3528     for (const auto *FieldInit : Constructor->inits()) {
3529       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3530         break;
3531 
3532       Expr *InitExpr = FieldInit->getInit();
3533       if (!InitExpr)
3534         continue;
3535 
3536       if (CXXDefaultInitExpr *Default =
3537               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3538         InitExpr = Default->getExpr();
3539         if (!InitExpr)
3540           continue;
3541         // In class initializers will point to the constructor.
3542         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3543                                               FieldInit->getAnyMember(),
3544                                               FieldInit->getBaseClass());
3545       } else {
3546         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3547                                               FieldInit->getAnyMember(),
3548                                               FieldInit->getBaseClass());
3549       }
3550     }
3551   }
3552 } // namespace
3553 
3554 /// \brief Enter a new C++ default initializer scope. After calling this, the
3555 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3556 /// parsing or instantiating the initializer failed.
3557 void Sema::ActOnStartCXXInClassMemberInitializer() {
3558   // Create a synthetic function scope to represent the call to the constructor
3559   // that notionally surrounds a use of this initializer.
3560   PushFunctionScope();
3561 }
3562 
3563 /// \brief This is invoked after parsing an in-class initializer for a
3564 /// non-static C++ class member, and after instantiating an in-class initializer
3565 /// in a class template. Such actions are deferred until the class is complete.
3566 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3567                                                   SourceLocation InitLoc,
3568                                                   Expr *InitExpr) {
3569   // Pop the notional constructor scope we created earlier.
3570   PopFunctionScopeInfo(nullptr, D);
3571 
3572   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3573   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3574          "must set init style when field is created");
3575 
3576   if (!InitExpr) {
3577     D->setInvalidDecl();
3578     if (FD)
3579       FD->removeInClassInitializer();
3580     return;
3581   }
3582 
3583   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3584     FD->setInvalidDecl();
3585     FD->removeInClassInitializer();
3586     return;
3587   }
3588 
3589   ExprResult Init = InitExpr;
3590   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3591     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3592     InitializationKind Kind =
3593         FD->getInClassInitStyle() == ICIS_ListInit
3594             ? InitializationKind::CreateDirectList(InitExpr->getLocStart(),
3595                                                    InitExpr->getLocStart(),
3596                                                    InitExpr->getLocEnd())
3597             : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3598     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3599     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3600     if (Init.isInvalid()) {
3601       FD->setInvalidDecl();
3602       return;
3603     }
3604   }
3605 
3606   // C++11 [class.base.init]p7:
3607   //   The initialization of each base and member constitutes a
3608   //   full-expression.
3609   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3610   if (Init.isInvalid()) {
3611     FD->setInvalidDecl();
3612     return;
3613   }
3614 
3615   InitExpr = Init.get();
3616 
3617   FD->setInClassInitializer(InitExpr);
3618 }
3619 
3620 /// \brief Find the direct and/or virtual base specifiers that
3621 /// correspond to the given base type, for use in base initialization
3622 /// within a constructor.
3623 static bool FindBaseInitializer(Sema &SemaRef,
3624                                 CXXRecordDecl *ClassDecl,
3625                                 QualType BaseType,
3626                                 const CXXBaseSpecifier *&DirectBaseSpec,
3627                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3628   // First, check for a direct base class.
3629   DirectBaseSpec = nullptr;
3630   for (const auto &Base : ClassDecl->bases()) {
3631     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3632       // We found a direct base of this type. That's what we're
3633       // initializing.
3634       DirectBaseSpec = &Base;
3635       break;
3636     }
3637   }
3638 
3639   // Check for a virtual base class.
3640   // FIXME: We might be able to short-circuit this if we know in advance that
3641   // there are no virtual bases.
3642   VirtualBaseSpec = nullptr;
3643   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3644     // We haven't found a base yet; search the class hierarchy for a
3645     // virtual base class.
3646     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3647                        /*DetectVirtual=*/false);
3648     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3649                               SemaRef.Context.getTypeDeclType(ClassDecl),
3650                               BaseType, Paths)) {
3651       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3652            Path != Paths.end(); ++Path) {
3653         if (Path->back().Base->isVirtual()) {
3654           VirtualBaseSpec = Path->back().Base;
3655           break;
3656         }
3657       }
3658     }
3659   }
3660 
3661   return DirectBaseSpec || VirtualBaseSpec;
3662 }
3663 
3664 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3665 MemInitResult
3666 Sema::ActOnMemInitializer(Decl *ConstructorD,
3667                           Scope *S,
3668                           CXXScopeSpec &SS,
3669                           IdentifierInfo *MemberOrBase,
3670                           ParsedType TemplateTypeTy,
3671                           const DeclSpec &DS,
3672                           SourceLocation IdLoc,
3673                           Expr *InitList,
3674                           SourceLocation EllipsisLoc) {
3675   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3676                              DS, IdLoc, InitList,
3677                              EllipsisLoc);
3678 }
3679 
3680 /// \brief Handle a C++ member initializer using parentheses syntax.
3681 MemInitResult
3682 Sema::ActOnMemInitializer(Decl *ConstructorD,
3683                           Scope *S,
3684                           CXXScopeSpec &SS,
3685                           IdentifierInfo *MemberOrBase,
3686                           ParsedType TemplateTypeTy,
3687                           const DeclSpec &DS,
3688                           SourceLocation IdLoc,
3689                           SourceLocation LParenLoc,
3690                           ArrayRef<Expr *> Args,
3691                           SourceLocation RParenLoc,
3692                           SourceLocation EllipsisLoc) {
3693   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3694                                            Args, RParenLoc);
3695   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3696                              DS, IdLoc, List, EllipsisLoc);
3697 }
3698 
3699 namespace {
3700 
3701 // Callback to only accept typo corrections that can be a valid C++ member
3702 // intializer: either a non-static field member or a base class.
3703 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3704 public:
3705   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3706       : ClassDecl(ClassDecl) {}
3707 
3708   bool ValidateCandidate(const TypoCorrection &candidate) override {
3709     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3710       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3711         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3712       return isa<TypeDecl>(ND);
3713     }
3714     return false;
3715   }
3716 
3717 private:
3718   CXXRecordDecl *ClassDecl;
3719 };
3720 
3721 }
3722 
3723 /// \brief Handle a C++ member initializer.
3724 MemInitResult
3725 Sema::BuildMemInitializer(Decl *ConstructorD,
3726                           Scope *S,
3727                           CXXScopeSpec &SS,
3728                           IdentifierInfo *MemberOrBase,
3729                           ParsedType TemplateTypeTy,
3730                           const DeclSpec &DS,
3731                           SourceLocation IdLoc,
3732                           Expr *Init,
3733                           SourceLocation EllipsisLoc) {
3734   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3735   if (!Res.isUsable())
3736     return true;
3737   Init = Res.get();
3738 
3739   if (!ConstructorD)
3740     return true;
3741 
3742   AdjustDeclIfTemplate(ConstructorD);
3743 
3744   CXXConstructorDecl *Constructor
3745     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3746   if (!Constructor) {
3747     // The user wrote a constructor initializer on a function that is
3748     // not a C++ constructor. Ignore the error for now, because we may
3749     // have more member initializers coming; we'll diagnose it just
3750     // once in ActOnMemInitializers.
3751     return true;
3752   }
3753 
3754   CXXRecordDecl *ClassDecl = Constructor->getParent();
3755 
3756   // C++ [class.base.init]p2:
3757   //   Names in a mem-initializer-id are looked up in the scope of the
3758   //   constructor's class and, if not found in that scope, are looked
3759   //   up in the scope containing the constructor's definition.
3760   //   [Note: if the constructor's class contains a member with the
3761   //   same name as a direct or virtual base class of the class, a
3762   //   mem-initializer-id naming the member or base class and composed
3763   //   of a single identifier refers to the class member. A
3764   //   mem-initializer-id for the hidden base class may be specified
3765   //   using a qualified name. ]
3766   if (!SS.getScopeRep() && !TemplateTypeTy) {
3767     // Look for a member, first.
3768     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3769     if (!Result.empty()) {
3770       ValueDecl *Member;
3771       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3772           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3773         if (EllipsisLoc.isValid())
3774           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3775             << MemberOrBase
3776             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3777 
3778         return BuildMemberInitializer(Member, Init, IdLoc);
3779       }
3780     }
3781   }
3782   // It didn't name a member, so see if it names a class.
3783   QualType BaseType;
3784   TypeSourceInfo *TInfo = nullptr;
3785 
3786   if (TemplateTypeTy) {
3787     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3788   } else if (DS.getTypeSpecType() == TST_decltype) {
3789     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3790   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3791     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3792     return true;
3793   } else {
3794     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3795     LookupParsedName(R, S, &SS);
3796 
3797     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3798     if (!TyD) {
3799       if (R.isAmbiguous()) return true;
3800 
3801       // We don't want access-control diagnostics here.
3802       R.suppressDiagnostics();
3803 
3804       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3805         bool NotUnknownSpecialization = false;
3806         DeclContext *DC = computeDeclContext(SS, false);
3807         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3808           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3809 
3810         if (!NotUnknownSpecialization) {
3811           // When the scope specifier can refer to a member of an unknown
3812           // specialization, we take it as a type name.
3813           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3814                                        SS.getWithLocInContext(Context),
3815                                        *MemberOrBase, IdLoc);
3816           if (BaseType.isNull())
3817             return true;
3818 
3819           TInfo = Context.CreateTypeSourceInfo(BaseType);
3820           DependentNameTypeLoc TL =
3821               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3822           if (!TL.isNull()) {
3823             TL.setNameLoc(IdLoc);
3824             TL.setElaboratedKeywordLoc(SourceLocation());
3825             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3826           }
3827 
3828           R.clear();
3829           R.setLookupName(MemberOrBase);
3830         }
3831       }
3832 
3833       // If no results were found, try to correct typos.
3834       TypoCorrection Corr;
3835       if (R.empty() && BaseType.isNull() &&
3836           (Corr = CorrectTypo(
3837                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3838                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3839                CTK_ErrorRecovery, ClassDecl))) {
3840         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3841           // We have found a non-static data member with a similar
3842           // name to what was typed; complain and initialize that
3843           // member.
3844           diagnoseTypo(Corr,
3845                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3846                          << MemberOrBase << true);
3847           return BuildMemberInitializer(Member, Init, IdLoc);
3848         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3849           const CXXBaseSpecifier *DirectBaseSpec;
3850           const CXXBaseSpecifier *VirtualBaseSpec;
3851           if (FindBaseInitializer(*this, ClassDecl,
3852                                   Context.getTypeDeclType(Type),
3853                                   DirectBaseSpec, VirtualBaseSpec)) {
3854             // We have found a direct or virtual base class with a
3855             // similar name to what was typed; complain and initialize
3856             // that base class.
3857             diagnoseTypo(Corr,
3858                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3859                            << MemberOrBase << false,
3860                          PDiag() /*Suppress note, we provide our own.*/);
3861 
3862             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3863                                                               : VirtualBaseSpec;
3864             Diag(BaseSpec->getLocStart(),
3865                  diag::note_base_class_specified_here)
3866               << BaseSpec->getType()
3867               << BaseSpec->getSourceRange();
3868 
3869             TyD = Type;
3870           }
3871         }
3872       }
3873 
3874       if (!TyD && BaseType.isNull()) {
3875         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3876           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3877         return true;
3878       }
3879     }
3880 
3881     if (BaseType.isNull()) {
3882       BaseType = Context.getTypeDeclType(TyD);
3883       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3884       if (SS.isSet()) {
3885         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3886                                              BaseType);
3887         TInfo = Context.CreateTypeSourceInfo(BaseType);
3888         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3889         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3890         TL.setElaboratedKeywordLoc(SourceLocation());
3891         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3892       }
3893     }
3894   }
3895 
3896   if (!TInfo)
3897     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3898 
3899   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3900 }
3901 
3902 /// Checks a member initializer expression for cases where reference (or
3903 /// pointer) members are bound to by-value parameters (or their addresses).
3904 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3905                                                Expr *Init,
3906                                                SourceLocation IdLoc) {
3907   QualType MemberTy = Member->getType();
3908 
3909   // We only handle pointers and references currently.
3910   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3911   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3912     return;
3913 
3914   const bool IsPointer = MemberTy->isPointerType();
3915   if (IsPointer) {
3916     if (const UnaryOperator *Op
3917           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3918       // The only case we're worried about with pointers requires taking the
3919       // address.
3920       if (Op->getOpcode() != UO_AddrOf)
3921         return;
3922 
3923       Init = Op->getSubExpr();
3924     } else {
3925       // We only handle address-of expression initializers for pointers.
3926       return;
3927     }
3928   }
3929 
3930   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3931     // We only warn when referring to a non-reference parameter declaration.
3932     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3933     if (!Parameter || Parameter->getType()->isReferenceType())
3934       return;
3935 
3936     S.Diag(Init->getExprLoc(),
3937            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3938                      : diag::warn_bind_ref_member_to_parameter)
3939       << Member << Parameter << Init->getSourceRange();
3940   } else {
3941     // Other initializers are fine.
3942     return;
3943   }
3944 
3945   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3946     << (unsigned)IsPointer;
3947 }
3948 
3949 MemInitResult
3950 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3951                              SourceLocation IdLoc) {
3952   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3953   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3954   assert((DirectMember || IndirectMember) &&
3955          "Member must be a FieldDecl or IndirectFieldDecl");
3956 
3957   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3958     return true;
3959 
3960   if (Member->isInvalidDecl())
3961     return true;
3962 
3963   MultiExprArg Args;
3964   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3965     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3966   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3967     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3968   } else {
3969     // Template instantiation doesn't reconstruct ParenListExprs for us.
3970     Args = Init;
3971   }
3972 
3973   SourceRange InitRange = Init->getSourceRange();
3974 
3975   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3976     // Can't check initialization for a member of dependent type or when
3977     // any of the arguments are type-dependent expressions.
3978     DiscardCleanupsInEvaluationContext();
3979   } else {
3980     bool InitList = false;
3981     if (isa<InitListExpr>(Init)) {
3982       InitList = true;
3983       Args = Init;
3984     }
3985 
3986     // Initialize the member.
3987     InitializedEntity MemberEntity =
3988       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3989                    : InitializedEntity::InitializeMember(IndirectMember,
3990                                                          nullptr);
3991     InitializationKind Kind =
3992         InitList ? InitializationKind::CreateDirectList(
3993                        IdLoc, Init->getLocStart(), Init->getLocEnd())
3994                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3995                                                     InitRange.getEnd());
3996 
3997     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3998     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3999                                             nullptr);
4000     if (MemberInit.isInvalid())
4001       return true;
4002 
4003     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
4004 
4005     // C++11 [class.base.init]p7:
4006     //   The initialization of each base and member constitutes a
4007     //   full-expression.
4008     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4009     if (MemberInit.isInvalid())
4010       return true;
4011 
4012     Init = MemberInit.get();
4013   }
4014 
4015   if (DirectMember) {
4016     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4017                                             InitRange.getBegin(), Init,
4018                                             InitRange.getEnd());
4019   } else {
4020     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4021                                             InitRange.getBegin(), Init,
4022                                             InitRange.getEnd());
4023   }
4024 }
4025 
4026 MemInitResult
4027 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4028                                  CXXRecordDecl *ClassDecl) {
4029   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4030   if (!LangOpts.CPlusPlus11)
4031     return Diag(NameLoc, diag::err_delegating_ctor)
4032       << TInfo->getTypeLoc().getLocalSourceRange();
4033   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4034 
4035   bool InitList = true;
4036   MultiExprArg Args = Init;
4037   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4038     InitList = false;
4039     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4040   }
4041 
4042   SourceRange InitRange = Init->getSourceRange();
4043   // Initialize the object.
4044   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4045                                      QualType(ClassDecl->getTypeForDecl(), 0));
4046   InitializationKind Kind =
4047       InitList ? InitializationKind::CreateDirectList(
4048                      NameLoc, Init->getLocStart(), Init->getLocEnd())
4049                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4050                                                   InitRange.getEnd());
4051   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4052   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4053                                               Args, nullptr);
4054   if (DelegationInit.isInvalid())
4055     return true;
4056 
4057   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4058          "Delegating constructor with no target?");
4059 
4060   // C++11 [class.base.init]p7:
4061   //   The initialization of each base and member constitutes a
4062   //   full-expression.
4063   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4064                                        InitRange.getBegin());
4065   if (DelegationInit.isInvalid())
4066     return true;
4067 
4068   // If we are in a dependent context, template instantiation will
4069   // perform this type-checking again. Just save the arguments that we
4070   // received in a ParenListExpr.
4071   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4072   // of the information that we have about the base
4073   // initializer. However, deconstructing the ASTs is a dicey process,
4074   // and this approach is far more likely to get the corner cases right.
4075   if (CurContext->isDependentContext())
4076     DelegationInit = Init;
4077 
4078   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4079                                           DelegationInit.getAs<Expr>(),
4080                                           InitRange.getEnd());
4081 }
4082 
4083 MemInitResult
4084 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4085                            Expr *Init, CXXRecordDecl *ClassDecl,
4086                            SourceLocation EllipsisLoc) {
4087   SourceLocation BaseLoc
4088     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4089 
4090   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4091     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4092              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4093 
4094   // C++ [class.base.init]p2:
4095   //   [...] Unless the mem-initializer-id names a nonstatic data
4096   //   member of the constructor's class or a direct or virtual base
4097   //   of that class, the mem-initializer is ill-formed. A
4098   //   mem-initializer-list can initialize a base class using any
4099   //   name that denotes that base class type.
4100   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4101 
4102   SourceRange InitRange = Init->getSourceRange();
4103   if (EllipsisLoc.isValid()) {
4104     // This is a pack expansion.
4105     if (!BaseType->containsUnexpandedParameterPack())  {
4106       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4107         << SourceRange(BaseLoc, InitRange.getEnd());
4108 
4109       EllipsisLoc = SourceLocation();
4110     }
4111   } else {
4112     // Check for any unexpanded parameter packs.
4113     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4114       return true;
4115 
4116     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4117       return true;
4118   }
4119 
4120   // Check for direct and virtual base classes.
4121   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4122   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4123   if (!Dependent) {
4124     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4125                                        BaseType))
4126       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4127 
4128     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4129                         VirtualBaseSpec);
4130 
4131     // C++ [base.class.init]p2:
4132     // Unless the mem-initializer-id names a nonstatic data member of the
4133     // constructor's class or a direct or virtual base of that class, the
4134     // mem-initializer is ill-formed.
4135     if (!DirectBaseSpec && !VirtualBaseSpec) {
4136       // If the class has any dependent bases, then it's possible that
4137       // one of those types will resolve to the same type as
4138       // BaseType. Therefore, just treat this as a dependent base
4139       // class initialization.  FIXME: Should we try to check the
4140       // initialization anyway? It seems odd.
4141       if (ClassDecl->hasAnyDependentBases())
4142         Dependent = true;
4143       else
4144         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4145           << BaseType << Context.getTypeDeclType(ClassDecl)
4146           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4147     }
4148   }
4149 
4150   if (Dependent) {
4151     DiscardCleanupsInEvaluationContext();
4152 
4153     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4154                                             /*IsVirtual=*/false,
4155                                             InitRange.getBegin(), Init,
4156                                             InitRange.getEnd(), EllipsisLoc);
4157   }
4158 
4159   // C++ [base.class.init]p2:
4160   //   If a mem-initializer-id is ambiguous because it designates both
4161   //   a direct non-virtual base class and an inherited virtual base
4162   //   class, the mem-initializer is ill-formed.
4163   if (DirectBaseSpec && VirtualBaseSpec)
4164     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4165       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4166 
4167   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4168   if (!BaseSpec)
4169     BaseSpec = VirtualBaseSpec;
4170 
4171   // Initialize the base.
4172   bool InitList = true;
4173   MultiExprArg Args = Init;
4174   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4175     InitList = false;
4176     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4177   }
4178 
4179   InitializedEntity BaseEntity =
4180     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4181   InitializationKind Kind =
4182       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4183                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4184                                                   InitRange.getEnd());
4185   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4186   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4187   if (BaseInit.isInvalid())
4188     return true;
4189 
4190   // C++11 [class.base.init]p7:
4191   //   The initialization of each base and member constitutes a
4192   //   full-expression.
4193   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4194   if (BaseInit.isInvalid())
4195     return true;
4196 
4197   // If we are in a dependent context, template instantiation will
4198   // perform this type-checking again. Just save the arguments that we
4199   // received in a ParenListExpr.
4200   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4201   // of the information that we have about the base
4202   // initializer. However, deconstructing the ASTs is a dicey process,
4203   // and this approach is far more likely to get the corner cases right.
4204   if (CurContext->isDependentContext())
4205     BaseInit = Init;
4206 
4207   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4208                                           BaseSpec->isVirtual(),
4209                                           InitRange.getBegin(),
4210                                           BaseInit.getAs<Expr>(),
4211                                           InitRange.getEnd(), EllipsisLoc);
4212 }
4213 
4214 // Create a static_cast\<T&&>(expr).
4215 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4216   if (T.isNull()) T = E->getType();
4217   QualType TargetType = SemaRef.BuildReferenceType(
4218       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4219   SourceLocation ExprLoc = E->getLocStart();
4220   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4221       TargetType, ExprLoc);
4222 
4223   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4224                                    SourceRange(ExprLoc, ExprLoc),
4225                                    E->getSourceRange()).get();
4226 }
4227 
4228 /// ImplicitInitializerKind - How an implicit base or member initializer should
4229 /// initialize its base or member.
4230 enum ImplicitInitializerKind {
4231   IIK_Default,
4232   IIK_Copy,
4233   IIK_Move,
4234   IIK_Inherit
4235 };
4236 
4237 static bool
4238 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4239                              ImplicitInitializerKind ImplicitInitKind,
4240                              CXXBaseSpecifier *BaseSpec,
4241                              bool IsInheritedVirtualBase,
4242                              CXXCtorInitializer *&CXXBaseInit) {
4243   InitializedEntity InitEntity
4244     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4245                                         IsInheritedVirtualBase);
4246 
4247   ExprResult BaseInit;
4248 
4249   switch (ImplicitInitKind) {
4250   case IIK_Inherit:
4251   case IIK_Default: {
4252     InitializationKind InitKind
4253       = InitializationKind::CreateDefault(Constructor->getLocation());
4254     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4255     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4256     break;
4257   }
4258 
4259   case IIK_Move:
4260   case IIK_Copy: {
4261     bool Moving = ImplicitInitKind == IIK_Move;
4262     ParmVarDecl *Param = Constructor->getParamDecl(0);
4263     QualType ParamType = Param->getType().getNonReferenceType();
4264 
4265     Expr *CopyCtorArg =
4266       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4267                           SourceLocation(), Param, false,
4268                           Constructor->getLocation(), ParamType,
4269                           VK_LValue, nullptr);
4270 
4271     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4272 
4273     // Cast to the base class to avoid ambiguities.
4274     QualType ArgTy =
4275       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4276                                        ParamType.getQualifiers());
4277 
4278     if (Moving) {
4279       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4280     }
4281 
4282     CXXCastPath BasePath;
4283     BasePath.push_back(BaseSpec);
4284     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4285                                             CK_UncheckedDerivedToBase,
4286                                             Moving ? VK_XValue : VK_LValue,
4287                                             &BasePath).get();
4288 
4289     InitializationKind InitKind
4290       = InitializationKind::CreateDirect(Constructor->getLocation(),
4291                                          SourceLocation(), SourceLocation());
4292     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4293     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4294     break;
4295   }
4296   }
4297 
4298   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4299   if (BaseInit.isInvalid())
4300     return true;
4301 
4302   CXXBaseInit =
4303     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4304                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4305                                                         SourceLocation()),
4306                                              BaseSpec->isVirtual(),
4307                                              SourceLocation(),
4308                                              BaseInit.getAs<Expr>(),
4309                                              SourceLocation(),
4310                                              SourceLocation());
4311 
4312   return false;
4313 }
4314 
4315 static bool RefersToRValueRef(Expr *MemRef) {
4316   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4317   return Referenced->getType()->isRValueReferenceType();
4318 }
4319 
4320 static bool
4321 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4322                                ImplicitInitializerKind ImplicitInitKind,
4323                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4324                                CXXCtorInitializer *&CXXMemberInit) {
4325   if (Field->isInvalidDecl())
4326     return true;
4327 
4328   SourceLocation Loc = Constructor->getLocation();
4329 
4330   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4331     bool Moving = ImplicitInitKind == IIK_Move;
4332     ParmVarDecl *Param = Constructor->getParamDecl(0);
4333     QualType ParamType = Param->getType().getNonReferenceType();
4334 
4335     // Suppress copying zero-width bitfields.
4336     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4337       return false;
4338 
4339     Expr *MemberExprBase =
4340       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4341                           SourceLocation(), Param, false,
4342                           Loc, ParamType, VK_LValue, nullptr);
4343 
4344     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4345 
4346     if (Moving) {
4347       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4348     }
4349 
4350     // Build a reference to this field within the parameter.
4351     CXXScopeSpec SS;
4352     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4353                               Sema::LookupMemberName);
4354     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4355                                   : cast<ValueDecl>(Field), AS_public);
4356     MemberLookup.resolveKind();
4357     ExprResult CtorArg
4358       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4359                                          ParamType, Loc,
4360                                          /*IsArrow=*/false,
4361                                          SS,
4362                                          /*TemplateKWLoc=*/SourceLocation(),
4363                                          /*FirstQualifierInScope=*/nullptr,
4364                                          MemberLookup,
4365                                          /*TemplateArgs=*/nullptr,
4366                                          /*S*/nullptr);
4367     if (CtorArg.isInvalid())
4368       return true;
4369 
4370     // C++11 [class.copy]p15:
4371     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4372     //     with static_cast<T&&>(x.m);
4373     if (RefersToRValueRef(CtorArg.get())) {
4374       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4375     }
4376 
4377     InitializedEntity Entity =
4378         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4379                                                        /*Implicit*/ true)
4380                  : InitializedEntity::InitializeMember(Field, nullptr,
4381                                                        /*Implicit*/ true);
4382 
4383     // Direct-initialize to use the copy constructor.
4384     InitializationKind InitKind =
4385       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4386 
4387     Expr *CtorArgE = CtorArg.getAs<Expr>();
4388     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4389     ExprResult MemberInit =
4390         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4391     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4392     if (MemberInit.isInvalid())
4393       return true;
4394 
4395     if (Indirect)
4396       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4397           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4398     else
4399       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4400           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4401     return false;
4402   }
4403 
4404   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4405          "Unhandled implicit init kind!");
4406 
4407   QualType FieldBaseElementType =
4408     SemaRef.Context.getBaseElementType(Field->getType());
4409 
4410   if (FieldBaseElementType->isRecordType()) {
4411     InitializedEntity InitEntity =
4412         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4413                                                        /*Implicit*/ true)
4414                  : InitializedEntity::InitializeMember(Field, nullptr,
4415                                                        /*Implicit*/ true);
4416     InitializationKind InitKind =
4417       InitializationKind::CreateDefault(Loc);
4418 
4419     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4420     ExprResult MemberInit =
4421       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4422 
4423     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4424     if (MemberInit.isInvalid())
4425       return true;
4426 
4427     if (Indirect)
4428       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4429                                                                Indirect, Loc,
4430                                                                Loc,
4431                                                                MemberInit.get(),
4432                                                                Loc);
4433     else
4434       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4435                                                                Field, Loc, Loc,
4436                                                                MemberInit.get(),
4437                                                                Loc);
4438     return false;
4439   }
4440 
4441   if (!Field->getParent()->isUnion()) {
4442     if (FieldBaseElementType->isReferenceType()) {
4443       SemaRef.Diag(Constructor->getLocation(),
4444                    diag::err_uninitialized_member_in_ctor)
4445       << (int)Constructor->isImplicit()
4446       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4447       << 0 << Field->getDeclName();
4448       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4449       return true;
4450     }
4451 
4452     if (FieldBaseElementType.isConstQualified()) {
4453       SemaRef.Diag(Constructor->getLocation(),
4454                    diag::err_uninitialized_member_in_ctor)
4455       << (int)Constructor->isImplicit()
4456       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4457       << 1 << Field->getDeclName();
4458       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4459       return true;
4460     }
4461   }
4462 
4463   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4464     // ARC and Weak:
4465     //   Default-initialize Objective-C pointers to NULL.
4466     CXXMemberInit
4467       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4468                                                  Loc, Loc,
4469                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4470                                                  Loc);
4471     return false;
4472   }
4473 
4474   // Nothing to initialize.
4475   CXXMemberInit = nullptr;
4476   return false;
4477 }
4478 
4479 namespace {
4480 struct BaseAndFieldInfo {
4481   Sema &S;
4482   CXXConstructorDecl *Ctor;
4483   bool AnyErrorsInInits;
4484   ImplicitInitializerKind IIK;
4485   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4486   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4487   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4488 
4489   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4490     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4491     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4492     if (Ctor->getInheritedConstructor())
4493       IIK = IIK_Inherit;
4494     else if (Generated && Ctor->isCopyConstructor())
4495       IIK = IIK_Copy;
4496     else if (Generated && Ctor->isMoveConstructor())
4497       IIK = IIK_Move;
4498     else
4499       IIK = IIK_Default;
4500   }
4501 
4502   bool isImplicitCopyOrMove() const {
4503     switch (IIK) {
4504     case IIK_Copy:
4505     case IIK_Move:
4506       return true;
4507 
4508     case IIK_Default:
4509     case IIK_Inherit:
4510       return false;
4511     }
4512 
4513     llvm_unreachable("Invalid ImplicitInitializerKind!");
4514   }
4515 
4516   bool addFieldInitializer(CXXCtorInitializer *Init) {
4517     AllToInit.push_back(Init);
4518 
4519     // Check whether this initializer makes the field "used".
4520     if (Init->getInit()->HasSideEffects(S.Context))
4521       S.UnusedPrivateFields.remove(Init->getAnyMember());
4522 
4523     return false;
4524   }
4525 
4526   bool isInactiveUnionMember(FieldDecl *Field) {
4527     RecordDecl *Record = Field->getParent();
4528     if (!Record->isUnion())
4529       return false;
4530 
4531     if (FieldDecl *Active =
4532             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4533       return Active != Field->getCanonicalDecl();
4534 
4535     // In an implicit copy or move constructor, ignore any in-class initializer.
4536     if (isImplicitCopyOrMove())
4537       return true;
4538 
4539     // If there's no explicit initialization, the field is active only if it
4540     // has an in-class initializer...
4541     if (Field->hasInClassInitializer())
4542       return false;
4543     // ... or it's an anonymous struct or union whose class has an in-class
4544     // initializer.
4545     if (!Field->isAnonymousStructOrUnion())
4546       return true;
4547     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4548     return !FieldRD->hasInClassInitializer();
4549   }
4550 
4551   /// \brief Determine whether the given field is, or is within, a union member
4552   /// that is inactive (because there was an initializer given for a different
4553   /// member of the union, or because the union was not initialized at all).
4554   bool isWithinInactiveUnionMember(FieldDecl *Field,
4555                                    IndirectFieldDecl *Indirect) {
4556     if (!Indirect)
4557       return isInactiveUnionMember(Field);
4558 
4559     for (auto *C : Indirect->chain()) {
4560       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4561       if (Field && isInactiveUnionMember(Field))
4562         return true;
4563     }
4564     return false;
4565   }
4566 };
4567 }
4568 
4569 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4570 /// array type.
4571 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4572   if (T->isIncompleteArrayType())
4573     return true;
4574 
4575   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4576     if (!ArrayT->getSize())
4577       return true;
4578 
4579     T = ArrayT->getElementType();
4580   }
4581 
4582   return false;
4583 }
4584 
4585 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4586                                     FieldDecl *Field,
4587                                     IndirectFieldDecl *Indirect = nullptr) {
4588   if (Field->isInvalidDecl())
4589     return false;
4590 
4591   // Overwhelmingly common case: we have a direct initializer for this field.
4592   if (CXXCtorInitializer *Init =
4593           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4594     return Info.addFieldInitializer(Init);
4595 
4596   // C++11 [class.base.init]p8:
4597   //   if the entity is a non-static data member that has a
4598   //   brace-or-equal-initializer and either
4599   //   -- the constructor's class is a union and no other variant member of that
4600   //      union is designated by a mem-initializer-id or
4601   //   -- the constructor's class is not a union, and, if the entity is a member
4602   //      of an anonymous union, no other member of that union is designated by
4603   //      a mem-initializer-id,
4604   //   the entity is initialized as specified in [dcl.init].
4605   //
4606   // We also apply the same rules to handle anonymous structs within anonymous
4607   // unions.
4608   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4609     return false;
4610 
4611   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4612     ExprResult DIE =
4613         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4614     if (DIE.isInvalid())
4615       return true;
4616     CXXCtorInitializer *Init;
4617     if (Indirect)
4618       Init = new (SemaRef.Context)
4619           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4620                              SourceLocation(), DIE.get(), SourceLocation());
4621     else
4622       Init = new (SemaRef.Context)
4623           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4624                              SourceLocation(), DIE.get(), SourceLocation());
4625     return Info.addFieldInitializer(Init);
4626   }
4627 
4628   // Don't initialize incomplete or zero-length arrays.
4629   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4630     return false;
4631 
4632   // Don't try to build an implicit initializer if there were semantic
4633   // errors in any of the initializers (and therefore we might be
4634   // missing some that the user actually wrote).
4635   if (Info.AnyErrorsInInits)
4636     return false;
4637 
4638   CXXCtorInitializer *Init = nullptr;
4639   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4640                                      Indirect, Init))
4641     return true;
4642 
4643   if (!Init)
4644     return false;
4645 
4646   return Info.addFieldInitializer(Init);
4647 }
4648 
4649 bool
4650 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4651                                CXXCtorInitializer *Initializer) {
4652   assert(Initializer->isDelegatingInitializer());
4653   Constructor->setNumCtorInitializers(1);
4654   CXXCtorInitializer **initializer =
4655     new (Context) CXXCtorInitializer*[1];
4656   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4657   Constructor->setCtorInitializers(initializer);
4658 
4659   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4660     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4661     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4662   }
4663 
4664   DelegatingCtorDecls.push_back(Constructor);
4665 
4666   DiagnoseUninitializedFields(*this, Constructor);
4667 
4668   return false;
4669 }
4670 
4671 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4672                                ArrayRef<CXXCtorInitializer *> Initializers) {
4673   if (Constructor->isDependentContext()) {
4674     // Just store the initializers as written, they will be checked during
4675     // instantiation.
4676     if (!Initializers.empty()) {
4677       Constructor->setNumCtorInitializers(Initializers.size());
4678       CXXCtorInitializer **baseOrMemberInitializers =
4679         new (Context) CXXCtorInitializer*[Initializers.size()];
4680       memcpy(baseOrMemberInitializers, Initializers.data(),
4681              Initializers.size() * sizeof(CXXCtorInitializer*));
4682       Constructor->setCtorInitializers(baseOrMemberInitializers);
4683     }
4684 
4685     // Let template instantiation know whether we had errors.
4686     if (AnyErrors)
4687       Constructor->setInvalidDecl();
4688 
4689     return false;
4690   }
4691 
4692   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4693 
4694   // We need to build the initializer AST according to order of construction
4695   // and not what user specified in the Initializers list.
4696   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4697   if (!ClassDecl)
4698     return true;
4699 
4700   bool HadError = false;
4701 
4702   for (unsigned i = 0; i < Initializers.size(); i++) {
4703     CXXCtorInitializer *Member = Initializers[i];
4704 
4705     if (Member->isBaseInitializer())
4706       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4707     else {
4708       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4709 
4710       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4711         for (auto *C : F->chain()) {
4712           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4713           if (FD && FD->getParent()->isUnion())
4714             Info.ActiveUnionMember.insert(std::make_pair(
4715                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4716         }
4717       } else if (FieldDecl *FD = Member->getMember()) {
4718         if (FD->getParent()->isUnion())
4719           Info.ActiveUnionMember.insert(std::make_pair(
4720               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4721       }
4722     }
4723   }
4724 
4725   // Keep track of the direct virtual bases.
4726   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4727   for (auto &I : ClassDecl->bases()) {
4728     if (I.isVirtual())
4729       DirectVBases.insert(&I);
4730   }
4731 
4732   // Push virtual bases before others.
4733   for (auto &VBase : ClassDecl->vbases()) {
4734     if (CXXCtorInitializer *Value
4735         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4736       // [class.base.init]p7, per DR257:
4737       //   A mem-initializer where the mem-initializer-id names a virtual base
4738       //   class is ignored during execution of a constructor of any class that
4739       //   is not the most derived class.
4740       if (ClassDecl->isAbstract()) {
4741         // FIXME: Provide a fixit to remove the base specifier. This requires
4742         // tracking the location of the associated comma for a base specifier.
4743         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4744           << VBase.getType() << ClassDecl;
4745         DiagnoseAbstractType(ClassDecl);
4746       }
4747 
4748       Info.AllToInit.push_back(Value);
4749     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4750       // [class.base.init]p8, per DR257:
4751       //   If a given [...] base class is not named by a mem-initializer-id
4752       //   [...] and the entity is not a virtual base class of an abstract
4753       //   class, then [...] the entity is default-initialized.
4754       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4755       CXXCtorInitializer *CXXBaseInit;
4756       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4757                                        &VBase, IsInheritedVirtualBase,
4758                                        CXXBaseInit)) {
4759         HadError = true;
4760         continue;
4761       }
4762 
4763       Info.AllToInit.push_back(CXXBaseInit);
4764     }
4765   }
4766 
4767   // Non-virtual bases.
4768   for (auto &Base : ClassDecl->bases()) {
4769     // Virtuals are in the virtual base list and already constructed.
4770     if (Base.isVirtual())
4771       continue;
4772 
4773     if (CXXCtorInitializer *Value
4774           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4775       Info.AllToInit.push_back(Value);
4776     } else if (!AnyErrors) {
4777       CXXCtorInitializer *CXXBaseInit;
4778       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4779                                        &Base, /*IsInheritedVirtualBase=*/false,
4780                                        CXXBaseInit)) {
4781         HadError = true;
4782         continue;
4783       }
4784 
4785       Info.AllToInit.push_back(CXXBaseInit);
4786     }
4787   }
4788 
4789   // Fields.
4790   for (auto *Mem : ClassDecl->decls()) {
4791     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4792       // C++ [class.bit]p2:
4793       //   A declaration for a bit-field that omits the identifier declares an
4794       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4795       //   initialized.
4796       if (F->isUnnamedBitfield())
4797         continue;
4798 
4799       // If we're not generating the implicit copy/move constructor, then we'll
4800       // handle anonymous struct/union fields based on their individual
4801       // indirect fields.
4802       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4803         continue;
4804 
4805       if (CollectFieldInitializer(*this, Info, F))
4806         HadError = true;
4807       continue;
4808     }
4809 
4810     // Beyond this point, we only consider default initialization.
4811     if (Info.isImplicitCopyOrMove())
4812       continue;
4813 
4814     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4815       if (F->getType()->isIncompleteArrayType()) {
4816         assert(ClassDecl->hasFlexibleArrayMember() &&
4817                "Incomplete array type is not valid");
4818         continue;
4819       }
4820 
4821       // Initialize each field of an anonymous struct individually.
4822       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4823         HadError = true;
4824 
4825       continue;
4826     }
4827   }
4828 
4829   unsigned NumInitializers = Info.AllToInit.size();
4830   if (NumInitializers > 0) {
4831     Constructor->setNumCtorInitializers(NumInitializers);
4832     CXXCtorInitializer **baseOrMemberInitializers =
4833       new (Context) CXXCtorInitializer*[NumInitializers];
4834     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4835            NumInitializers * sizeof(CXXCtorInitializer*));
4836     Constructor->setCtorInitializers(baseOrMemberInitializers);
4837 
4838     // Constructors implicitly reference the base and member
4839     // destructors.
4840     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4841                                            Constructor->getParent());
4842   }
4843 
4844   return HadError;
4845 }
4846 
4847 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4848   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4849     const RecordDecl *RD = RT->getDecl();
4850     if (RD->isAnonymousStructOrUnion()) {
4851       for (auto *Field : RD->fields())
4852         PopulateKeysForFields(Field, IdealInits);
4853       return;
4854     }
4855   }
4856   IdealInits.push_back(Field->getCanonicalDecl());
4857 }
4858 
4859 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4860   return Context.getCanonicalType(BaseType).getTypePtr();
4861 }
4862 
4863 static const void *GetKeyForMember(ASTContext &Context,
4864                                    CXXCtorInitializer *Member) {
4865   if (!Member->isAnyMemberInitializer())
4866     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4867 
4868   return Member->getAnyMember()->getCanonicalDecl();
4869 }
4870 
4871 static void DiagnoseBaseOrMemInitializerOrder(
4872     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4873     ArrayRef<CXXCtorInitializer *> Inits) {
4874   if (Constructor->getDeclContext()->isDependentContext())
4875     return;
4876 
4877   // Don't check initializers order unless the warning is enabled at the
4878   // location of at least one initializer.
4879   bool ShouldCheckOrder = false;
4880   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4881     CXXCtorInitializer *Init = Inits[InitIndex];
4882     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4883                                  Init->getSourceLocation())) {
4884       ShouldCheckOrder = true;
4885       break;
4886     }
4887   }
4888   if (!ShouldCheckOrder)
4889     return;
4890 
4891   // Build the list of bases and members in the order that they'll
4892   // actually be initialized.  The explicit initializers should be in
4893   // this same order but may be missing things.
4894   SmallVector<const void*, 32> IdealInitKeys;
4895 
4896   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4897 
4898   // 1. Virtual bases.
4899   for (const auto &VBase : ClassDecl->vbases())
4900     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4901 
4902   // 2. Non-virtual bases.
4903   for (const auto &Base : ClassDecl->bases()) {
4904     if (Base.isVirtual())
4905       continue;
4906     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4907   }
4908 
4909   // 3. Direct fields.
4910   for (auto *Field : ClassDecl->fields()) {
4911     if (Field->isUnnamedBitfield())
4912       continue;
4913 
4914     PopulateKeysForFields(Field, IdealInitKeys);
4915   }
4916 
4917   unsigned NumIdealInits = IdealInitKeys.size();
4918   unsigned IdealIndex = 0;
4919 
4920   CXXCtorInitializer *PrevInit = nullptr;
4921   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4922     CXXCtorInitializer *Init = Inits[InitIndex];
4923     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4924 
4925     // Scan forward to try to find this initializer in the idealized
4926     // initializers list.
4927     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4928       if (InitKey == IdealInitKeys[IdealIndex])
4929         break;
4930 
4931     // If we didn't find this initializer, it must be because we
4932     // scanned past it on a previous iteration.  That can only
4933     // happen if we're out of order;  emit a warning.
4934     if (IdealIndex == NumIdealInits && PrevInit) {
4935       Sema::SemaDiagnosticBuilder D =
4936         SemaRef.Diag(PrevInit->getSourceLocation(),
4937                      diag::warn_initializer_out_of_order);
4938 
4939       if (PrevInit->isAnyMemberInitializer())
4940         D << 0 << PrevInit->getAnyMember()->getDeclName();
4941       else
4942         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4943 
4944       if (Init->isAnyMemberInitializer())
4945         D << 0 << Init->getAnyMember()->getDeclName();
4946       else
4947         D << 1 << Init->getTypeSourceInfo()->getType();
4948 
4949       // Move back to the initializer's location in the ideal list.
4950       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4951         if (InitKey == IdealInitKeys[IdealIndex])
4952           break;
4953 
4954       assert(IdealIndex < NumIdealInits &&
4955              "initializer not found in initializer list");
4956     }
4957 
4958     PrevInit = Init;
4959   }
4960 }
4961 
4962 namespace {
4963 bool CheckRedundantInit(Sema &S,
4964                         CXXCtorInitializer *Init,
4965                         CXXCtorInitializer *&PrevInit) {
4966   if (!PrevInit) {
4967     PrevInit = Init;
4968     return false;
4969   }
4970 
4971   if (FieldDecl *Field = Init->getAnyMember())
4972     S.Diag(Init->getSourceLocation(),
4973            diag::err_multiple_mem_initialization)
4974       << Field->getDeclName()
4975       << Init->getSourceRange();
4976   else {
4977     const Type *BaseClass = Init->getBaseClass();
4978     assert(BaseClass && "neither field nor base");
4979     S.Diag(Init->getSourceLocation(),
4980            diag::err_multiple_base_initialization)
4981       << QualType(BaseClass, 0)
4982       << Init->getSourceRange();
4983   }
4984   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4985     << 0 << PrevInit->getSourceRange();
4986 
4987   return true;
4988 }
4989 
4990 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4991 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4992 
4993 bool CheckRedundantUnionInit(Sema &S,
4994                              CXXCtorInitializer *Init,
4995                              RedundantUnionMap &Unions) {
4996   FieldDecl *Field = Init->getAnyMember();
4997   RecordDecl *Parent = Field->getParent();
4998   NamedDecl *Child = Field;
4999 
5000   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5001     if (Parent->isUnion()) {
5002       UnionEntry &En = Unions[Parent];
5003       if (En.first && En.first != Child) {
5004         S.Diag(Init->getSourceLocation(),
5005                diag::err_multiple_mem_union_initialization)
5006           << Field->getDeclName()
5007           << Init->getSourceRange();
5008         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5009           << 0 << En.second->getSourceRange();
5010         return true;
5011       }
5012       if (!En.first) {
5013         En.first = Child;
5014         En.second = Init;
5015       }
5016       if (!Parent->isAnonymousStructOrUnion())
5017         return false;
5018     }
5019 
5020     Child = Parent;
5021     Parent = cast<RecordDecl>(Parent->getDeclContext());
5022   }
5023 
5024   return false;
5025 }
5026 }
5027 
5028 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5029 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5030                                 SourceLocation ColonLoc,
5031                                 ArrayRef<CXXCtorInitializer*> MemInits,
5032                                 bool AnyErrors) {
5033   if (!ConstructorDecl)
5034     return;
5035 
5036   AdjustDeclIfTemplate(ConstructorDecl);
5037 
5038   CXXConstructorDecl *Constructor
5039     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5040 
5041   if (!Constructor) {
5042     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5043     return;
5044   }
5045 
5046   // Mapping for the duplicate initializers check.
5047   // For member initializers, this is keyed with a FieldDecl*.
5048   // For base initializers, this is keyed with a Type*.
5049   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5050 
5051   // Mapping for the inconsistent anonymous-union initializers check.
5052   RedundantUnionMap MemberUnions;
5053 
5054   bool HadError = false;
5055   for (unsigned i = 0; i < MemInits.size(); i++) {
5056     CXXCtorInitializer *Init = MemInits[i];
5057 
5058     // Set the source order index.
5059     Init->setSourceOrder(i);
5060 
5061     if (Init->isAnyMemberInitializer()) {
5062       const void *Key = GetKeyForMember(Context, Init);
5063       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5064           CheckRedundantUnionInit(*this, Init, MemberUnions))
5065         HadError = true;
5066     } else if (Init->isBaseInitializer()) {
5067       const void *Key = GetKeyForMember(Context, Init);
5068       if (CheckRedundantInit(*this, Init, Members[Key]))
5069         HadError = true;
5070     } else {
5071       assert(Init->isDelegatingInitializer());
5072       // This must be the only initializer
5073       if (MemInits.size() != 1) {
5074         Diag(Init->getSourceLocation(),
5075              diag::err_delegating_initializer_alone)
5076           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5077         // We will treat this as being the only initializer.
5078       }
5079       SetDelegatingInitializer(Constructor, MemInits[i]);
5080       // Return immediately as the initializer is set.
5081       return;
5082     }
5083   }
5084 
5085   if (HadError)
5086     return;
5087 
5088   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5089 
5090   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5091 
5092   DiagnoseUninitializedFields(*this, Constructor);
5093 }
5094 
5095 void
5096 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5097                                              CXXRecordDecl *ClassDecl) {
5098   // Ignore dependent contexts. Also ignore unions, since their members never
5099   // have destructors implicitly called.
5100   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5101     return;
5102 
5103   // FIXME: all the access-control diagnostics are positioned on the
5104   // field/base declaration.  That's probably good; that said, the
5105   // user might reasonably want to know why the destructor is being
5106   // emitted, and we currently don't say.
5107 
5108   // Non-static data members.
5109   for (auto *Field : ClassDecl->fields()) {
5110     if (Field->isInvalidDecl())
5111       continue;
5112 
5113     // Don't destroy incomplete or zero-length arrays.
5114     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5115       continue;
5116 
5117     QualType FieldType = Context.getBaseElementType(Field->getType());
5118 
5119     const RecordType* RT = FieldType->getAs<RecordType>();
5120     if (!RT)
5121       continue;
5122 
5123     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5124     if (FieldClassDecl->isInvalidDecl())
5125       continue;
5126     if (FieldClassDecl->hasIrrelevantDestructor())
5127       continue;
5128     // The destructor for an implicit anonymous union member is never invoked.
5129     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5130       continue;
5131 
5132     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5133     assert(Dtor && "No dtor found for FieldClassDecl!");
5134     CheckDestructorAccess(Field->getLocation(), Dtor,
5135                           PDiag(diag::err_access_dtor_field)
5136                             << Field->getDeclName()
5137                             << FieldType);
5138 
5139     MarkFunctionReferenced(Location, Dtor);
5140     DiagnoseUseOfDecl(Dtor, Location);
5141   }
5142 
5143   // We only potentially invoke the destructors of potentially constructed
5144   // subobjects.
5145   bool VisitVirtualBases = !ClassDecl->isAbstract();
5146 
5147   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5148 
5149   // Bases.
5150   for (const auto &Base : ClassDecl->bases()) {
5151     // Bases are always records in a well-formed non-dependent class.
5152     const RecordType *RT = Base.getType()->getAs<RecordType>();
5153 
5154     // Remember direct virtual bases.
5155     if (Base.isVirtual()) {
5156       if (!VisitVirtualBases)
5157         continue;
5158       DirectVirtualBases.insert(RT);
5159     }
5160 
5161     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5162     // If our base class is invalid, we probably can't get its dtor anyway.
5163     if (BaseClassDecl->isInvalidDecl())
5164       continue;
5165     if (BaseClassDecl->hasIrrelevantDestructor())
5166       continue;
5167 
5168     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5169     assert(Dtor && "No dtor found for BaseClassDecl!");
5170 
5171     // FIXME: caret should be on the start of the class name
5172     CheckDestructorAccess(Base.getLocStart(), Dtor,
5173                           PDiag(diag::err_access_dtor_base)
5174                             << Base.getType()
5175                             << Base.getSourceRange(),
5176                           Context.getTypeDeclType(ClassDecl));
5177 
5178     MarkFunctionReferenced(Location, Dtor);
5179     DiagnoseUseOfDecl(Dtor, Location);
5180   }
5181 
5182   if (!VisitVirtualBases)
5183     return;
5184 
5185   // Virtual bases.
5186   for (const auto &VBase : ClassDecl->vbases()) {
5187     // Bases are always records in a well-formed non-dependent class.
5188     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5189 
5190     // Ignore direct virtual bases.
5191     if (DirectVirtualBases.count(RT))
5192       continue;
5193 
5194     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5195     // If our base class is invalid, we probably can't get its dtor anyway.
5196     if (BaseClassDecl->isInvalidDecl())
5197       continue;
5198     if (BaseClassDecl->hasIrrelevantDestructor())
5199       continue;
5200 
5201     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5202     assert(Dtor && "No dtor found for BaseClassDecl!");
5203     if (CheckDestructorAccess(
5204             ClassDecl->getLocation(), Dtor,
5205             PDiag(diag::err_access_dtor_vbase)
5206                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5207             Context.getTypeDeclType(ClassDecl)) ==
5208         AR_accessible) {
5209       CheckDerivedToBaseConversion(
5210           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5211           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5212           SourceRange(), DeclarationName(), nullptr);
5213     }
5214 
5215     MarkFunctionReferenced(Location, Dtor);
5216     DiagnoseUseOfDecl(Dtor, Location);
5217   }
5218 }
5219 
5220 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5221   if (!CDtorDecl)
5222     return;
5223 
5224   if (CXXConstructorDecl *Constructor
5225       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5226     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5227     DiagnoseUninitializedFields(*this, Constructor);
5228   }
5229 }
5230 
5231 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5232   if (!getLangOpts().CPlusPlus)
5233     return false;
5234 
5235   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5236   if (!RD)
5237     return false;
5238 
5239   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5240   // class template specialization here, but doing so breaks a lot of code.
5241 
5242   // We can't answer whether something is abstract until it has a
5243   // definition. If it's currently being defined, we'll walk back
5244   // over all the declarations when we have a full definition.
5245   const CXXRecordDecl *Def = RD->getDefinition();
5246   if (!Def || Def->isBeingDefined())
5247     return false;
5248 
5249   return RD->isAbstract();
5250 }
5251 
5252 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5253                                   TypeDiagnoser &Diagnoser) {
5254   if (!isAbstractType(Loc, T))
5255     return false;
5256 
5257   T = Context.getBaseElementType(T);
5258   Diagnoser.diagnose(*this, Loc, T);
5259   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5260   return true;
5261 }
5262 
5263 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5264   // Check if we've already emitted the list of pure virtual functions
5265   // for this class.
5266   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5267     return;
5268 
5269   // If the diagnostic is suppressed, don't emit the notes. We're only
5270   // going to emit them once, so try to attach them to a diagnostic we're
5271   // actually going to show.
5272   if (Diags.isLastDiagnosticIgnored())
5273     return;
5274 
5275   CXXFinalOverriderMap FinalOverriders;
5276   RD->getFinalOverriders(FinalOverriders);
5277 
5278   // Keep a set of seen pure methods so we won't diagnose the same method
5279   // more than once.
5280   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5281 
5282   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5283                                    MEnd = FinalOverriders.end();
5284        M != MEnd;
5285        ++M) {
5286     for (OverridingMethods::iterator SO = M->second.begin(),
5287                                   SOEnd = M->second.end();
5288          SO != SOEnd; ++SO) {
5289       // C++ [class.abstract]p4:
5290       //   A class is abstract if it contains or inherits at least one
5291       //   pure virtual function for which the final overrider is pure
5292       //   virtual.
5293 
5294       //
5295       if (SO->second.size() != 1)
5296         continue;
5297 
5298       if (!SO->second.front().Method->isPure())
5299         continue;
5300 
5301       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5302         continue;
5303 
5304       Diag(SO->second.front().Method->getLocation(),
5305            diag::note_pure_virtual_function)
5306         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5307     }
5308   }
5309 
5310   if (!PureVirtualClassDiagSet)
5311     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5312   PureVirtualClassDiagSet->insert(RD);
5313 }
5314 
5315 namespace {
5316 struct AbstractUsageInfo {
5317   Sema &S;
5318   CXXRecordDecl *Record;
5319   CanQualType AbstractType;
5320   bool Invalid;
5321 
5322   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5323     : S(S), Record(Record),
5324       AbstractType(S.Context.getCanonicalType(
5325                    S.Context.getTypeDeclType(Record))),
5326       Invalid(false) {}
5327 
5328   void DiagnoseAbstractType() {
5329     if (Invalid) return;
5330     S.DiagnoseAbstractType(Record);
5331     Invalid = true;
5332   }
5333 
5334   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5335 };
5336 
5337 struct CheckAbstractUsage {
5338   AbstractUsageInfo &Info;
5339   const NamedDecl *Ctx;
5340 
5341   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5342     : Info(Info), Ctx(Ctx) {}
5343 
5344   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5345     switch (TL.getTypeLocClass()) {
5346 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5347 #define TYPELOC(CLASS, PARENT) \
5348     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5349 #include "clang/AST/TypeLocNodes.def"
5350     }
5351   }
5352 
5353   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5354     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5355     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5356       if (!TL.getParam(I))
5357         continue;
5358 
5359       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5360       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5361     }
5362   }
5363 
5364   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5365     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5366   }
5367 
5368   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5369     // Visit the type parameters from a permissive context.
5370     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5371       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5372       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5373         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5374           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5375       // TODO: other template argument types?
5376     }
5377   }
5378 
5379   // Visit pointee types from a permissive context.
5380 #define CheckPolymorphic(Type) \
5381   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5382     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5383   }
5384   CheckPolymorphic(PointerTypeLoc)
5385   CheckPolymorphic(ReferenceTypeLoc)
5386   CheckPolymorphic(MemberPointerTypeLoc)
5387   CheckPolymorphic(BlockPointerTypeLoc)
5388   CheckPolymorphic(AtomicTypeLoc)
5389 
5390   /// Handle all the types we haven't given a more specific
5391   /// implementation for above.
5392   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5393     // Every other kind of type that we haven't called out already
5394     // that has an inner type is either (1) sugar or (2) contains that
5395     // inner type in some way as a subobject.
5396     if (TypeLoc Next = TL.getNextTypeLoc())
5397       return Visit(Next, Sel);
5398 
5399     // If there's no inner type and we're in a permissive context,
5400     // don't diagnose.
5401     if (Sel == Sema::AbstractNone) return;
5402 
5403     // Check whether the type matches the abstract type.
5404     QualType T = TL.getType();
5405     if (T->isArrayType()) {
5406       Sel = Sema::AbstractArrayType;
5407       T = Info.S.Context.getBaseElementType(T);
5408     }
5409     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5410     if (CT != Info.AbstractType) return;
5411 
5412     // It matched; do some magic.
5413     if (Sel == Sema::AbstractArrayType) {
5414       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5415         << T << TL.getSourceRange();
5416     } else {
5417       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5418         << Sel << T << TL.getSourceRange();
5419     }
5420     Info.DiagnoseAbstractType();
5421   }
5422 };
5423 
5424 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5425                                   Sema::AbstractDiagSelID Sel) {
5426   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5427 }
5428 
5429 }
5430 
5431 /// Check for invalid uses of an abstract type in a method declaration.
5432 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5433                                     CXXMethodDecl *MD) {
5434   // No need to do the check on definitions, which require that
5435   // the return/param types be complete.
5436   if (MD->doesThisDeclarationHaveABody())
5437     return;
5438 
5439   // For safety's sake, just ignore it if we don't have type source
5440   // information.  This should never happen for non-implicit methods,
5441   // but...
5442   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5443     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5444 }
5445 
5446 /// Check for invalid uses of an abstract type within a class definition.
5447 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5448                                     CXXRecordDecl *RD) {
5449   for (auto *D : RD->decls()) {
5450     if (D->isImplicit()) continue;
5451 
5452     // Methods and method templates.
5453     if (isa<CXXMethodDecl>(D)) {
5454       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5455     } else if (isa<FunctionTemplateDecl>(D)) {
5456       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5457       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5458 
5459     // Fields and static variables.
5460     } else if (isa<FieldDecl>(D)) {
5461       FieldDecl *FD = cast<FieldDecl>(D);
5462       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5463         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5464     } else if (isa<VarDecl>(D)) {
5465       VarDecl *VD = cast<VarDecl>(D);
5466       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5467         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5468 
5469     // Nested classes and class templates.
5470     } else if (isa<CXXRecordDecl>(D)) {
5471       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5472     } else if (isa<ClassTemplateDecl>(D)) {
5473       CheckAbstractClassUsage(Info,
5474                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5475     }
5476   }
5477 }
5478 
5479 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5480   Attr *ClassAttr = getDLLAttr(Class);
5481   if (!ClassAttr)
5482     return;
5483 
5484   assert(ClassAttr->getKind() == attr::DLLExport);
5485 
5486   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5487 
5488   if (TSK == TSK_ExplicitInstantiationDeclaration)
5489     // Don't go any further if this is just an explicit instantiation
5490     // declaration.
5491     return;
5492 
5493   for (Decl *Member : Class->decls()) {
5494     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5495     if (!MD)
5496       continue;
5497 
5498     if (Member->getAttr<DLLExportAttr>()) {
5499       if (MD->isUserProvided()) {
5500         // Instantiate non-default class member functions ...
5501 
5502         // .. except for certain kinds of template specializations.
5503         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5504           continue;
5505 
5506         S.MarkFunctionReferenced(Class->getLocation(), MD);
5507 
5508         // The function will be passed to the consumer when its definition is
5509         // encountered.
5510       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5511                  MD->isCopyAssignmentOperator() ||
5512                  MD->isMoveAssignmentOperator()) {
5513         // Synthesize and instantiate non-trivial implicit methods, explicitly
5514         // defaulted methods, and the copy and move assignment operators. The
5515         // latter are exported even if they are trivial, because the address of
5516         // an operator can be taken and should compare equal across libraries.
5517         DiagnosticErrorTrap Trap(S.Diags);
5518         S.MarkFunctionReferenced(Class->getLocation(), MD);
5519         if (Trap.hasErrorOccurred()) {
5520           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5521               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5522           break;
5523         }
5524 
5525         // There is no later point when we will see the definition of this
5526         // function, so pass it to the consumer now.
5527         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5528       }
5529     }
5530   }
5531 }
5532 
5533 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5534                                                         CXXRecordDecl *Class) {
5535   // Only the MS ABI has default constructor closures, so we don't need to do
5536   // this semantic checking anywhere else.
5537   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5538     return;
5539 
5540   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5541   for (Decl *Member : Class->decls()) {
5542     // Look for exported default constructors.
5543     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5544     if (!CD || !CD->isDefaultConstructor())
5545       continue;
5546     auto *Attr = CD->getAttr<DLLExportAttr>();
5547     if (!Attr)
5548       continue;
5549 
5550     // If the class is non-dependent, mark the default arguments as ODR-used so
5551     // that we can properly codegen the constructor closure.
5552     if (!Class->isDependentContext()) {
5553       for (ParmVarDecl *PD : CD->parameters()) {
5554         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5555         S.DiscardCleanupsInEvaluationContext();
5556       }
5557     }
5558 
5559     if (LastExportedDefaultCtor) {
5560       S.Diag(LastExportedDefaultCtor->getLocation(),
5561              diag::err_attribute_dll_ambiguous_default_ctor)
5562           << Class;
5563       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5564           << CD->getDeclName();
5565       return;
5566     }
5567     LastExportedDefaultCtor = CD;
5568   }
5569 }
5570 
5571 /// \brief Check class-level dllimport/dllexport attribute.
5572 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5573   Attr *ClassAttr = getDLLAttr(Class);
5574 
5575   // MSVC inherits DLL attributes to partial class template specializations.
5576   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5577     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5578       if (Attr *TemplateAttr =
5579               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5580         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5581         A->setInherited(true);
5582         ClassAttr = A;
5583       }
5584     }
5585   }
5586 
5587   if (!ClassAttr)
5588     return;
5589 
5590   if (!Class->isExternallyVisible()) {
5591     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5592         << Class << ClassAttr;
5593     return;
5594   }
5595 
5596   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5597       !ClassAttr->isInherited()) {
5598     // Diagnose dll attributes on members of class with dll attribute.
5599     for (Decl *Member : Class->decls()) {
5600       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5601         continue;
5602       InheritableAttr *MemberAttr = getDLLAttr(Member);
5603       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5604         continue;
5605 
5606       Diag(MemberAttr->getLocation(),
5607              diag::err_attribute_dll_member_of_dll_class)
5608           << MemberAttr << ClassAttr;
5609       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5610       Member->setInvalidDecl();
5611     }
5612   }
5613 
5614   if (Class->getDescribedClassTemplate())
5615     // Don't inherit dll attribute until the template is instantiated.
5616     return;
5617 
5618   // The class is either imported or exported.
5619   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5620 
5621   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5622 
5623   // Ignore explicit dllexport on explicit class template instantiation declarations.
5624   if (ClassExported && !ClassAttr->isInherited() &&
5625       TSK == TSK_ExplicitInstantiationDeclaration) {
5626     Class->dropAttr<DLLExportAttr>();
5627     return;
5628   }
5629 
5630   // Force declaration of implicit members so they can inherit the attribute.
5631   ForceDeclarationOfImplicitMembers(Class);
5632 
5633   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5634   // seem to be true in practice?
5635 
5636   for (Decl *Member : Class->decls()) {
5637     VarDecl *VD = dyn_cast<VarDecl>(Member);
5638     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5639 
5640     // Only methods and static fields inherit the attributes.
5641     if (!VD && !MD)
5642       continue;
5643 
5644     if (MD) {
5645       // Don't process deleted methods.
5646       if (MD->isDeleted())
5647         continue;
5648 
5649       if (MD->isInlined()) {
5650         // MinGW does not import or export inline methods.
5651         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5652             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5653           continue;
5654 
5655         // MSVC versions before 2015 don't export the move assignment operators
5656         // and move constructor, so don't attempt to import/export them if
5657         // we have a definition.
5658         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5659         if ((MD->isMoveAssignmentOperator() ||
5660              (Ctor && Ctor->isMoveConstructor())) &&
5661             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5662           continue;
5663 
5664         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5665         // operator is exported anyway.
5666         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5667             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5668           continue;
5669       }
5670     }
5671 
5672     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5673       continue;
5674 
5675     if (!getDLLAttr(Member)) {
5676       auto *NewAttr =
5677           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5678       NewAttr->setInherited(true);
5679       Member->addAttr(NewAttr);
5680     }
5681   }
5682 
5683   if (ClassExported)
5684     DelayedDllExportClasses.push_back(Class);
5685 }
5686 
5687 /// \brief Perform propagation of DLL attributes from a derived class to a
5688 /// templated base class for MS compatibility.
5689 void Sema::propagateDLLAttrToBaseClassTemplate(
5690     CXXRecordDecl *Class, Attr *ClassAttr,
5691     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5692   if (getDLLAttr(
5693           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5694     // If the base class template has a DLL attribute, don't try to change it.
5695     return;
5696   }
5697 
5698   auto TSK = BaseTemplateSpec->getSpecializationKind();
5699   if (!getDLLAttr(BaseTemplateSpec) &&
5700       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5701        TSK == TSK_ImplicitInstantiation)) {
5702     // The template hasn't been instantiated yet (or it has, but only as an
5703     // explicit instantiation declaration or implicit instantiation, which means
5704     // we haven't codegenned any members yet), so propagate the attribute.
5705     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5706     NewAttr->setInherited(true);
5707     BaseTemplateSpec->addAttr(NewAttr);
5708 
5709     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5710     // needs to be run again to work see the new attribute. Otherwise this will
5711     // get run whenever the template is instantiated.
5712     if (TSK != TSK_Undeclared)
5713       checkClassLevelDLLAttribute(BaseTemplateSpec);
5714 
5715     return;
5716   }
5717 
5718   if (getDLLAttr(BaseTemplateSpec)) {
5719     // The template has already been specialized or instantiated with an
5720     // attribute, explicitly or through propagation. We should not try to change
5721     // it.
5722     return;
5723   }
5724 
5725   // The template was previously instantiated or explicitly specialized without
5726   // a dll attribute, It's too late for us to add an attribute, so warn that
5727   // this is unsupported.
5728   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5729       << BaseTemplateSpec->isExplicitSpecialization();
5730   Diag(ClassAttr->getLocation(), diag::note_attribute);
5731   if (BaseTemplateSpec->isExplicitSpecialization()) {
5732     Diag(BaseTemplateSpec->getLocation(),
5733            diag::note_template_class_explicit_specialization_was_here)
5734         << BaseTemplateSpec;
5735   } else {
5736     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5737            diag::note_template_class_instantiation_was_here)
5738         << BaseTemplateSpec;
5739   }
5740 }
5741 
5742 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5743                                         SourceLocation DefaultLoc) {
5744   switch (S.getSpecialMember(MD)) {
5745   case Sema::CXXDefaultConstructor:
5746     S.DefineImplicitDefaultConstructor(DefaultLoc,
5747                                        cast<CXXConstructorDecl>(MD));
5748     break;
5749   case Sema::CXXCopyConstructor:
5750     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5751     break;
5752   case Sema::CXXCopyAssignment:
5753     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5754     break;
5755   case Sema::CXXDestructor:
5756     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5757     break;
5758   case Sema::CXXMoveConstructor:
5759     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5760     break;
5761   case Sema::CXXMoveAssignment:
5762     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5763     break;
5764   case Sema::CXXInvalid:
5765     llvm_unreachable("Invalid special member.");
5766   }
5767 }
5768 
5769 /// Determine whether a type is permitted to be passed or returned in
5770 /// registers, per C++ [class.temporary]p3.
5771 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) {
5772   if (D->isDependentType() || D->isInvalidDecl())
5773     return false;
5774 
5775   // Per C++ [class.temporary]p3, the relevant condition is:
5776   //   each copy constructor, move constructor, and destructor of X is
5777   //   either trivial or deleted, and X has at least one non-deleted copy
5778   //   or move constructor
5779   bool HasNonDeletedCopyOrMove = false;
5780 
5781   if (D->needsImplicitCopyConstructor() &&
5782       !D->defaultedCopyConstructorIsDeleted()) {
5783     if (!D->hasTrivialCopyConstructorForCall())
5784       return false;
5785     HasNonDeletedCopyOrMove = true;
5786   }
5787 
5788   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5789       !D->defaultedMoveConstructorIsDeleted()) {
5790     if (!D->hasTrivialMoveConstructorForCall())
5791       return false;
5792     HasNonDeletedCopyOrMove = true;
5793   }
5794 
5795   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5796       !D->hasTrivialDestructorForCall())
5797     return false;
5798 
5799   for (const CXXMethodDecl *MD : D->methods()) {
5800     if (MD->isDeleted())
5801       continue;
5802 
5803     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5804     if (CD && CD->isCopyOrMoveConstructor())
5805       HasNonDeletedCopyOrMove = true;
5806     else if (!isa<CXXDestructorDecl>(MD))
5807       continue;
5808 
5809     if (!MD->isTrivialForCall())
5810       return false;
5811   }
5812 
5813   return HasNonDeletedCopyOrMove;
5814 }
5815 
5816 /// \brief Perform semantic checks on a class definition that has been
5817 /// completing, introducing implicitly-declared members, checking for
5818 /// abstract types, etc.
5819 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5820   if (!Record)
5821     return;
5822 
5823   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5824     AbstractUsageInfo Info(*this, Record);
5825     CheckAbstractClassUsage(Info, Record);
5826   }
5827 
5828   // If this is not an aggregate type and has no user-declared constructor,
5829   // complain about any non-static data members of reference or const scalar
5830   // type, since they will never get initializers.
5831   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5832       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5833       !Record->isLambda()) {
5834     bool Complained = false;
5835     for (const auto *F : Record->fields()) {
5836       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5837         continue;
5838 
5839       if (F->getType()->isReferenceType() ||
5840           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5841         if (!Complained) {
5842           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5843             << Record->getTagKind() << Record;
5844           Complained = true;
5845         }
5846 
5847         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5848           << F->getType()->isReferenceType()
5849           << F->getDeclName();
5850       }
5851     }
5852   }
5853 
5854   if (Record->getIdentifier()) {
5855     // C++ [class.mem]p13:
5856     //   If T is the name of a class, then each of the following shall have a
5857     //   name different from T:
5858     //     - every member of every anonymous union that is a member of class T.
5859     //
5860     // C++ [class.mem]p14:
5861     //   In addition, if class T has a user-declared constructor (12.1), every
5862     //   non-static data member of class T shall have a name different from T.
5863     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5864     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5865          ++I) {
5866       NamedDecl *D = *I;
5867       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5868           isa<IndirectFieldDecl>(D)) {
5869         Diag(D->getLocation(), diag::err_member_name_of_class)
5870           << D->getDeclName();
5871         break;
5872       }
5873     }
5874   }
5875 
5876   // Warn if the class has virtual methods but non-virtual public destructor.
5877   if (Record->isPolymorphic() && !Record->isDependentType()) {
5878     CXXDestructorDecl *dtor = Record->getDestructor();
5879     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5880         !Record->hasAttr<FinalAttr>())
5881       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5882            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5883   }
5884 
5885   if (Record->isAbstract()) {
5886     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5887       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5888         << FA->isSpelledAsSealed();
5889       DiagnoseAbstractType(Record);
5890     }
5891   }
5892 
5893   // Set HasTrivialSpecialMemberForCall if the record has attribute
5894   // "trivial_abi".
5895   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
5896 
5897   if (HasTrivialABI)
5898     Record->setHasTrivialSpecialMemberForCall();
5899 
5900   bool HasMethodWithOverrideControl = false,
5901        HasOverridingMethodWithoutOverrideControl = false;
5902   if (!Record->isDependentType()) {
5903     for (auto *M : Record->methods()) {
5904       // See if a method overloads virtual methods in a base
5905       // class without overriding any.
5906       if (!M->isStatic())
5907         DiagnoseHiddenVirtualMethods(M);
5908       if (M->hasAttr<OverrideAttr>())
5909         HasMethodWithOverrideControl = true;
5910       else if (M->size_overridden_methods() > 0)
5911         HasOverridingMethodWithoutOverrideControl = true;
5912       // Check whether the explicitly-defaulted special members are valid.
5913       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5914         CheckExplicitlyDefaultedSpecialMember(M);
5915 
5916       // For an explicitly defaulted or deleted special member, we defer
5917       // determining triviality until the class is complete. That time is now!
5918       CXXSpecialMember CSM = getSpecialMember(M);
5919       if (!M->isImplicit() && !M->isUserProvided()) {
5920         if (CSM != CXXInvalid) {
5921           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5922           // Inform the class that we've finished declaring this member.
5923           Record->finishedDefaultedOrDeletedMember(M);
5924           M->setTrivialForCall(
5925               HasTrivialABI ||
5926               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
5927           Record->setTrivialForCallFlags(M);
5928         }
5929       }
5930 
5931       // Set triviality for the purpose of calls if this is a user-provided
5932       // copy/move constructor or destructor.
5933       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
5934            CSM == CXXDestructor) && M->isUserProvided()) {
5935         M->setTrivialForCall(HasTrivialABI);
5936         Record->setTrivialForCallFlags(M);
5937       }
5938 
5939       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5940           M->hasAttr<DLLExportAttr>()) {
5941         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5942             M->isTrivial() &&
5943             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5944              CSM == CXXDestructor))
5945           M->dropAttr<DLLExportAttr>();
5946 
5947         if (M->hasAttr<DLLExportAttr>()) {
5948           DefineImplicitSpecialMember(*this, M, M->getLocation());
5949           ActOnFinishInlineFunctionDef(M);
5950         }
5951       }
5952     }
5953   }
5954 
5955   if (HasMethodWithOverrideControl &&
5956       HasOverridingMethodWithoutOverrideControl) {
5957     // At least one method has the 'override' control declared.
5958     // Diagnose all other overridden methods which do not have 'override' specified on them.
5959     for (auto *M : Record->methods())
5960       DiagnoseAbsenceOfOverrideControl(M);
5961   }
5962 
5963   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5964   // whether this class uses any C++ features that are implemented
5965   // completely differently in MSVC, and if so, emit a diagnostic.
5966   // That diagnostic defaults to an error, but we allow projects to
5967   // map it down to a warning (or ignore it).  It's a fairly common
5968   // practice among users of the ms_struct pragma to mass-annotate
5969   // headers, sweeping up a bunch of types that the project doesn't
5970   // really rely on MSVC-compatible layout for.  We must therefore
5971   // support "ms_struct except for C++ stuff" as a secondary ABI.
5972   if (Record->isMsStruct(Context) &&
5973       (Record->isPolymorphic() || Record->getNumBases())) {
5974     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5975   }
5976 
5977   checkClassLevelDLLAttribute(Record);
5978 
5979   Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record));
5980 }
5981 
5982 /// Look up the special member function that would be called by a special
5983 /// member function for a subobject of class type.
5984 ///
5985 /// \param Class The class type of the subobject.
5986 /// \param CSM The kind of special member function.
5987 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5988 /// \param ConstRHS True if this is a copy operation with a const object
5989 ///        on its RHS, that is, if the argument to the outer special member
5990 ///        function is 'const' and this is not a field marked 'mutable'.
5991 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
5992     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5993     unsigned FieldQuals, bool ConstRHS) {
5994   unsigned LHSQuals = 0;
5995   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5996     LHSQuals = FieldQuals;
5997 
5998   unsigned RHSQuals = FieldQuals;
5999   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6000     RHSQuals = 0;
6001   else if (ConstRHS)
6002     RHSQuals |= Qualifiers::Const;
6003 
6004   return S.LookupSpecialMember(Class, CSM,
6005                                RHSQuals & Qualifiers::Const,
6006                                RHSQuals & Qualifiers::Volatile,
6007                                false,
6008                                LHSQuals & Qualifiers::Const,
6009                                LHSQuals & Qualifiers::Volatile);
6010 }
6011 
6012 class Sema::InheritedConstructorInfo {
6013   Sema &S;
6014   SourceLocation UseLoc;
6015 
6016   /// A mapping from the base classes through which the constructor was
6017   /// inherited to the using shadow declaration in that base class (or a null
6018   /// pointer if the constructor was declared in that base class).
6019   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6020       InheritedFromBases;
6021 
6022 public:
6023   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6024                            ConstructorUsingShadowDecl *Shadow)
6025       : S(S), UseLoc(UseLoc) {
6026     bool DiagnosedMultipleConstructedBases = false;
6027     CXXRecordDecl *ConstructedBase = nullptr;
6028     UsingDecl *ConstructedBaseUsing = nullptr;
6029 
6030     // Find the set of such base class subobjects and check that there's a
6031     // unique constructed subobject.
6032     for (auto *D : Shadow->redecls()) {
6033       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6034       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6035       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6036 
6037       InheritedFromBases.insert(
6038           std::make_pair(DNominatedBase->getCanonicalDecl(),
6039                          DShadow->getNominatedBaseClassShadowDecl()));
6040       if (DShadow->constructsVirtualBase())
6041         InheritedFromBases.insert(
6042             std::make_pair(DConstructedBase->getCanonicalDecl(),
6043                            DShadow->getConstructedBaseClassShadowDecl()));
6044       else
6045         assert(DNominatedBase == DConstructedBase);
6046 
6047       // [class.inhctor.init]p2:
6048       //   If the constructor was inherited from multiple base class subobjects
6049       //   of type B, the program is ill-formed.
6050       if (!ConstructedBase) {
6051         ConstructedBase = DConstructedBase;
6052         ConstructedBaseUsing = D->getUsingDecl();
6053       } else if (ConstructedBase != DConstructedBase &&
6054                  !Shadow->isInvalidDecl()) {
6055         if (!DiagnosedMultipleConstructedBases) {
6056           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6057               << Shadow->getTargetDecl();
6058           S.Diag(ConstructedBaseUsing->getLocation(),
6059                diag::note_ambiguous_inherited_constructor_using)
6060               << ConstructedBase;
6061           DiagnosedMultipleConstructedBases = true;
6062         }
6063         S.Diag(D->getUsingDecl()->getLocation(),
6064                diag::note_ambiguous_inherited_constructor_using)
6065             << DConstructedBase;
6066       }
6067     }
6068 
6069     if (DiagnosedMultipleConstructedBases)
6070       Shadow->setInvalidDecl();
6071   }
6072 
6073   /// Find the constructor to use for inherited construction of a base class,
6074   /// and whether that base class constructor inherits the constructor from a
6075   /// virtual base class (in which case it won't actually invoke it).
6076   std::pair<CXXConstructorDecl *, bool>
6077   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6078     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6079     if (It == InheritedFromBases.end())
6080       return std::make_pair(nullptr, false);
6081 
6082     // This is an intermediary class.
6083     if (It->second)
6084       return std::make_pair(
6085           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6086           It->second->constructsVirtualBase());
6087 
6088     // This is the base class from which the constructor was inherited.
6089     return std::make_pair(Ctor, false);
6090   }
6091 };
6092 
6093 /// Is the special member function which would be selected to perform the
6094 /// specified operation on the specified class type a constexpr constructor?
6095 static bool
6096 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6097                          Sema::CXXSpecialMember CSM, unsigned Quals,
6098                          bool ConstRHS,
6099                          CXXConstructorDecl *InheritedCtor = nullptr,
6100                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6101   // If we're inheriting a constructor, see if we need to call it for this base
6102   // class.
6103   if (InheritedCtor) {
6104     assert(CSM == Sema::CXXDefaultConstructor);
6105     auto BaseCtor =
6106         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6107     if (BaseCtor)
6108       return BaseCtor->isConstexpr();
6109   }
6110 
6111   if (CSM == Sema::CXXDefaultConstructor)
6112     return ClassDecl->hasConstexprDefaultConstructor();
6113 
6114   Sema::SpecialMemberOverloadResult SMOR =
6115       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6116   if (!SMOR.getMethod())
6117     // A constructor we wouldn't select can't be "involved in initializing"
6118     // anything.
6119     return true;
6120   return SMOR.getMethod()->isConstexpr();
6121 }
6122 
6123 /// Determine whether the specified special member function would be constexpr
6124 /// if it were implicitly defined.
6125 static bool defaultedSpecialMemberIsConstexpr(
6126     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6127     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6128     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6129   if (!S.getLangOpts().CPlusPlus11)
6130     return false;
6131 
6132   // C++11 [dcl.constexpr]p4:
6133   // In the definition of a constexpr constructor [...]
6134   bool Ctor = true;
6135   switch (CSM) {
6136   case Sema::CXXDefaultConstructor:
6137     if (Inherited)
6138       break;
6139     // Since default constructor lookup is essentially trivial (and cannot
6140     // involve, for instance, template instantiation), we compute whether a
6141     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6142     //
6143     // This is important for performance; we need to know whether the default
6144     // constructor is constexpr to determine whether the type is a literal type.
6145     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6146 
6147   case Sema::CXXCopyConstructor:
6148   case Sema::CXXMoveConstructor:
6149     // For copy or move constructors, we need to perform overload resolution.
6150     break;
6151 
6152   case Sema::CXXCopyAssignment:
6153   case Sema::CXXMoveAssignment:
6154     if (!S.getLangOpts().CPlusPlus14)
6155       return false;
6156     // In C++1y, we need to perform overload resolution.
6157     Ctor = false;
6158     break;
6159 
6160   case Sema::CXXDestructor:
6161   case Sema::CXXInvalid:
6162     return false;
6163   }
6164 
6165   //   -- if the class is a non-empty union, or for each non-empty anonymous
6166   //      union member of a non-union class, exactly one non-static data member
6167   //      shall be initialized; [DR1359]
6168   //
6169   // If we squint, this is guaranteed, since exactly one non-static data member
6170   // will be initialized (if the constructor isn't deleted), we just don't know
6171   // which one.
6172   if (Ctor && ClassDecl->isUnion())
6173     return CSM == Sema::CXXDefaultConstructor
6174                ? ClassDecl->hasInClassInitializer() ||
6175                      !ClassDecl->hasVariantMembers()
6176                : true;
6177 
6178   //   -- the class shall not have any virtual base classes;
6179   if (Ctor && ClassDecl->getNumVBases())
6180     return false;
6181 
6182   // C++1y [class.copy]p26:
6183   //   -- [the class] is a literal type, and
6184   if (!Ctor && !ClassDecl->isLiteral())
6185     return false;
6186 
6187   //   -- every constructor involved in initializing [...] base class
6188   //      sub-objects shall be a constexpr constructor;
6189   //   -- the assignment operator selected to copy/move each direct base
6190   //      class is a constexpr function, and
6191   for (const auto &B : ClassDecl->bases()) {
6192     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6193     if (!BaseType) continue;
6194 
6195     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6196     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6197                                   InheritedCtor, Inherited))
6198       return false;
6199   }
6200 
6201   //   -- every constructor involved in initializing non-static data members
6202   //      [...] shall be a constexpr constructor;
6203   //   -- every non-static data member and base class sub-object shall be
6204   //      initialized
6205   //   -- for each non-static data member of X that is of class type (or array
6206   //      thereof), the assignment operator selected to copy/move that member is
6207   //      a constexpr function
6208   for (const auto *F : ClassDecl->fields()) {
6209     if (F->isInvalidDecl())
6210       continue;
6211     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6212       continue;
6213     QualType BaseType = S.Context.getBaseElementType(F->getType());
6214     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6215       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6216       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6217                                     BaseType.getCVRQualifiers(),
6218                                     ConstArg && !F->isMutable()))
6219         return false;
6220     } else if (CSM == Sema::CXXDefaultConstructor) {
6221       return false;
6222     }
6223   }
6224 
6225   // All OK, it's constexpr!
6226   return true;
6227 }
6228 
6229 static Sema::ImplicitExceptionSpecification
6230 ComputeDefaultedSpecialMemberExceptionSpec(
6231     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6232     Sema::InheritedConstructorInfo *ICI);
6233 
6234 static Sema::ImplicitExceptionSpecification
6235 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6236   auto CSM = S.getSpecialMember(MD);
6237   if (CSM != Sema::CXXInvalid)
6238     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6239 
6240   auto *CD = cast<CXXConstructorDecl>(MD);
6241   assert(CD->getInheritedConstructor() &&
6242          "only special members have implicit exception specs");
6243   Sema::InheritedConstructorInfo ICI(
6244       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6245   return ComputeDefaultedSpecialMemberExceptionSpec(
6246       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6247 }
6248 
6249 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6250                                                             CXXMethodDecl *MD) {
6251   FunctionProtoType::ExtProtoInfo EPI;
6252 
6253   // Build an exception specification pointing back at this member.
6254   EPI.ExceptionSpec.Type = EST_Unevaluated;
6255   EPI.ExceptionSpec.SourceDecl = MD;
6256 
6257   // Set the calling convention to the default for C++ instance methods.
6258   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6259       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6260                                             /*IsCXXMethod=*/true));
6261   return EPI;
6262 }
6263 
6264 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6265   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6266   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6267     return;
6268 
6269   // Evaluate the exception specification.
6270   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6271   auto ESI = IES.getExceptionSpec();
6272 
6273   // Update the type of the special member to use it.
6274   UpdateExceptionSpec(MD, ESI);
6275 
6276   // A user-provided destructor can be defined outside the class. When that
6277   // happens, be sure to update the exception specification on both
6278   // declarations.
6279   const FunctionProtoType *CanonicalFPT =
6280     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6281   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6282     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6283 }
6284 
6285 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6286   CXXRecordDecl *RD = MD->getParent();
6287   CXXSpecialMember CSM = getSpecialMember(MD);
6288 
6289   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6290          "not an explicitly-defaulted special member");
6291 
6292   // Whether this was the first-declared instance of the constructor.
6293   // This affects whether we implicitly add an exception spec and constexpr.
6294   bool First = MD == MD->getCanonicalDecl();
6295 
6296   bool HadError = false;
6297 
6298   // C++11 [dcl.fct.def.default]p1:
6299   //   A function that is explicitly defaulted shall
6300   //     -- be a special member function (checked elsewhere),
6301   //     -- have the same type (except for ref-qualifiers, and except that a
6302   //        copy operation can take a non-const reference) as an implicit
6303   //        declaration, and
6304   //     -- not have default arguments.
6305   unsigned ExpectedParams = 1;
6306   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6307     ExpectedParams = 0;
6308   if (MD->getNumParams() != ExpectedParams) {
6309     // This also checks for default arguments: a copy or move constructor with a
6310     // default argument is classified as a default constructor, and assignment
6311     // operations and destructors can't have default arguments.
6312     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6313       << CSM << MD->getSourceRange();
6314     HadError = true;
6315   } else if (MD->isVariadic()) {
6316     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6317       << CSM << MD->getSourceRange();
6318     HadError = true;
6319   }
6320 
6321   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6322 
6323   bool CanHaveConstParam = false;
6324   if (CSM == CXXCopyConstructor)
6325     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6326   else if (CSM == CXXCopyAssignment)
6327     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6328 
6329   QualType ReturnType = Context.VoidTy;
6330   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6331     // Check for return type matching.
6332     ReturnType = Type->getReturnType();
6333     QualType ExpectedReturnType =
6334         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6335     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6336       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6337         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6338       HadError = true;
6339     }
6340 
6341     // A defaulted special member cannot have cv-qualifiers.
6342     if (Type->getTypeQuals()) {
6343       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6344         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6345       HadError = true;
6346     }
6347   }
6348 
6349   // Check for parameter type matching.
6350   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6351   bool HasConstParam = false;
6352   if (ExpectedParams && ArgType->isReferenceType()) {
6353     // Argument must be reference to possibly-const T.
6354     QualType ReferentType = ArgType->getPointeeType();
6355     HasConstParam = ReferentType.isConstQualified();
6356 
6357     if (ReferentType.isVolatileQualified()) {
6358       Diag(MD->getLocation(),
6359            diag::err_defaulted_special_member_volatile_param) << CSM;
6360       HadError = true;
6361     }
6362 
6363     if (HasConstParam && !CanHaveConstParam) {
6364       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6365         Diag(MD->getLocation(),
6366              diag::err_defaulted_special_member_copy_const_param)
6367           << (CSM == CXXCopyAssignment);
6368         // FIXME: Explain why this special member can't be const.
6369       } else {
6370         Diag(MD->getLocation(),
6371              diag::err_defaulted_special_member_move_const_param)
6372           << (CSM == CXXMoveAssignment);
6373       }
6374       HadError = true;
6375     }
6376   } else if (ExpectedParams) {
6377     // A copy assignment operator can take its argument by value, but a
6378     // defaulted one cannot.
6379     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6380     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6381     HadError = true;
6382   }
6383 
6384   // C++11 [dcl.fct.def.default]p2:
6385   //   An explicitly-defaulted function may be declared constexpr only if it
6386   //   would have been implicitly declared as constexpr,
6387   // Do not apply this rule to members of class templates, since core issue 1358
6388   // makes such functions always instantiate to constexpr functions. For
6389   // functions which cannot be constexpr (for non-constructors in C++11 and for
6390   // destructors in C++1y), this is checked elsewhere.
6391   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6392                                                      HasConstParam);
6393   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6394                                  : isa<CXXConstructorDecl>(MD)) &&
6395       MD->isConstexpr() && !Constexpr &&
6396       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6397     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6398     // FIXME: Explain why the special member can't be constexpr.
6399     HadError = true;
6400   }
6401 
6402   //   and may have an explicit exception-specification only if it is compatible
6403   //   with the exception-specification on the implicit declaration.
6404   if (Type->hasExceptionSpec()) {
6405     // Delay the check if this is the first declaration of the special member,
6406     // since we may not have parsed some necessary in-class initializers yet.
6407     if (First) {
6408       // If the exception specification needs to be instantiated, do so now,
6409       // before we clobber it with an EST_Unevaluated specification below.
6410       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6411         InstantiateExceptionSpec(MD->getLocStart(), MD);
6412         Type = MD->getType()->getAs<FunctionProtoType>();
6413       }
6414       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6415     } else
6416       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6417   }
6418 
6419   //   If a function is explicitly defaulted on its first declaration,
6420   if (First) {
6421     //  -- it is implicitly considered to be constexpr if the implicit
6422     //     definition would be,
6423     MD->setConstexpr(Constexpr);
6424 
6425     //  -- it is implicitly considered to have the same exception-specification
6426     //     as if it had been implicitly declared,
6427     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6428     EPI.ExceptionSpec.Type = EST_Unevaluated;
6429     EPI.ExceptionSpec.SourceDecl = MD;
6430     MD->setType(Context.getFunctionType(ReturnType,
6431                                         llvm::makeArrayRef(&ArgType,
6432                                                            ExpectedParams),
6433                                         EPI));
6434   }
6435 
6436   if (ShouldDeleteSpecialMember(MD, CSM)) {
6437     if (First) {
6438       SetDeclDeleted(MD, MD->getLocation());
6439     } else {
6440       // C++11 [dcl.fct.def.default]p4:
6441       //   [For a] user-provided explicitly-defaulted function [...] if such a
6442       //   function is implicitly defined as deleted, the program is ill-formed.
6443       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6444       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6445       HadError = true;
6446     }
6447   }
6448 
6449   if (HadError)
6450     MD->setInvalidDecl();
6451 }
6452 
6453 /// Check whether the exception specification provided for an
6454 /// explicitly-defaulted special member matches the exception specification
6455 /// that would have been generated for an implicit special member, per
6456 /// C++11 [dcl.fct.def.default]p2.
6457 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6458     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6459   // If the exception specification was explicitly specified but hadn't been
6460   // parsed when the method was defaulted, grab it now.
6461   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6462     SpecifiedType =
6463         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6464 
6465   // Compute the implicit exception specification.
6466   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6467                                                        /*IsCXXMethod=*/true);
6468   FunctionProtoType::ExtProtoInfo EPI(CC);
6469   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6470   EPI.ExceptionSpec = IES.getExceptionSpec();
6471   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6472     Context.getFunctionType(Context.VoidTy, None, EPI));
6473 
6474   // Ensure that it matches.
6475   CheckEquivalentExceptionSpec(
6476     PDiag(diag::err_incorrect_defaulted_exception_spec)
6477       << getSpecialMember(MD), PDiag(),
6478     ImplicitType, SourceLocation(),
6479     SpecifiedType, MD->getLocation());
6480 }
6481 
6482 void Sema::CheckDelayedMemberExceptionSpecs() {
6483   decltype(DelayedExceptionSpecChecks) Checks;
6484   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6485 
6486   std::swap(Checks, DelayedExceptionSpecChecks);
6487   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6488 
6489   // Perform any deferred checking of exception specifications for virtual
6490   // destructors.
6491   for (auto &Check : Checks)
6492     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6493 
6494   // Check that any explicitly-defaulted methods have exception specifications
6495   // compatible with their implicit exception specifications.
6496   for (auto &Spec : Specs)
6497     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6498 }
6499 
6500 namespace {
6501 /// CRTP base class for visiting operations performed by a special member
6502 /// function (or inherited constructor).
6503 template<typename Derived>
6504 struct SpecialMemberVisitor {
6505   Sema &S;
6506   CXXMethodDecl *MD;
6507   Sema::CXXSpecialMember CSM;
6508   Sema::InheritedConstructorInfo *ICI;
6509 
6510   // Properties of the special member, computed for convenience.
6511   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6512 
6513   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6514                        Sema::InheritedConstructorInfo *ICI)
6515       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6516     switch (CSM) {
6517     case Sema::CXXDefaultConstructor:
6518     case Sema::CXXCopyConstructor:
6519     case Sema::CXXMoveConstructor:
6520       IsConstructor = true;
6521       break;
6522     case Sema::CXXCopyAssignment:
6523     case Sema::CXXMoveAssignment:
6524       IsAssignment = true;
6525       break;
6526     case Sema::CXXDestructor:
6527       break;
6528     case Sema::CXXInvalid:
6529       llvm_unreachable("invalid special member kind");
6530     }
6531 
6532     if (MD->getNumParams()) {
6533       if (const ReferenceType *RT =
6534               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6535         ConstArg = RT->getPointeeType().isConstQualified();
6536     }
6537   }
6538 
6539   Derived &getDerived() { return static_cast<Derived&>(*this); }
6540 
6541   /// Is this a "move" special member?
6542   bool isMove() const {
6543     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6544   }
6545 
6546   /// Look up the corresponding special member in the given class.
6547   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6548                                              unsigned Quals, bool IsMutable) {
6549     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6550                                        ConstArg && !IsMutable);
6551   }
6552 
6553   /// Look up the constructor for the specified base class to see if it's
6554   /// overridden due to this being an inherited constructor.
6555   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6556     if (!ICI)
6557       return {};
6558     assert(CSM == Sema::CXXDefaultConstructor);
6559     auto *BaseCtor =
6560       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6561     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6562       return MD;
6563     return {};
6564   }
6565 
6566   /// A base or member subobject.
6567   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6568 
6569   /// Get the location to use for a subobject in diagnostics.
6570   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6571     // FIXME: For an indirect virtual base, the direct base leading to
6572     // the indirect virtual base would be a more useful choice.
6573     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6574       return B->getBaseTypeLoc();
6575     else
6576       return Subobj.get<FieldDecl*>()->getLocation();
6577   }
6578 
6579   enum BasesToVisit {
6580     /// Visit all non-virtual (direct) bases.
6581     VisitNonVirtualBases,
6582     /// Visit all direct bases, virtual or not.
6583     VisitDirectBases,
6584     /// Visit all non-virtual bases, and all virtual bases if the class
6585     /// is not abstract.
6586     VisitPotentiallyConstructedBases,
6587     /// Visit all direct or virtual bases.
6588     VisitAllBases
6589   };
6590 
6591   // Visit the bases and members of the class.
6592   bool visit(BasesToVisit Bases) {
6593     CXXRecordDecl *RD = MD->getParent();
6594 
6595     if (Bases == VisitPotentiallyConstructedBases)
6596       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6597 
6598     for (auto &B : RD->bases())
6599       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6600           getDerived().visitBase(&B))
6601         return true;
6602 
6603     if (Bases == VisitAllBases)
6604       for (auto &B : RD->vbases())
6605         if (getDerived().visitBase(&B))
6606           return true;
6607 
6608     for (auto *F : RD->fields())
6609       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6610           getDerived().visitField(F))
6611         return true;
6612 
6613     return false;
6614   }
6615 };
6616 }
6617 
6618 namespace {
6619 struct SpecialMemberDeletionInfo
6620     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6621   bool Diagnose;
6622 
6623   SourceLocation Loc;
6624 
6625   bool AllFieldsAreConst;
6626 
6627   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6628                             Sema::CXXSpecialMember CSM,
6629                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6630       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6631         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6632 
6633   bool inUnion() const { return MD->getParent()->isUnion(); }
6634 
6635   Sema::CXXSpecialMember getEffectiveCSM() {
6636     return ICI ? Sema::CXXInvalid : CSM;
6637   }
6638 
6639   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6640   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6641 
6642   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6643   bool shouldDeleteForField(FieldDecl *FD);
6644   bool shouldDeleteForAllConstMembers();
6645 
6646   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6647                                      unsigned Quals);
6648   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6649                                     Sema::SpecialMemberOverloadResult SMOR,
6650                                     bool IsDtorCallInCtor);
6651 
6652   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6653 };
6654 }
6655 
6656 /// Is the given special member inaccessible when used on the given
6657 /// sub-object.
6658 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6659                                              CXXMethodDecl *target) {
6660   /// If we're operating on a base class, the object type is the
6661   /// type of this special member.
6662   QualType objectTy;
6663   AccessSpecifier access = target->getAccess();
6664   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6665     objectTy = S.Context.getTypeDeclType(MD->getParent());
6666     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6667 
6668   // If we're operating on a field, the object type is the type of the field.
6669   } else {
6670     objectTy = S.Context.getTypeDeclType(target->getParent());
6671   }
6672 
6673   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6674 }
6675 
6676 /// Check whether we should delete a special member due to the implicit
6677 /// definition containing a call to a special member of a subobject.
6678 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6679     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6680     bool IsDtorCallInCtor) {
6681   CXXMethodDecl *Decl = SMOR.getMethod();
6682   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6683 
6684   int DiagKind = -1;
6685 
6686   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6687     DiagKind = !Decl ? 0 : 1;
6688   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6689     DiagKind = 2;
6690   else if (!isAccessible(Subobj, Decl))
6691     DiagKind = 3;
6692   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6693            !Decl->isTrivial()) {
6694     // A member of a union must have a trivial corresponding special member.
6695     // As a weird special case, a destructor call from a union's constructor
6696     // must be accessible and non-deleted, but need not be trivial. Such a
6697     // destructor is never actually called, but is semantically checked as
6698     // if it were.
6699     DiagKind = 4;
6700   }
6701 
6702   if (DiagKind == -1)
6703     return false;
6704 
6705   if (Diagnose) {
6706     if (Field) {
6707       S.Diag(Field->getLocation(),
6708              diag::note_deleted_special_member_class_subobject)
6709         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6710         << Field << DiagKind << IsDtorCallInCtor;
6711     } else {
6712       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6713       S.Diag(Base->getLocStart(),
6714              diag::note_deleted_special_member_class_subobject)
6715         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6716         << Base->getType() << DiagKind << IsDtorCallInCtor;
6717     }
6718 
6719     if (DiagKind == 1)
6720       S.NoteDeletedFunction(Decl);
6721     // FIXME: Explain inaccessibility if DiagKind == 3.
6722   }
6723 
6724   return true;
6725 }
6726 
6727 /// Check whether we should delete a special member function due to having a
6728 /// direct or virtual base class or non-static data member of class type M.
6729 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6730     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6731   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6732   bool IsMutable = Field && Field->isMutable();
6733 
6734   // C++11 [class.ctor]p5:
6735   // -- any direct or virtual base class, or non-static data member with no
6736   //    brace-or-equal-initializer, has class type M (or array thereof) and
6737   //    either M has no default constructor or overload resolution as applied
6738   //    to M's default constructor results in an ambiguity or in a function
6739   //    that is deleted or inaccessible
6740   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6741   // -- a direct or virtual base class B that cannot be copied/moved because
6742   //    overload resolution, as applied to B's corresponding special member,
6743   //    results in an ambiguity or a function that is deleted or inaccessible
6744   //    from the defaulted special member
6745   // C++11 [class.dtor]p5:
6746   // -- any direct or virtual base class [...] has a type with a destructor
6747   //    that is deleted or inaccessible
6748   if (!(CSM == Sema::CXXDefaultConstructor &&
6749         Field && Field->hasInClassInitializer()) &&
6750       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6751                                    false))
6752     return true;
6753 
6754   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6755   // -- any direct or virtual base class or non-static data member has a
6756   //    type with a destructor that is deleted or inaccessible
6757   if (IsConstructor) {
6758     Sema::SpecialMemberOverloadResult SMOR =
6759         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6760                               false, false, false, false, false);
6761     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6762       return true;
6763   }
6764 
6765   return false;
6766 }
6767 
6768 /// Check whether we should delete a special member function due to the class
6769 /// having a particular direct or virtual base class.
6770 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6771   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6772   // If program is correct, BaseClass cannot be null, but if it is, the error
6773   // must be reported elsewhere.
6774   if (!BaseClass)
6775     return false;
6776   // If we have an inheriting constructor, check whether we're calling an
6777   // inherited constructor instead of a default constructor.
6778   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6779   if (auto *BaseCtor = SMOR.getMethod()) {
6780     // Note that we do not check access along this path; other than that,
6781     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6782     // FIXME: Check that the base has a usable destructor! Sink this into
6783     // shouldDeleteForClassSubobject.
6784     if (BaseCtor->isDeleted() && Diagnose) {
6785       S.Diag(Base->getLocStart(),
6786              diag::note_deleted_special_member_class_subobject)
6787         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6788         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6789       S.NoteDeletedFunction(BaseCtor);
6790     }
6791     return BaseCtor->isDeleted();
6792   }
6793   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6794 }
6795 
6796 /// Check whether we should delete a special member function due to the class
6797 /// having a particular non-static data member.
6798 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6799   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6800   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6801 
6802   if (CSM == Sema::CXXDefaultConstructor) {
6803     // For a default constructor, all references must be initialized in-class
6804     // and, if a union, it must have a non-const member.
6805     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6806       if (Diagnose)
6807         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6808           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6809       return true;
6810     }
6811     // C++11 [class.ctor]p5: any non-variant non-static data member of
6812     // const-qualified type (or array thereof) with no
6813     // brace-or-equal-initializer does not have a user-provided default
6814     // constructor.
6815     if (!inUnion() && FieldType.isConstQualified() &&
6816         !FD->hasInClassInitializer() &&
6817         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6818       if (Diagnose)
6819         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6820           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6821       return true;
6822     }
6823 
6824     if (inUnion() && !FieldType.isConstQualified())
6825       AllFieldsAreConst = false;
6826   } else if (CSM == Sema::CXXCopyConstructor) {
6827     // For a copy constructor, data members must not be of rvalue reference
6828     // type.
6829     if (FieldType->isRValueReferenceType()) {
6830       if (Diagnose)
6831         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6832           << MD->getParent() << FD << FieldType;
6833       return true;
6834     }
6835   } else if (IsAssignment) {
6836     // For an assignment operator, data members must not be of reference type.
6837     if (FieldType->isReferenceType()) {
6838       if (Diagnose)
6839         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6840           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6841       return true;
6842     }
6843     if (!FieldRecord && FieldType.isConstQualified()) {
6844       // C++11 [class.copy]p23:
6845       // -- a non-static data member of const non-class type (or array thereof)
6846       if (Diagnose)
6847         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6848           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6849       return true;
6850     }
6851   }
6852 
6853   if (FieldRecord) {
6854     // Some additional restrictions exist on the variant members.
6855     if (!inUnion() && FieldRecord->isUnion() &&
6856         FieldRecord->isAnonymousStructOrUnion()) {
6857       bool AllVariantFieldsAreConst = true;
6858 
6859       // FIXME: Handle anonymous unions declared within anonymous unions.
6860       for (auto *UI : FieldRecord->fields()) {
6861         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6862 
6863         if (!UnionFieldType.isConstQualified())
6864           AllVariantFieldsAreConst = false;
6865 
6866         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6867         if (UnionFieldRecord &&
6868             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6869                                           UnionFieldType.getCVRQualifiers()))
6870           return true;
6871       }
6872 
6873       // At least one member in each anonymous union must be non-const
6874       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6875           !FieldRecord->field_empty()) {
6876         if (Diagnose)
6877           S.Diag(FieldRecord->getLocation(),
6878                  diag::note_deleted_default_ctor_all_const)
6879             << !!ICI << MD->getParent() << /*anonymous union*/1;
6880         return true;
6881       }
6882 
6883       // Don't check the implicit member of the anonymous union type.
6884       // This is technically non-conformant, but sanity demands it.
6885       return false;
6886     }
6887 
6888     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6889                                       FieldType.getCVRQualifiers()))
6890       return true;
6891   }
6892 
6893   return false;
6894 }
6895 
6896 /// C++11 [class.ctor] p5:
6897 ///   A defaulted default constructor for a class X is defined as deleted if
6898 /// X is a union and all of its variant members are of const-qualified type.
6899 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6900   // This is a silly definition, because it gives an empty union a deleted
6901   // default constructor. Don't do that.
6902   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6903     bool AnyFields = false;
6904     for (auto *F : MD->getParent()->fields())
6905       if ((AnyFields = !F->isUnnamedBitfield()))
6906         break;
6907     if (!AnyFields)
6908       return false;
6909     if (Diagnose)
6910       S.Diag(MD->getParent()->getLocation(),
6911              diag::note_deleted_default_ctor_all_const)
6912         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6913     return true;
6914   }
6915   return false;
6916 }
6917 
6918 /// Determine whether a defaulted special member function should be defined as
6919 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6920 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6921 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6922                                      InheritedConstructorInfo *ICI,
6923                                      bool Diagnose) {
6924   if (MD->isInvalidDecl())
6925     return false;
6926   CXXRecordDecl *RD = MD->getParent();
6927   assert(!RD->isDependentType() && "do deletion after instantiation");
6928   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6929     return false;
6930 
6931   // C++11 [expr.lambda.prim]p19:
6932   //   The closure type associated with a lambda-expression has a
6933   //   deleted (8.4.3) default constructor and a deleted copy
6934   //   assignment operator.
6935   if (RD->isLambda() &&
6936       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6937     if (Diagnose)
6938       Diag(RD->getLocation(), diag::note_lambda_decl);
6939     return true;
6940   }
6941 
6942   // For an anonymous struct or union, the copy and assignment special members
6943   // will never be used, so skip the check. For an anonymous union declared at
6944   // namespace scope, the constructor and destructor are used.
6945   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6946       RD->isAnonymousStructOrUnion())
6947     return false;
6948 
6949   // C++11 [class.copy]p7, p18:
6950   //   If the class definition declares a move constructor or move assignment
6951   //   operator, an implicitly declared copy constructor or copy assignment
6952   //   operator is defined as deleted.
6953   if (MD->isImplicit() &&
6954       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6955     CXXMethodDecl *UserDeclaredMove = nullptr;
6956 
6957     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6958     // deletion of the corresponding copy operation, not both copy operations.
6959     // MSVC 2015 has adopted the standards conforming behavior.
6960     bool DeletesOnlyMatchingCopy =
6961         getLangOpts().MSVCCompat &&
6962         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6963 
6964     if (RD->hasUserDeclaredMoveConstructor() &&
6965         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6966       if (!Diagnose) return true;
6967 
6968       // Find any user-declared move constructor.
6969       for (auto *I : RD->ctors()) {
6970         if (I->isMoveConstructor()) {
6971           UserDeclaredMove = I;
6972           break;
6973         }
6974       }
6975       assert(UserDeclaredMove);
6976     } else if (RD->hasUserDeclaredMoveAssignment() &&
6977                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6978       if (!Diagnose) return true;
6979 
6980       // Find any user-declared move assignment operator.
6981       for (auto *I : RD->methods()) {
6982         if (I->isMoveAssignmentOperator()) {
6983           UserDeclaredMove = I;
6984           break;
6985         }
6986       }
6987       assert(UserDeclaredMove);
6988     }
6989 
6990     if (UserDeclaredMove) {
6991       Diag(UserDeclaredMove->getLocation(),
6992            diag::note_deleted_copy_user_declared_move)
6993         << (CSM == CXXCopyAssignment) << RD
6994         << UserDeclaredMove->isMoveAssignmentOperator();
6995       return true;
6996     }
6997   }
6998 
6999   // Do access control from the special member function
7000   ContextRAII MethodContext(*this, MD);
7001 
7002   // C++11 [class.dtor]p5:
7003   // -- for a virtual destructor, lookup of the non-array deallocation function
7004   //    results in an ambiguity or in a function that is deleted or inaccessible
7005   if (CSM == CXXDestructor && MD->isVirtual()) {
7006     FunctionDecl *OperatorDelete = nullptr;
7007     DeclarationName Name =
7008       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7009     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7010                                  OperatorDelete, /*Diagnose*/false)) {
7011       if (Diagnose)
7012         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7013       return true;
7014     }
7015   }
7016 
7017   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7018 
7019   // Per DR1611, do not consider virtual bases of constructors of abstract
7020   // classes, since we are not going to construct them.
7021   // Per DR1658, do not consider virtual bases of destructors of abstract
7022   // classes either.
7023   // Per DR2180, for assignment operators we only assign (and thus only
7024   // consider) direct bases.
7025   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7026                                  : SMI.VisitPotentiallyConstructedBases))
7027     return true;
7028 
7029   if (SMI.shouldDeleteForAllConstMembers())
7030     return true;
7031 
7032   if (getLangOpts().CUDA) {
7033     // We should delete the special member in CUDA mode if target inference
7034     // failed.
7035     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7036                                                    Diagnose);
7037   }
7038 
7039   return false;
7040 }
7041 
7042 /// Perform lookup for a special member of the specified kind, and determine
7043 /// whether it is trivial. If the triviality can be determined without the
7044 /// lookup, skip it. This is intended for use when determining whether a
7045 /// special member of a containing object is trivial, and thus does not ever
7046 /// perform overload resolution for default constructors.
7047 ///
7048 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7049 /// member that was most likely to be intended to be trivial, if any.
7050 ///
7051 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7052 /// determine whether the special member is trivial.
7053 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7054                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7055                                      bool ConstRHS,
7056                                      Sema::TrivialABIHandling TAH,
7057                                      CXXMethodDecl **Selected) {
7058   if (Selected)
7059     *Selected = nullptr;
7060 
7061   switch (CSM) {
7062   case Sema::CXXInvalid:
7063     llvm_unreachable("not a special member");
7064 
7065   case Sema::CXXDefaultConstructor:
7066     // C++11 [class.ctor]p5:
7067     //   A default constructor is trivial if:
7068     //    - all the [direct subobjects] have trivial default constructors
7069     //
7070     // Note, no overload resolution is performed in this case.
7071     if (RD->hasTrivialDefaultConstructor())
7072       return true;
7073 
7074     if (Selected) {
7075       // If there's a default constructor which could have been trivial, dig it
7076       // out. Otherwise, if there's any user-provided default constructor, point
7077       // to that as an example of why there's not a trivial one.
7078       CXXConstructorDecl *DefCtor = nullptr;
7079       if (RD->needsImplicitDefaultConstructor())
7080         S.DeclareImplicitDefaultConstructor(RD);
7081       for (auto *CI : RD->ctors()) {
7082         if (!CI->isDefaultConstructor())
7083           continue;
7084         DefCtor = CI;
7085         if (!DefCtor->isUserProvided())
7086           break;
7087       }
7088 
7089       *Selected = DefCtor;
7090     }
7091 
7092     return false;
7093 
7094   case Sema::CXXDestructor:
7095     // C++11 [class.dtor]p5:
7096     //   A destructor is trivial if:
7097     //    - all the direct [subobjects] have trivial destructors
7098     if (RD->hasTrivialDestructor() ||
7099         (TAH == Sema::TAH_ConsiderTrivialABI &&
7100          RD->hasTrivialDestructorForCall()))
7101       return true;
7102 
7103     if (Selected) {
7104       if (RD->needsImplicitDestructor())
7105         S.DeclareImplicitDestructor(RD);
7106       *Selected = RD->getDestructor();
7107     }
7108 
7109     return false;
7110 
7111   case Sema::CXXCopyConstructor:
7112     // C++11 [class.copy]p12:
7113     //   A copy constructor is trivial if:
7114     //    - the constructor selected to copy each direct [subobject] is trivial
7115     if (RD->hasTrivialCopyConstructor() ||
7116         (TAH == Sema::TAH_ConsiderTrivialABI &&
7117          RD->hasTrivialCopyConstructorForCall())) {
7118       if (Quals == Qualifiers::Const)
7119         // We must either select the trivial copy constructor or reach an
7120         // ambiguity; no need to actually perform overload resolution.
7121         return true;
7122     } else if (!Selected) {
7123       return false;
7124     }
7125     // In C++98, we are not supposed to perform overload resolution here, but we
7126     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7127     // cases like B as having a non-trivial copy constructor:
7128     //   struct A { template<typename T> A(T&); };
7129     //   struct B { mutable A a; };
7130     goto NeedOverloadResolution;
7131 
7132   case Sema::CXXCopyAssignment:
7133     // C++11 [class.copy]p25:
7134     //   A copy assignment operator is trivial if:
7135     //    - the assignment operator selected to copy each direct [subobject] is
7136     //      trivial
7137     if (RD->hasTrivialCopyAssignment()) {
7138       if (Quals == Qualifiers::Const)
7139         return true;
7140     } else if (!Selected) {
7141       return false;
7142     }
7143     // In C++98, we are not supposed to perform overload resolution here, but we
7144     // treat that as a language defect.
7145     goto NeedOverloadResolution;
7146 
7147   case Sema::CXXMoveConstructor:
7148   case Sema::CXXMoveAssignment:
7149   NeedOverloadResolution:
7150     Sema::SpecialMemberOverloadResult SMOR =
7151         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7152 
7153     // The standard doesn't describe how to behave if the lookup is ambiguous.
7154     // We treat it as not making the member non-trivial, just like the standard
7155     // mandates for the default constructor. This should rarely matter, because
7156     // the member will also be deleted.
7157     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7158       return true;
7159 
7160     if (!SMOR.getMethod()) {
7161       assert(SMOR.getKind() ==
7162              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7163       return false;
7164     }
7165 
7166     // We deliberately don't check if we found a deleted special member. We're
7167     // not supposed to!
7168     if (Selected)
7169       *Selected = SMOR.getMethod();
7170 
7171     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7172         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7173       return SMOR.getMethod()->isTrivialForCall();
7174     return SMOR.getMethod()->isTrivial();
7175   }
7176 
7177   llvm_unreachable("unknown special method kind");
7178 }
7179 
7180 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7181   for (auto *CI : RD->ctors())
7182     if (!CI->isImplicit())
7183       return CI;
7184 
7185   // Look for constructor templates.
7186   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7187   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7188     if (CXXConstructorDecl *CD =
7189           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7190       return CD;
7191   }
7192 
7193   return nullptr;
7194 }
7195 
7196 /// The kind of subobject we are checking for triviality. The values of this
7197 /// enumeration are used in diagnostics.
7198 enum TrivialSubobjectKind {
7199   /// The subobject is a base class.
7200   TSK_BaseClass,
7201   /// The subobject is a non-static data member.
7202   TSK_Field,
7203   /// The object is actually the complete object.
7204   TSK_CompleteObject
7205 };
7206 
7207 /// Check whether the special member selected for a given type would be trivial.
7208 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7209                                       QualType SubType, bool ConstRHS,
7210                                       Sema::CXXSpecialMember CSM,
7211                                       TrivialSubobjectKind Kind,
7212                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7213   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7214   if (!SubRD)
7215     return true;
7216 
7217   CXXMethodDecl *Selected;
7218   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7219                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7220     return true;
7221 
7222   if (Diagnose) {
7223     if (ConstRHS)
7224       SubType.addConst();
7225 
7226     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7227       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7228         << Kind << SubType.getUnqualifiedType();
7229       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7230         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7231     } else if (!Selected)
7232       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7233         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7234     else if (Selected->isUserProvided()) {
7235       if (Kind == TSK_CompleteObject)
7236         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7237           << Kind << SubType.getUnqualifiedType() << CSM;
7238       else {
7239         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7240           << Kind << SubType.getUnqualifiedType() << CSM;
7241         S.Diag(Selected->getLocation(), diag::note_declared_at);
7242       }
7243     } else {
7244       if (Kind != TSK_CompleteObject)
7245         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7246           << Kind << SubType.getUnqualifiedType() << CSM;
7247 
7248       // Explain why the defaulted or deleted special member isn't trivial.
7249       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7250                                Diagnose);
7251     }
7252   }
7253 
7254   return false;
7255 }
7256 
7257 /// Check whether the members of a class type allow a special member to be
7258 /// trivial.
7259 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7260                                      Sema::CXXSpecialMember CSM,
7261                                      bool ConstArg,
7262                                      Sema::TrivialABIHandling TAH,
7263                                      bool Diagnose) {
7264   for (const auto *FI : RD->fields()) {
7265     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7266       continue;
7267 
7268     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7269 
7270     // Pretend anonymous struct or union members are members of this class.
7271     if (FI->isAnonymousStructOrUnion()) {
7272       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7273                                     CSM, ConstArg, TAH, Diagnose))
7274         return false;
7275       continue;
7276     }
7277 
7278     // C++11 [class.ctor]p5:
7279     //   A default constructor is trivial if [...]
7280     //    -- no non-static data member of its class has a
7281     //       brace-or-equal-initializer
7282     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7283       if (Diagnose)
7284         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7285       return false;
7286     }
7287 
7288     // Objective C ARC 4.3.5:
7289     //   [...] nontrivally ownership-qualified types are [...] not trivially
7290     //   default constructible, copy constructible, move constructible, copy
7291     //   assignable, move assignable, or destructible [...]
7292     if (FieldType.hasNonTrivialObjCLifetime()) {
7293       if (Diagnose)
7294         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7295           << RD << FieldType.getObjCLifetime();
7296       return false;
7297     }
7298 
7299     bool ConstRHS = ConstArg && !FI->isMutable();
7300     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7301                                    CSM, TSK_Field, TAH, Diagnose))
7302       return false;
7303   }
7304 
7305   return true;
7306 }
7307 
7308 /// Diagnose why the specified class does not have a trivial special member of
7309 /// the given kind.
7310 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7311   QualType Ty = Context.getRecordType(RD);
7312 
7313   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7314   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7315                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7316                             /*Diagnose*/true);
7317 }
7318 
7319 /// Determine whether a defaulted or deleted special member function is trivial,
7320 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7321 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7322 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7323                                   TrivialABIHandling TAH, bool Diagnose) {
7324   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7325 
7326   CXXRecordDecl *RD = MD->getParent();
7327 
7328   bool ConstArg = false;
7329 
7330   // C++11 [class.copy]p12, p25: [DR1593]
7331   //   A [special member] is trivial if [...] its parameter-type-list is
7332   //   equivalent to the parameter-type-list of an implicit declaration [...]
7333   switch (CSM) {
7334   case CXXDefaultConstructor:
7335   case CXXDestructor:
7336     // Trivial default constructors and destructors cannot have parameters.
7337     break;
7338 
7339   case CXXCopyConstructor:
7340   case CXXCopyAssignment: {
7341     // Trivial copy operations always have const, non-volatile parameter types.
7342     ConstArg = true;
7343     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7344     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7345     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7346       if (Diagnose)
7347         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7348           << Param0->getSourceRange() << Param0->getType()
7349           << Context.getLValueReferenceType(
7350                Context.getRecordType(RD).withConst());
7351       return false;
7352     }
7353     break;
7354   }
7355 
7356   case CXXMoveConstructor:
7357   case CXXMoveAssignment: {
7358     // Trivial move operations always have non-cv-qualified parameters.
7359     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7360     const RValueReferenceType *RT =
7361       Param0->getType()->getAs<RValueReferenceType>();
7362     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7363       if (Diagnose)
7364         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7365           << Param0->getSourceRange() << Param0->getType()
7366           << Context.getRValueReferenceType(Context.getRecordType(RD));
7367       return false;
7368     }
7369     break;
7370   }
7371 
7372   case CXXInvalid:
7373     llvm_unreachable("not a special member");
7374   }
7375 
7376   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7377     if (Diagnose)
7378       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7379            diag::note_nontrivial_default_arg)
7380         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7381     return false;
7382   }
7383   if (MD->isVariadic()) {
7384     if (Diagnose)
7385       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7386     return false;
7387   }
7388 
7389   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7390   //   A copy/move [constructor or assignment operator] is trivial if
7391   //    -- the [member] selected to copy/move each direct base class subobject
7392   //       is trivial
7393   //
7394   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7395   //   A [default constructor or destructor] is trivial if
7396   //    -- all the direct base classes have trivial [default constructors or
7397   //       destructors]
7398   for (const auto &BI : RD->bases())
7399     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7400                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7401       return false;
7402 
7403   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7404   //   A copy/move [constructor or assignment operator] for a class X is
7405   //   trivial if
7406   //    -- for each non-static data member of X that is of class type (or array
7407   //       thereof), the constructor selected to copy/move that member is
7408   //       trivial
7409   //
7410   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7411   //   A [default constructor or destructor] is trivial if
7412   //    -- for all of the non-static data members of its class that are of class
7413   //       type (or array thereof), each such class has a trivial [default
7414   //       constructor or destructor]
7415   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7416     return false;
7417 
7418   // C++11 [class.dtor]p5:
7419   //   A destructor is trivial if [...]
7420   //    -- the destructor is not virtual
7421   if (CSM == CXXDestructor && MD->isVirtual()) {
7422     if (Diagnose)
7423       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7424     return false;
7425   }
7426 
7427   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7428   //   A [special member] for class X is trivial if [...]
7429   //    -- class X has no virtual functions and no virtual base classes
7430   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7431     if (!Diagnose)
7432       return false;
7433 
7434     if (RD->getNumVBases()) {
7435       // Check for virtual bases. We already know that the corresponding
7436       // member in all bases is trivial, so vbases must all be direct.
7437       CXXBaseSpecifier &BS = *RD->vbases_begin();
7438       assert(BS.isVirtual());
7439       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7440       return false;
7441     }
7442 
7443     // Must have a virtual method.
7444     for (const auto *MI : RD->methods()) {
7445       if (MI->isVirtual()) {
7446         SourceLocation MLoc = MI->getLocStart();
7447         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7448         return false;
7449       }
7450     }
7451 
7452     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7453   }
7454 
7455   // Looks like it's trivial!
7456   return true;
7457 }
7458 
7459 namespace {
7460 struct FindHiddenVirtualMethod {
7461   Sema *S;
7462   CXXMethodDecl *Method;
7463   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7464   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7465 
7466 private:
7467   /// Check whether any most overriden method from MD in Methods
7468   static bool CheckMostOverridenMethods(
7469       const CXXMethodDecl *MD,
7470       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7471     if (MD->size_overridden_methods() == 0)
7472       return Methods.count(MD->getCanonicalDecl());
7473     for (const CXXMethodDecl *O : MD->overridden_methods())
7474       if (CheckMostOverridenMethods(O, Methods))
7475         return true;
7476     return false;
7477   }
7478 
7479 public:
7480   /// Member lookup function that determines whether a given C++
7481   /// method overloads virtual methods in a base class without overriding any,
7482   /// to be used with CXXRecordDecl::lookupInBases().
7483   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7484     RecordDecl *BaseRecord =
7485         Specifier->getType()->getAs<RecordType>()->getDecl();
7486 
7487     DeclarationName Name = Method->getDeclName();
7488     assert(Name.getNameKind() == DeclarationName::Identifier);
7489 
7490     bool foundSameNameMethod = false;
7491     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7492     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7493          Path.Decls = Path.Decls.slice(1)) {
7494       NamedDecl *D = Path.Decls.front();
7495       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7496         MD = MD->getCanonicalDecl();
7497         foundSameNameMethod = true;
7498         // Interested only in hidden virtual methods.
7499         if (!MD->isVirtual())
7500           continue;
7501         // If the method we are checking overrides a method from its base
7502         // don't warn about the other overloaded methods. Clang deviates from
7503         // GCC by only diagnosing overloads of inherited virtual functions that
7504         // do not override any other virtual functions in the base. GCC's
7505         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7506         // function from a base class. These cases may be better served by a
7507         // warning (not specific to virtual functions) on call sites when the
7508         // call would select a different function from the base class, were it
7509         // visible.
7510         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7511         if (!S->IsOverload(Method, MD, false))
7512           return true;
7513         // Collect the overload only if its hidden.
7514         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7515           overloadedMethods.push_back(MD);
7516       }
7517     }
7518 
7519     if (foundSameNameMethod)
7520       OverloadedMethods.append(overloadedMethods.begin(),
7521                                overloadedMethods.end());
7522     return foundSameNameMethod;
7523   }
7524 };
7525 } // end anonymous namespace
7526 
7527 /// \brief Add the most overriden methods from MD to Methods
7528 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7529                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7530   if (MD->size_overridden_methods() == 0)
7531     Methods.insert(MD->getCanonicalDecl());
7532   else
7533     for (const CXXMethodDecl *O : MD->overridden_methods())
7534       AddMostOverridenMethods(O, Methods);
7535 }
7536 
7537 /// \brief Check if a method overloads virtual methods in a base class without
7538 /// overriding any.
7539 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7540                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7541   if (!MD->getDeclName().isIdentifier())
7542     return;
7543 
7544   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7545                      /*bool RecordPaths=*/false,
7546                      /*bool DetectVirtual=*/false);
7547   FindHiddenVirtualMethod FHVM;
7548   FHVM.Method = MD;
7549   FHVM.S = this;
7550 
7551   // Keep the base methods that were overriden or introduced in the subclass
7552   // by 'using' in a set. A base method not in this set is hidden.
7553   CXXRecordDecl *DC = MD->getParent();
7554   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7555   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7556     NamedDecl *ND = *I;
7557     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7558       ND = shad->getTargetDecl();
7559     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7560       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7561   }
7562 
7563   if (DC->lookupInBases(FHVM, Paths))
7564     OverloadedMethods = FHVM.OverloadedMethods;
7565 }
7566 
7567 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7568                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7569   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7570     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7571     PartialDiagnostic PD = PDiag(
7572          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7573     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7574     Diag(overloadedMD->getLocation(), PD);
7575   }
7576 }
7577 
7578 /// \brief Diagnose methods which overload virtual methods in a base class
7579 /// without overriding any.
7580 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7581   if (MD->isInvalidDecl())
7582     return;
7583 
7584   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7585     return;
7586 
7587   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7588   FindHiddenVirtualMethods(MD, OverloadedMethods);
7589   if (!OverloadedMethods.empty()) {
7590     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7591       << MD << (OverloadedMethods.size() > 1);
7592 
7593     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7594   }
7595 }
7596 
7597 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7598   auto PrintDiagAndRemoveAttr = [&]() {
7599     // No diagnostics if this is a template instantiation.
7600     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7601       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7602            diag::ext_cannot_use_trivial_abi) << &RD;
7603     RD.dropAttr<TrivialABIAttr>();
7604   };
7605 
7606   // Ill-formed if the struct has virtual functions.
7607   if (RD.isPolymorphic()) {
7608     PrintDiagAndRemoveAttr();
7609     return;
7610   }
7611 
7612   for (const auto &B : RD.bases()) {
7613     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7614     // virtual base.
7615     if ((!B.getType()->isDependentType() &&
7616          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7617         B.isVirtual()) {
7618       PrintDiagAndRemoveAttr();
7619       return;
7620     }
7621   }
7622 
7623   for (const auto *FD : RD.fields()) {
7624     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7625     // non-trivial for the purpose of calls.
7626     QualType FT = FD->getType();
7627     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7628       PrintDiagAndRemoveAttr();
7629       return;
7630     }
7631 
7632     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7633       if (!RT->isDependentType() &&
7634           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7635         PrintDiagAndRemoveAttr();
7636         return;
7637       }
7638   }
7639 }
7640 
7641 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7642                                              Decl *TagDecl,
7643                                              SourceLocation LBrac,
7644                                              SourceLocation RBrac,
7645                                              AttributeList *AttrList) {
7646   if (!TagDecl)
7647     return;
7648 
7649   AdjustDeclIfTemplate(TagDecl);
7650 
7651   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7652     if (l->getKind() != AttributeList::AT_Visibility)
7653       continue;
7654     l->setInvalid();
7655     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7656       l->getName();
7657   }
7658 
7659   // See if trivial_abi has to be dropped.
7660   auto *RD = dyn_cast<CXXRecordDecl>(TagDecl);
7661   if (RD && RD->hasAttr<TrivialABIAttr>())
7662     checkIllFormedTrivialABIStruct(*RD);
7663 
7664   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7665               // strict aliasing violation!
7666               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7667               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7668 
7669   CheckCompletedCXXClass(RD);
7670 }
7671 
7672 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7673 /// special functions, such as the default constructor, copy
7674 /// constructor, or destructor, to the given C++ class (C++
7675 /// [special]p1).  This routine can only be executed just before the
7676 /// definition of the class is complete.
7677 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7678   if (ClassDecl->needsImplicitDefaultConstructor()) {
7679     ++ASTContext::NumImplicitDefaultConstructors;
7680 
7681     if (ClassDecl->hasInheritedConstructor())
7682       DeclareImplicitDefaultConstructor(ClassDecl);
7683   }
7684 
7685   if (ClassDecl->needsImplicitCopyConstructor()) {
7686     ++ASTContext::NumImplicitCopyConstructors;
7687 
7688     // If the properties or semantics of the copy constructor couldn't be
7689     // determined while the class was being declared, force a declaration
7690     // of it now.
7691     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7692         ClassDecl->hasInheritedConstructor())
7693       DeclareImplicitCopyConstructor(ClassDecl);
7694     // For the MS ABI we need to know whether the copy ctor is deleted. A
7695     // prerequisite for deleting the implicit copy ctor is that the class has a
7696     // move ctor or move assignment that is either user-declared or whose
7697     // semantics are inherited from a subobject. FIXME: We should provide a more
7698     // direct way for CodeGen to ask whether the constructor was deleted.
7699     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7700              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7701               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7702               ClassDecl->hasUserDeclaredMoveAssignment() ||
7703               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7704       DeclareImplicitCopyConstructor(ClassDecl);
7705   }
7706 
7707   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7708     ++ASTContext::NumImplicitMoveConstructors;
7709 
7710     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7711         ClassDecl->hasInheritedConstructor())
7712       DeclareImplicitMoveConstructor(ClassDecl);
7713   }
7714 
7715   if (ClassDecl->needsImplicitCopyAssignment()) {
7716     ++ASTContext::NumImplicitCopyAssignmentOperators;
7717 
7718     // If we have a dynamic class, then the copy assignment operator may be
7719     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7720     // it shows up in the right place in the vtable and that we diagnose
7721     // problems with the implicit exception specification.
7722     if (ClassDecl->isDynamicClass() ||
7723         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7724         ClassDecl->hasInheritedAssignment())
7725       DeclareImplicitCopyAssignment(ClassDecl);
7726   }
7727 
7728   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7729     ++ASTContext::NumImplicitMoveAssignmentOperators;
7730 
7731     // Likewise for the move assignment operator.
7732     if (ClassDecl->isDynamicClass() ||
7733         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7734         ClassDecl->hasInheritedAssignment())
7735       DeclareImplicitMoveAssignment(ClassDecl);
7736   }
7737 
7738   if (ClassDecl->needsImplicitDestructor()) {
7739     ++ASTContext::NumImplicitDestructors;
7740 
7741     // If we have a dynamic class, then the destructor may be virtual, so we
7742     // have to declare the destructor immediately. This ensures that, e.g., it
7743     // shows up in the right place in the vtable and that we diagnose problems
7744     // with the implicit exception specification.
7745     if (ClassDecl->isDynamicClass() ||
7746         ClassDecl->needsOverloadResolutionForDestructor())
7747       DeclareImplicitDestructor(ClassDecl);
7748   }
7749 }
7750 
7751 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7752   if (!D)
7753     return 0;
7754 
7755   // The order of template parameters is not important here. All names
7756   // get added to the same scope.
7757   SmallVector<TemplateParameterList *, 4> ParameterLists;
7758 
7759   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7760     D = TD->getTemplatedDecl();
7761 
7762   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7763     ParameterLists.push_back(PSD->getTemplateParameters());
7764 
7765   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7766     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7767       ParameterLists.push_back(DD->getTemplateParameterList(i));
7768 
7769     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7770       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7771         ParameterLists.push_back(FTD->getTemplateParameters());
7772     }
7773   }
7774 
7775   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7776     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7777       ParameterLists.push_back(TD->getTemplateParameterList(i));
7778 
7779     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7780       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7781         ParameterLists.push_back(CTD->getTemplateParameters());
7782     }
7783   }
7784 
7785   unsigned Count = 0;
7786   for (TemplateParameterList *Params : ParameterLists) {
7787     if (Params->size() > 0)
7788       // Ignore explicit specializations; they don't contribute to the template
7789       // depth.
7790       ++Count;
7791     for (NamedDecl *Param : *Params) {
7792       if (Param->getDeclName()) {
7793         S->AddDecl(Param);
7794         IdResolver.AddDecl(Param);
7795       }
7796     }
7797   }
7798 
7799   return Count;
7800 }
7801 
7802 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7803   if (!RecordD) return;
7804   AdjustDeclIfTemplate(RecordD);
7805   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7806   PushDeclContext(S, Record);
7807 }
7808 
7809 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7810   if (!RecordD) return;
7811   PopDeclContext();
7812 }
7813 
7814 /// This is used to implement the constant expression evaluation part of the
7815 /// attribute enable_if extension. There is nothing in standard C++ which would
7816 /// require reentering parameters.
7817 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7818   if (!Param)
7819     return;
7820 
7821   S->AddDecl(Param);
7822   if (Param->getDeclName())
7823     IdResolver.AddDecl(Param);
7824 }
7825 
7826 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7827 /// parsing a top-level (non-nested) C++ class, and we are now
7828 /// parsing those parts of the given Method declaration that could
7829 /// not be parsed earlier (C++ [class.mem]p2), such as default
7830 /// arguments. This action should enter the scope of the given
7831 /// Method declaration as if we had just parsed the qualified method
7832 /// name. However, it should not bring the parameters into scope;
7833 /// that will be performed by ActOnDelayedCXXMethodParameter.
7834 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7835 }
7836 
7837 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7838 /// C++ method declaration. We're (re-)introducing the given
7839 /// function parameter into scope for use in parsing later parts of
7840 /// the method declaration. For example, we could see an
7841 /// ActOnParamDefaultArgument event for this parameter.
7842 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7843   if (!ParamD)
7844     return;
7845 
7846   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7847 
7848   // If this parameter has an unparsed default argument, clear it out
7849   // to make way for the parsed default argument.
7850   if (Param->hasUnparsedDefaultArg())
7851     Param->setDefaultArg(nullptr);
7852 
7853   S->AddDecl(Param);
7854   if (Param->getDeclName())
7855     IdResolver.AddDecl(Param);
7856 }
7857 
7858 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7859 /// processing the delayed method declaration for Method. The method
7860 /// declaration is now considered finished. There may be a separate
7861 /// ActOnStartOfFunctionDef action later (not necessarily
7862 /// immediately!) for this method, if it was also defined inside the
7863 /// class body.
7864 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7865   if (!MethodD)
7866     return;
7867 
7868   AdjustDeclIfTemplate(MethodD);
7869 
7870   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7871 
7872   // Now that we have our default arguments, check the constructor
7873   // again. It could produce additional diagnostics or affect whether
7874   // the class has implicitly-declared destructors, among other
7875   // things.
7876   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7877     CheckConstructor(Constructor);
7878 
7879   // Check the default arguments, which we may have added.
7880   if (!Method->isInvalidDecl())
7881     CheckCXXDefaultArguments(Method);
7882 }
7883 
7884 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7885 /// the well-formedness of the constructor declarator @p D with type @p
7886 /// R. If there are any errors in the declarator, this routine will
7887 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7888 /// will be updated to reflect a well-formed type for the constructor and
7889 /// returned.
7890 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7891                                           StorageClass &SC) {
7892   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7893 
7894   // C++ [class.ctor]p3:
7895   //   A constructor shall not be virtual (10.3) or static (9.4). A
7896   //   constructor can be invoked for a const, volatile or const
7897   //   volatile object. A constructor shall not be declared const,
7898   //   volatile, or const volatile (9.3.2).
7899   if (isVirtual) {
7900     if (!D.isInvalidType())
7901       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7902         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7903         << SourceRange(D.getIdentifierLoc());
7904     D.setInvalidType();
7905   }
7906   if (SC == SC_Static) {
7907     if (!D.isInvalidType())
7908       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7909         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7910         << SourceRange(D.getIdentifierLoc());
7911     D.setInvalidType();
7912     SC = SC_None;
7913   }
7914 
7915   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7916     diagnoseIgnoredQualifiers(
7917         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7918         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7919         D.getDeclSpec().getRestrictSpecLoc(),
7920         D.getDeclSpec().getAtomicSpecLoc());
7921     D.setInvalidType();
7922   }
7923 
7924   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7925   if (FTI.TypeQuals != 0) {
7926     if (FTI.TypeQuals & Qualifiers::Const)
7927       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7928         << "const" << SourceRange(D.getIdentifierLoc());
7929     if (FTI.TypeQuals & Qualifiers::Volatile)
7930       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7931         << "volatile" << SourceRange(D.getIdentifierLoc());
7932     if (FTI.TypeQuals & Qualifiers::Restrict)
7933       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7934         << "restrict" << SourceRange(D.getIdentifierLoc());
7935     D.setInvalidType();
7936   }
7937 
7938   // C++0x [class.ctor]p4:
7939   //   A constructor shall not be declared with a ref-qualifier.
7940   if (FTI.hasRefQualifier()) {
7941     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7942       << FTI.RefQualifierIsLValueRef
7943       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7944     D.setInvalidType();
7945   }
7946 
7947   // Rebuild the function type "R" without any type qualifiers (in
7948   // case any of the errors above fired) and with "void" as the
7949   // return type, since constructors don't have return types.
7950   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7951   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7952     return R;
7953 
7954   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7955   EPI.TypeQuals = 0;
7956   EPI.RefQualifier = RQ_None;
7957 
7958   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7959 }
7960 
7961 /// CheckConstructor - Checks a fully-formed constructor for
7962 /// well-formedness, issuing any diagnostics required. Returns true if
7963 /// the constructor declarator is invalid.
7964 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7965   CXXRecordDecl *ClassDecl
7966     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7967   if (!ClassDecl)
7968     return Constructor->setInvalidDecl();
7969 
7970   // C++ [class.copy]p3:
7971   //   A declaration of a constructor for a class X is ill-formed if
7972   //   its first parameter is of type (optionally cv-qualified) X and
7973   //   either there are no other parameters or else all other
7974   //   parameters have default arguments.
7975   if (!Constructor->isInvalidDecl() &&
7976       ((Constructor->getNumParams() == 1) ||
7977        (Constructor->getNumParams() > 1 &&
7978         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7979       Constructor->getTemplateSpecializationKind()
7980                                               != TSK_ImplicitInstantiation) {
7981     QualType ParamType = Constructor->getParamDecl(0)->getType();
7982     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7983     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7984       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7985       const char *ConstRef
7986         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7987                                                         : " const &";
7988       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7989         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7990 
7991       // FIXME: Rather that making the constructor invalid, we should endeavor
7992       // to fix the type.
7993       Constructor->setInvalidDecl();
7994     }
7995   }
7996 }
7997 
7998 /// CheckDestructor - Checks a fully-formed destructor definition for
7999 /// well-formedness, issuing any diagnostics required.  Returns true
8000 /// on error.
8001 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8002   CXXRecordDecl *RD = Destructor->getParent();
8003 
8004   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8005     SourceLocation Loc;
8006 
8007     if (!Destructor->isImplicit())
8008       Loc = Destructor->getLocation();
8009     else
8010       Loc = RD->getLocation();
8011 
8012     // If we have a virtual destructor, look up the deallocation function
8013     if (FunctionDecl *OperatorDelete =
8014             FindDeallocationFunctionForDestructor(Loc, RD)) {
8015       Expr *ThisArg = nullptr;
8016 
8017       // If the notional 'delete this' expression requires a non-trivial
8018       // conversion from 'this' to the type of a destroying operator delete's
8019       // first parameter, perform that conversion now.
8020       if (OperatorDelete->isDestroyingOperatorDelete()) {
8021         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8022         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8023           // C++ [class.dtor]p13:
8024           //   ... as if for the expression 'delete this' appearing in a
8025           //   non-virtual destructor of the destructor's class.
8026           ContextRAII SwitchContext(*this, Destructor);
8027           ExprResult This =
8028               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8029           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8030           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8031           if (This.isInvalid()) {
8032             // FIXME: Register this as a context note so that it comes out
8033             // in the right order.
8034             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8035             return true;
8036           }
8037           ThisArg = This.get();
8038         }
8039       }
8040 
8041       MarkFunctionReferenced(Loc, OperatorDelete);
8042       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8043     }
8044   }
8045 
8046   return false;
8047 }
8048 
8049 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8050 /// the well-formednes of the destructor declarator @p D with type @p
8051 /// R. If there are any errors in the declarator, this routine will
8052 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8053 /// will be updated to reflect a well-formed type for the destructor and
8054 /// returned.
8055 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8056                                          StorageClass& SC) {
8057   // C++ [class.dtor]p1:
8058   //   [...] A typedef-name that names a class is a class-name
8059   //   (7.1.3); however, a typedef-name that names a class shall not
8060   //   be used as the identifier in the declarator for a destructor
8061   //   declaration.
8062   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8063   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8064     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8065       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8066   else if (const TemplateSpecializationType *TST =
8067              DeclaratorType->getAs<TemplateSpecializationType>())
8068     if (TST->isTypeAlias())
8069       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8070         << DeclaratorType << 1;
8071 
8072   // C++ [class.dtor]p2:
8073   //   A destructor is used to destroy objects of its class type. A
8074   //   destructor takes no parameters, and no return type can be
8075   //   specified for it (not even void). The address of a destructor
8076   //   shall not be taken. A destructor shall not be static. A
8077   //   destructor can be invoked for a const, volatile or const
8078   //   volatile object. A destructor shall not be declared const,
8079   //   volatile or const volatile (9.3.2).
8080   if (SC == SC_Static) {
8081     if (!D.isInvalidType())
8082       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8083         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8084         << SourceRange(D.getIdentifierLoc())
8085         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8086 
8087     SC = SC_None;
8088   }
8089   if (!D.isInvalidType()) {
8090     // Destructors don't have return types, but the parser will
8091     // happily parse something like:
8092     //
8093     //   class X {
8094     //     float ~X();
8095     //   };
8096     //
8097     // The return type will be eliminated later.
8098     if (D.getDeclSpec().hasTypeSpecifier())
8099       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8100         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8101         << SourceRange(D.getIdentifierLoc());
8102     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8103       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8104                                 SourceLocation(),
8105                                 D.getDeclSpec().getConstSpecLoc(),
8106                                 D.getDeclSpec().getVolatileSpecLoc(),
8107                                 D.getDeclSpec().getRestrictSpecLoc(),
8108                                 D.getDeclSpec().getAtomicSpecLoc());
8109       D.setInvalidType();
8110     }
8111   }
8112 
8113   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8114   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8115     if (FTI.TypeQuals & Qualifiers::Const)
8116       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8117         << "const" << SourceRange(D.getIdentifierLoc());
8118     if (FTI.TypeQuals & Qualifiers::Volatile)
8119       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8120         << "volatile" << SourceRange(D.getIdentifierLoc());
8121     if (FTI.TypeQuals & Qualifiers::Restrict)
8122       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8123         << "restrict" << SourceRange(D.getIdentifierLoc());
8124     D.setInvalidType();
8125   }
8126 
8127   // C++0x [class.dtor]p2:
8128   //   A destructor shall not be declared with a ref-qualifier.
8129   if (FTI.hasRefQualifier()) {
8130     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8131       << FTI.RefQualifierIsLValueRef
8132       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8133     D.setInvalidType();
8134   }
8135 
8136   // Make sure we don't have any parameters.
8137   if (FTIHasNonVoidParameters(FTI)) {
8138     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8139 
8140     // Delete the parameters.
8141     FTI.freeParams();
8142     D.setInvalidType();
8143   }
8144 
8145   // Make sure the destructor isn't variadic.
8146   if (FTI.isVariadic) {
8147     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8148     D.setInvalidType();
8149   }
8150 
8151   // Rebuild the function type "R" without any type qualifiers or
8152   // parameters (in case any of the errors above fired) and with
8153   // "void" as the return type, since destructors don't have return
8154   // types.
8155   if (!D.isInvalidType())
8156     return R;
8157 
8158   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8159   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8160   EPI.Variadic = false;
8161   EPI.TypeQuals = 0;
8162   EPI.RefQualifier = RQ_None;
8163   return Context.getFunctionType(Context.VoidTy, None, EPI);
8164 }
8165 
8166 static void extendLeft(SourceRange &R, SourceRange Before) {
8167   if (Before.isInvalid())
8168     return;
8169   R.setBegin(Before.getBegin());
8170   if (R.getEnd().isInvalid())
8171     R.setEnd(Before.getEnd());
8172 }
8173 
8174 static void extendRight(SourceRange &R, SourceRange After) {
8175   if (After.isInvalid())
8176     return;
8177   if (R.getBegin().isInvalid())
8178     R.setBegin(After.getBegin());
8179   R.setEnd(After.getEnd());
8180 }
8181 
8182 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8183 /// well-formednes of the conversion function declarator @p D with
8184 /// type @p R. If there are any errors in the declarator, this routine
8185 /// will emit diagnostics and return true. Otherwise, it will return
8186 /// false. Either way, the type @p R will be updated to reflect a
8187 /// well-formed type for the conversion operator.
8188 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8189                                      StorageClass& SC) {
8190   // C++ [class.conv.fct]p1:
8191   //   Neither parameter types nor return type can be specified. The
8192   //   type of a conversion function (8.3.5) is "function taking no
8193   //   parameter returning conversion-type-id."
8194   if (SC == SC_Static) {
8195     if (!D.isInvalidType())
8196       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8197         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8198         << D.getName().getSourceRange();
8199     D.setInvalidType();
8200     SC = SC_None;
8201   }
8202 
8203   TypeSourceInfo *ConvTSI = nullptr;
8204   QualType ConvType =
8205       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8206 
8207   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
8208     // Conversion functions don't have return types, but the parser will
8209     // happily parse something like:
8210     //
8211     //   class X {
8212     //     float operator bool();
8213     //   };
8214     //
8215     // The return type will be changed later anyway.
8216     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8217       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8218       << SourceRange(D.getIdentifierLoc());
8219     D.setInvalidType();
8220   }
8221 
8222   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8223 
8224   // Make sure we don't have any parameters.
8225   if (Proto->getNumParams() > 0) {
8226     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8227 
8228     // Delete the parameters.
8229     D.getFunctionTypeInfo().freeParams();
8230     D.setInvalidType();
8231   } else if (Proto->isVariadic()) {
8232     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8233     D.setInvalidType();
8234   }
8235 
8236   // Diagnose "&operator bool()" and other such nonsense.  This
8237   // is actually a gcc extension which we don't support.
8238   if (Proto->getReturnType() != ConvType) {
8239     bool NeedsTypedef = false;
8240     SourceRange Before, After;
8241 
8242     // Walk the chunks and extract information on them for our diagnostic.
8243     bool PastFunctionChunk = false;
8244     for (auto &Chunk : D.type_objects()) {
8245       switch (Chunk.Kind) {
8246       case DeclaratorChunk::Function:
8247         if (!PastFunctionChunk) {
8248           if (Chunk.Fun.HasTrailingReturnType) {
8249             TypeSourceInfo *TRT = nullptr;
8250             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8251             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8252           }
8253           PastFunctionChunk = true;
8254           break;
8255         }
8256         LLVM_FALLTHROUGH;
8257       case DeclaratorChunk::Array:
8258         NeedsTypedef = true;
8259         extendRight(After, Chunk.getSourceRange());
8260         break;
8261 
8262       case DeclaratorChunk::Pointer:
8263       case DeclaratorChunk::BlockPointer:
8264       case DeclaratorChunk::Reference:
8265       case DeclaratorChunk::MemberPointer:
8266       case DeclaratorChunk::Pipe:
8267         extendLeft(Before, Chunk.getSourceRange());
8268         break;
8269 
8270       case DeclaratorChunk::Paren:
8271         extendLeft(Before, Chunk.Loc);
8272         extendRight(After, Chunk.EndLoc);
8273         break;
8274       }
8275     }
8276 
8277     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8278                          After.isValid()  ? After.getBegin() :
8279                                             D.getIdentifierLoc();
8280     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8281     DB << Before << After;
8282 
8283     if (!NeedsTypedef) {
8284       DB << /*don't need a typedef*/0;
8285 
8286       // If we can provide a correct fix-it hint, do so.
8287       if (After.isInvalid() && ConvTSI) {
8288         SourceLocation InsertLoc =
8289             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8290         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8291            << FixItHint::CreateInsertionFromRange(
8292                   InsertLoc, CharSourceRange::getTokenRange(Before))
8293            << FixItHint::CreateRemoval(Before);
8294       }
8295     } else if (!Proto->getReturnType()->isDependentType()) {
8296       DB << /*typedef*/1 << Proto->getReturnType();
8297     } else if (getLangOpts().CPlusPlus11) {
8298       DB << /*alias template*/2 << Proto->getReturnType();
8299     } else {
8300       DB << /*might not be fixable*/3;
8301     }
8302 
8303     // Recover by incorporating the other type chunks into the result type.
8304     // Note, this does *not* change the name of the function. This is compatible
8305     // with the GCC extension:
8306     //   struct S { &operator int(); } s;
8307     //   int &r = s.operator int(); // ok in GCC
8308     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8309     ConvType = Proto->getReturnType();
8310   }
8311 
8312   // C++ [class.conv.fct]p4:
8313   //   The conversion-type-id shall not represent a function type nor
8314   //   an array type.
8315   if (ConvType->isArrayType()) {
8316     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8317     ConvType = Context.getPointerType(ConvType);
8318     D.setInvalidType();
8319   } else if (ConvType->isFunctionType()) {
8320     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8321     ConvType = Context.getPointerType(ConvType);
8322     D.setInvalidType();
8323   }
8324 
8325   // Rebuild the function type "R" without any parameters (in case any
8326   // of the errors above fired) and with the conversion type as the
8327   // return type.
8328   if (D.isInvalidType())
8329     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8330 
8331   // C++0x explicit conversion operators.
8332   if (D.getDeclSpec().isExplicitSpecified())
8333     Diag(D.getDeclSpec().getExplicitSpecLoc(),
8334          getLangOpts().CPlusPlus11 ?
8335            diag::warn_cxx98_compat_explicit_conversion_functions :
8336            diag::ext_explicit_conversion_functions)
8337       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8338 }
8339 
8340 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8341 /// the declaration of the given C++ conversion function. This routine
8342 /// is responsible for recording the conversion function in the C++
8343 /// class, if possible.
8344 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8345   assert(Conversion && "Expected to receive a conversion function declaration");
8346 
8347   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8348 
8349   // Make sure we aren't redeclaring the conversion function.
8350   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8351 
8352   // C++ [class.conv.fct]p1:
8353   //   [...] A conversion function is never used to convert a
8354   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8355   //   same object type (or a reference to it), to a (possibly
8356   //   cv-qualified) base class of that type (or a reference to it),
8357   //   or to (possibly cv-qualified) void.
8358   // FIXME: Suppress this warning if the conversion function ends up being a
8359   // virtual function that overrides a virtual function in a base class.
8360   QualType ClassType
8361     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8362   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8363     ConvType = ConvTypeRef->getPointeeType();
8364   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8365       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8366     /* Suppress diagnostics for instantiations. */;
8367   else if (ConvType->isRecordType()) {
8368     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8369     if (ConvType == ClassType)
8370       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8371         << ClassType;
8372     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8373       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8374         <<  ClassType << ConvType;
8375   } else if (ConvType->isVoidType()) {
8376     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8377       << ClassType << ConvType;
8378   }
8379 
8380   if (FunctionTemplateDecl *ConversionTemplate
8381                                 = Conversion->getDescribedFunctionTemplate())
8382     return ConversionTemplate;
8383 
8384   return Conversion;
8385 }
8386 
8387 namespace {
8388 /// Utility class to accumulate and print a diagnostic listing the invalid
8389 /// specifier(s) on a declaration.
8390 struct BadSpecifierDiagnoser {
8391   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8392       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8393   ~BadSpecifierDiagnoser() {
8394     Diagnostic << Specifiers;
8395   }
8396 
8397   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8398     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8399   }
8400   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8401     return check(SpecLoc,
8402                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8403   }
8404   void check(SourceLocation SpecLoc, const char *Spec) {
8405     if (SpecLoc.isInvalid()) return;
8406     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8407     if (!Specifiers.empty()) Specifiers += " ";
8408     Specifiers += Spec;
8409   }
8410 
8411   Sema &S;
8412   Sema::SemaDiagnosticBuilder Diagnostic;
8413   std::string Specifiers;
8414 };
8415 }
8416 
8417 /// Check the validity of a declarator that we parsed for a deduction-guide.
8418 /// These aren't actually declarators in the grammar, so we need to check that
8419 /// the user didn't specify any pieces that are not part of the deduction-guide
8420 /// grammar.
8421 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8422                                          StorageClass &SC) {
8423   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8424   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8425   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8426 
8427   // C++ [temp.deduct.guide]p3:
8428   //   A deduction-gide shall be declared in the same scope as the
8429   //   corresponding class template.
8430   if (!CurContext->getRedeclContext()->Equals(
8431           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8432     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8433       << GuidedTemplateDecl;
8434     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8435   }
8436 
8437   auto &DS = D.getMutableDeclSpec();
8438   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8439   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8440       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8441       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8442     BadSpecifierDiagnoser Diagnoser(
8443         *this, D.getIdentifierLoc(),
8444         diag::err_deduction_guide_invalid_specifier);
8445 
8446     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8447     DS.ClearStorageClassSpecs();
8448     SC = SC_None;
8449 
8450     // 'explicit' is permitted.
8451     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8452     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8453     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8454     DS.ClearConstexprSpec();
8455 
8456     Diagnoser.check(DS.getConstSpecLoc(), "const");
8457     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8458     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8459     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8460     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8461     DS.ClearTypeQualifiers();
8462 
8463     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8464     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8465     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8466     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8467     DS.ClearTypeSpecType();
8468   }
8469 
8470   if (D.isInvalidType())
8471     return;
8472 
8473   // Check the declarator is simple enough.
8474   bool FoundFunction = false;
8475   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8476     if (Chunk.Kind == DeclaratorChunk::Paren)
8477       continue;
8478     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8479       Diag(D.getDeclSpec().getLocStart(),
8480           diag::err_deduction_guide_with_complex_decl)
8481         << D.getSourceRange();
8482       break;
8483     }
8484     if (!Chunk.Fun.hasTrailingReturnType()) {
8485       Diag(D.getName().getLocStart(),
8486            diag::err_deduction_guide_no_trailing_return_type);
8487       break;
8488     }
8489 
8490     // Check that the return type is written as a specialization of
8491     // the template specified as the deduction-guide's name.
8492     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8493     TypeSourceInfo *TSI = nullptr;
8494     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8495     assert(TSI && "deduction guide has valid type but invalid return type?");
8496     bool AcceptableReturnType = false;
8497     bool MightInstantiateToSpecialization = false;
8498     if (auto RetTST =
8499             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8500       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8501       bool TemplateMatches =
8502           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8503       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8504         AcceptableReturnType = true;
8505       else {
8506         // This could still instantiate to the right type, unless we know it
8507         // names the wrong class template.
8508         auto *TD = SpecifiedName.getAsTemplateDecl();
8509         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8510                                              !TemplateMatches);
8511       }
8512     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8513       MightInstantiateToSpecialization = true;
8514     }
8515 
8516     if (!AcceptableReturnType) {
8517       Diag(TSI->getTypeLoc().getLocStart(),
8518            diag::err_deduction_guide_bad_trailing_return_type)
8519         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8520         << TSI->getTypeLoc().getSourceRange();
8521     }
8522 
8523     // Keep going to check that we don't have any inner declarator pieces (we
8524     // could still have a function returning a pointer to a function).
8525     FoundFunction = true;
8526   }
8527 
8528   if (D.isFunctionDefinition())
8529     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8530 }
8531 
8532 //===----------------------------------------------------------------------===//
8533 // Namespace Handling
8534 //===----------------------------------------------------------------------===//
8535 
8536 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8537 /// reopened.
8538 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8539                                             SourceLocation Loc,
8540                                             IdentifierInfo *II, bool *IsInline,
8541                                             NamespaceDecl *PrevNS) {
8542   assert(*IsInline != PrevNS->isInline());
8543 
8544   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8545   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8546   // inline namespaces, with the intention of bringing names into namespace std.
8547   //
8548   // We support this just well enough to get that case working; this is not
8549   // sufficient to support reopening namespaces as inline in general.
8550   if (*IsInline && II && II->getName().startswith("__atomic") &&
8551       S.getSourceManager().isInSystemHeader(Loc)) {
8552     // Mark all prior declarations of the namespace as inline.
8553     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8554          NS = NS->getPreviousDecl())
8555       NS->setInline(*IsInline);
8556     // Patch up the lookup table for the containing namespace. This isn't really
8557     // correct, but it's good enough for this particular case.
8558     for (auto *I : PrevNS->decls())
8559       if (auto *ND = dyn_cast<NamedDecl>(I))
8560         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8561     return;
8562   }
8563 
8564   if (PrevNS->isInline())
8565     // The user probably just forgot the 'inline', so suggest that it
8566     // be added back.
8567     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8568       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8569   else
8570     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8571 
8572   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8573   *IsInline = PrevNS->isInline();
8574 }
8575 
8576 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8577 /// definition.
8578 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8579                                    SourceLocation InlineLoc,
8580                                    SourceLocation NamespaceLoc,
8581                                    SourceLocation IdentLoc,
8582                                    IdentifierInfo *II,
8583                                    SourceLocation LBrace,
8584                                    AttributeList *AttrList,
8585                                    UsingDirectiveDecl *&UD) {
8586   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8587   // For anonymous namespace, take the location of the left brace.
8588   SourceLocation Loc = II ? IdentLoc : LBrace;
8589   bool IsInline = InlineLoc.isValid();
8590   bool IsInvalid = false;
8591   bool IsStd = false;
8592   bool AddToKnown = false;
8593   Scope *DeclRegionScope = NamespcScope->getParent();
8594 
8595   NamespaceDecl *PrevNS = nullptr;
8596   if (II) {
8597     // C++ [namespace.def]p2:
8598     //   The identifier in an original-namespace-definition shall not
8599     //   have been previously defined in the declarative region in
8600     //   which the original-namespace-definition appears. The
8601     //   identifier in an original-namespace-definition is the name of
8602     //   the namespace. Subsequently in that declarative region, it is
8603     //   treated as an original-namespace-name.
8604     //
8605     // Since namespace names are unique in their scope, and we don't
8606     // look through using directives, just look for any ordinary names
8607     // as if by qualified name lookup.
8608     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8609                    ForExternalRedeclaration);
8610     LookupQualifiedName(R, CurContext->getRedeclContext());
8611     NamedDecl *PrevDecl =
8612         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8613     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8614 
8615     if (PrevNS) {
8616       // This is an extended namespace definition.
8617       if (IsInline != PrevNS->isInline())
8618         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8619                                         &IsInline, PrevNS);
8620     } else if (PrevDecl) {
8621       // This is an invalid name redefinition.
8622       Diag(Loc, diag::err_redefinition_different_kind)
8623         << II;
8624       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8625       IsInvalid = true;
8626       // Continue on to push Namespc as current DeclContext and return it.
8627     } else if (II->isStr("std") &&
8628                CurContext->getRedeclContext()->isTranslationUnit()) {
8629       // This is the first "real" definition of the namespace "std", so update
8630       // our cache of the "std" namespace to point at this definition.
8631       PrevNS = getStdNamespace();
8632       IsStd = true;
8633       AddToKnown = !IsInline;
8634     } else {
8635       // We've seen this namespace for the first time.
8636       AddToKnown = !IsInline;
8637     }
8638   } else {
8639     // Anonymous namespaces.
8640 
8641     // Determine whether the parent already has an anonymous namespace.
8642     DeclContext *Parent = CurContext->getRedeclContext();
8643     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8644       PrevNS = TU->getAnonymousNamespace();
8645     } else {
8646       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8647       PrevNS = ND->getAnonymousNamespace();
8648     }
8649 
8650     if (PrevNS && IsInline != PrevNS->isInline())
8651       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8652                                       &IsInline, PrevNS);
8653   }
8654 
8655   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8656                                                  StartLoc, Loc, II, PrevNS);
8657   if (IsInvalid)
8658     Namespc->setInvalidDecl();
8659 
8660   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8661   AddPragmaAttributes(DeclRegionScope, Namespc);
8662 
8663   // FIXME: Should we be merging attributes?
8664   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8665     PushNamespaceVisibilityAttr(Attr, Loc);
8666 
8667   if (IsStd)
8668     StdNamespace = Namespc;
8669   if (AddToKnown)
8670     KnownNamespaces[Namespc] = false;
8671 
8672   if (II) {
8673     PushOnScopeChains(Namespc, DeclRegionScope);
8674   } else {
8675     // Link the anonymous namespace into its parent.
8676     DeclContext *Parent = CurContext->getRedeclContext();
8677     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8678       TU->setAnonymousNamespace(Namespc);
8679     } else {
8680       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8681     }
8682 
8683     CurContext->addDecl(Namespc);
8684 
8685     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8686     //   behaves as if it were replaced by
8687     //     namespace unique { /* empty body */ }
8688     //     using namespace unique;
8689     //     namespace unique { namespace-body }
8690     //   where all occurrences of 'unique' in a translation unit are
8691     //   replaced by the same identifier and this identifier differs
8692     //   from all other identifiers in the entire program.
8693 
8694     // We just create the namespace with an empty name and then add an
8695     // implicit using declaration, just like the standard suggests.
8696     //
8697     // CodeGen enforces the "universally unique" aspect by giving all
8698     // declarations semantically contained within an anonymous
8699     // namespace internal linkage.
8700 
8701     if (!PrevNS) {
8702       UD = UsingDirectiveDecl::Create(Context, Parent,
8703                                       /* 'using' */ LBrace,
8704                                       /* 'namespace' */ SourceLocation(),
8705                                       /* qualifier */ NestedNameSpecifierLoc(),
8706                                       /* identifier */ SourceLocation(),
8707                                       Namespc,
8708                                       /* Ancestor */ Parent);
8709       UD->setImplicit();
8710       Parent->addDecl(UD);
8711     }
8712   }
8713 
8714   ActOnDocumentableDecl(Namespc);
8715 
8716   // Although we could have an invalid decl (i.e. the namespace name is a
8717   // redefinition), push it as current DeclContext and try to continue parsing.
8718   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8719   // for the namespace has the declarations that showed up in that particular
8720   // namespace definition.
8721   PushDeclContext(NamespcScope, Namespc);
8722   return Namespc;
8723 }
8724 
8725 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8726 /// is a namespace alias, returns the namespace it points to.
8727 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8728   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8729     return AD->getNamespace();
8730   return dyn_cast_or_null<NamespaceDecl>(D);
8731 }
8732 
8733 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8734 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8735 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8736   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8737   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8738   Namespc->setRBraceLoc(RBrace);
8739   PopDeclContext();
8740   if (Namespc->hasAttr<VisibilityAttr>())
8741     PopPragmaVisibility(true, RBrace);
8742 }
8743 
8744 CXXRecordDecl *Sema::getStdBadAlloc() const {
8745   return cast_or_null<CXXRecordDecl>(
8746                                   StdBadAlloc.get(Context.getExternalSource()));
8747 }
8748 
8749 EnumDecl *Sema::getStdAlignValT() const {
8750   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8751 }
8752 
8753 NamespaceDecl *Sema::getStdNamespace() const {
8754   return cast_or_null<NamespaceDecl>(
8755                                  StdNamespace.get(Context.getExternalSource()));
8756 }
8757 
8758 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8759   if (!StdExperimentalNamespaceCache) {
8760     if (auto Std = getStdNamespace()) {
8761       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8762                           SourceLocation(), LookupNamespaceName);
8763       if (!LookupQualifiedName(Result, Std) ||
8764           !(StdExperimentalNamespaceCache =
8765                 Result.getAsSingle<NamespaceDecl>()))
8766         Result.suppressDiagnostics();
8767     }
8768   }
8769   return StdExperimentalNamespaceCache;
8770 }
8771 
8772 /// \brief Retrieve the special "std" namespace, which may require us to
8773 /// implicitly define the namespace.
8774 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8775   if (!StdNamespace) {
8776     // The "std" namespace has not yet been defined, so build one implicitly.
8777     StdNamespace = NamespaceDecl::Create(Context,
8778                                          Context.getTranslationUnitDecl(),
8779                                          /*Inline=*/false,
8780                                          SourceLocation(), SourceLocation(),
8781                                          &PP.getIdentifierTable().get("std"),
8782                                          /*PrevDecl=*/nullptr);
8783     getStdNamespace()->setImplicit(true);
8784   }
8785 
8786   return getStdNamespace();
8787 }
8788 
8789 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8790   assert(getLangOpts().CPlusPlus &&
8791          "Looking for std::initializer_list outside of C++.");
8792 
8793   // We're looking for implicit instantiations of
8794   // template <typename E> class std::initializer_list.
8795 
8796   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8797     return false;
8798 
8799   ClassTemplateDecl *Template = nullptr;
8800   const TemplateArgument *Arguments = nullptr;
8801 
8802   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8803 
8804     ClassTemplateSpecializationDecl *Specialization =
8805         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8806     if (!Specialization)
8807       return false;
8808 
8809     Template = Specialization->getSpecializedTemplate();
8810     Arguments = Specialization->getTemplateArgs().data();
8811   } else if (const TemplateSpecializationType *TST =
8812                  Ty->getAs<TemplateSpecializationType>()) {
8813     Template = dyn_cast_or_null<ClassTemplateDecl>(
8814         TST->getTemplateName().getAsTemplateDecl());
8815     Arguments = TST->getArgs();
8816   }
8817   if (!Template)
8818     return false;
8819 
8820   if (!StdInitializerList) {
8821     // Haven't recognized std::initializer_list yet, maybe this is it.
8822     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8823     if (TemplateClass->getIdentifier() !=
8824             &PP.getIdentifierTable().get("initializer_list") ||
8825         !getStdNamespace()->InEnclosingNamespaceSetOf(
8826             TemplateClass->getDeclContext()))
8827       return false;
8828     // This is a template called std::initializer_list, but is it the right
8829     // template?
8830     TemplateParameterList *Params = Template->getTemplateParameters();
8831     if (Params->getMinRequiredArguments() != 1)
8832       return false;
8833     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8834       return false;
8835 
8836     // It's the right template.
8837     StdInitializerList = Template;
8838   }
8839 
8840   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8841     return false;
8842 
8843   // This is an instance of std::initializer_list. Find the argument type.
8844   if (Element)
8845     *Element = Arguments[0].getAsType();
8846   return true;
8847 }
8848 
8849 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8850   NamespaceDecl *Std = S.getStdNamespace();
8851   if (!Std) {
8852     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8853     return nullptr;
8854   }
8855 
8856   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8857                       Loc, Sema::LookupOrdinaryName);
8858   if (!S.LookupQualifiedName(Result, Std)) {
8859     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8860     return nullptr;
8861   }
8862   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8863   if (!Template) {
8864     Result.suppressDiagnostics();
8865     // We found something weird. Complain about the first thing we found.
8866     NamedDecl *Found = *Result.begin();
8867     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8868     return nullptr;
8869   }
8870 
8871   // We found some template called std::initializer_list. Now verify that it's
8872   // correct.
8873   TemplateParameterList *Params = Template->getTemplateParameters();
8874   if (Params->getMinRequiredArguments() != 1 ||
8875       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8876     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8877     return nullptr;
8878   }
8879 
8880   return Template;
8881 }
8882 
8883 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8884   if (!StdInitializerList) {
8885     StdInitializerList = LookupStdInitializerList(*this, Loc);
8886     if (!StdInitializerList)
8887       return QualType();
8888   }
8889 
8890   TemplateArgumentListInfo Args(Loc, Loc);
8891   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8892                                        Context.getTrivialTypeSourceInfo(Element,
8893                                                                         Loc)));
8894   return Context.getCanonicalType(
8895       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8896 }
8897 
8898 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
8899   // C++ [dcl.init.list]p2:
8900   //   A constructor is an initializer-list constructor if its first parameter
8901   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8902   //   std::initializer_list<E> for some type E, and either there are no other
8903   //   parameters or else all other parameters have default arguments.
8904   if (Ctor->getNumParams() < 1 ||
8905       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8906     return false;
8907 
8908   QualType ArgType = Ctor->getParamDecl(0)->getType();
8909   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8910     ArgType = RT->getPointeeType().getUnqualifiedType();
8911 
8912   return isStdInitializerList(ArgType, nullptr);
8913 }
8914 
8915 /// \brief Determine whether a using statement is in a context where it will be
8916 /// apply in all contexts.
8917 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8918   switch (CurContext->getDeclKind()) {
8919     case Decl::TranslationUnit:
8920       return true;
8921     case Decl::LinkageSpec:
8922       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8923     default:
8924       return false;
8925   }
8926 }
8927 
8928 namespace {
8929 
8930 // Callback to only accept typo corrections that are namespaces.
8931 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8932 public:
8933   bool ValidateCandidate(const TypoCorrection &candidate) override {
8934     if (NamedDecl *ND = candidate.getCorrectionDecl())
8935       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8936     return false;
8937   }
8938 };
8939 
8940 }
8941 
8942 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8943                                        CXXScopeSpec &SS,
8944                                        SourceLocation IdentLoc,
8945                                        IdentifierInfo *Ident) {
8946   R.clear();
8947   if (TypoCorrection Corrected =
8948           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8949                         llvm::make_unique<NamespaceValidatorCCC>(),
8950                         Sema::CTK_ErrorRecovery)) {
8951     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8952       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8953       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8954                               Ident->getName().equals(CorrectedStr);
8955       S.diagnoseTypo(Corrected,
8956                      S.PDiag(diag::err_using_directive_member_suggest)
8957                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8958                      S.PDiag(diag::note_namespace_defined_here));
8959     } else {
8960       S.diagnoseTypo(Corrected,
8961                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8962                      S.PDiag(diag::note_namespace_defined_here));
8963     }
8964     R.addDecl(Corrected.getFoundDecl());
8965     return true;
8966   }
8967   return false;
8968 }
8969 
8970 Decl *Sema::ActOnUsingDirective(Scope *S,
8971                                           SourceLocation UsingLoc,
8972                                           SourceLocation NamespcLoc,
8973                                           CXXScopeSpec &SS,
8974                                           SourceLocation IdentLoc,
8975                                           IdentifierInfo *NamespcName,
8976                                           AttributeList *AttrList) {
8977   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8978   assert(NamespcName && "Invalid NamespcName.");
8979   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8980 
8981   // This can only happen along a recovery path.
8982   while (S->isTemplateParamScope())
8983     S = S->getParent();
8984   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8985 
8986   UsingDirectiveDecl *UDir = nullptr;
8987   NestedNameSpecifier *Qualifier = nullptr;
8988   if (SS.isSet())
8989     Qualifier = SS.getScopeRep();
8990 
8991   // Lookup namespace name.
8992   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8993   LookupParsedName(R, S, &SS);
8994   if (R.isAmbiguous())
8995     return nullptr;
8996 
8997   if (R.empty()) {
8998     R.clear();
8999     // Allow "using namespace std;" or "using namespace ::std;" even if
9000     // "std" hasn't been defined yet, for GCC compatibility.
9001     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9002         NamespcName->isStr("std")) {
9003       Diag(IdentLoc, diag::ext_using_undefined_std);
9004       R.addDecl(getOrCreateStdNamespace());
9005       R.resolveKind();
9006     }
9007     // Otherwise, attempt typo correction.
9008     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9009   }
9010 
9011   if (!R.empty()) {
9012     NamedDecl *Named = R.getRepresentativeDecl();
9013     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9014     assert(NS && "expected namespace decl");
9015 
9016     // The use of a nested name specifier may trigger deprecation warnings.
9017     DiagnoseUseOfDecl(Named, IdentLoc);
9018 
9019     // C++ [namespace.udir]p1:
9020     //   A using-directive specifies that the names in the nominated
9021     //   namespace can be used in the scope in which the
9022     //   using-directive appears after the using-directive. During
9023     //   unqualified name lookup (3.4.1), the names appear as if they
9024     //   were declared in the nearest enclosing namespace which
9025     //   contains both the using-directive and the nominated
9026     //   namespace. [Note: in this context, "contains" means "contains
9027     //   directly or indirectly". ]
9028 
9029     // Find enclosing context containing both using-directive and
9030     // nominated namespace.
9031     DeclContext *CommonAncestor = cast<DeclContext>(NS);
9032     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9033       CommonAncestor = CommonAncestor->getParent();
9034 
9035     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9036                                       SS.getWithLocInContext(Context),
9037                                       IdentLoc, Named, CommonAncestor);
9038 
9039     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9040         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9041       Diag(IdentLoc, diag::warn_using_directive_in_header);
9042     }
9043 
9044     PushUsingDirective(S, UDir);
9045   } else {
9046     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9047   }
9048 
9049   if (UDir)
9050     ProcessDeclAttributeList(S, UDir, AttrList);
9051 
9052   return UDir;
9053 }
9054 
9055 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9056   // If the scope has an associated entity and the using directive is at
9057   // namespace or translation unit scope, add the UsingDirectiveDecl into
9058   // its lookup structure so qualified name lookup can find it.
9059   DeclContext *Ctx = S->getEntity();
9060   if (Ctx && !Ctx->isFunctionOrMethod())
9061     Ctx->addDecl(UDir);
9062   else
9063     // Otherwise, it is at block scope. The using-directives will affect lookup
9064     // only to the end of the scope.
9065     S->PushUsingDirective(UDir);
9066 }
9067 
9068 
9069 Decl *Sema::ActOnUsingDeclaration(Scope *S,
9070                                   AccessSpecifier AS,
9071                                   SourceLocation UsingLoc,
9072                                   SourceLocation TypenameLoc,
9073                                   CXXScopeSpec &SS,
9074                                   UnqualifiedId &Name,
9075                                   SourceLocation EllipsisLoc,
9076                                   AttributeList *AttrList) {
9077   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9078 
9079   if (SS.isEmpty()) {
9080     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
9081     return nullptr;
9082   }
9083 
9084   switch (Name.getKind()) {
9085   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9086   case UnqualifiedIdKind::IK_Identifier:
9087   case UnqualifiedIdKind::IK_OperatorFunctionId:
9088   case UnqualifiedIdKind::IK_LiteralOperatorId:
9089   case UnqualifiedIdKind::IK_ConversionFunctionId:
9090     break;
9091 
9092   case UnqualifiedIdKind::IK_ConstructorName:
9093   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9094     // C++11 inheriting constructors.
9095     Diag(Name.getLocStart(),
9096          getLangOpts().CPlusPlus11 ?
9097            diag::warn_cxx98_compat_using_decl_constructor :
9098            diag::err_using_decl_constructor)
9099       << SS.getRange();
9100 
9101     if (getLangOpts().CPlusPlus11) break;
9102 
9103     return nullptr;
9104 
9105   case UnqualifiedIdKind::IK_DestructorName:
9106     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9107       << SS.getRange();
9108     return nullptr;
9109 
9110   case UnqualifiedIdKind::IK_TemplateId:
9111     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9112       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9113     return nullptr;
9114 
9115   case UnqualifiedIdKind::IK_DeductionGuideName:
9116     llvm_unreachable("cannot parse qualified deduction guide name");
9117   }
9118 
9119   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9120   DeclarationName TargetName = TargetNameInfo.getName();
9121   if (!TargetName)
9122     return nullptr;
9123 
9124   // Warn about access declarations.
9125   if (UsingLoc.isInvalid()) {
9126     Diag(Name.getLocStart(),
9127          getLangOpts().CPlusPlus11 ? diag::err_access_decl
9128                                    : diag::warn_access_decl_deprecated)
9129       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9130   }
9131 
9132   if (EllipsisLoc.isInvalid()) {
9133     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9134         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9135       return nullptr;
9136   } else {
9137     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9138         !TargetNameInfo.containsUnexpandedParameterPack()) {
9139       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9140         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9141       EllipsisLoc = SourceLocation();
9142     }
9143   }
9144 
9145   NamedDecl *UD =
9146       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9147                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9148                             /*IsInstantiation*/false);
9149   if (UD)
9150     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9151 
9152   return UD;
9153 }
9154 
9155 /// \brief Determine whether a using declaration considers the given
9156 /// declarations as "equivalent", e.g., if they are redeclarations of
9157 /// the same entity or are both typedefs of the same type.
9158 static bool
9159 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9160   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9161     return true;
9162 
9163   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9164     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9165       return Context.hasSameType(TD1->getUnderlyingType(),
9166                                  TD2->getUnderlyingType());
9167 
9168   return false;
9169 }
9170 
9171 
9172 /// Determines whether to create a using shadow decl for a particular
9173 /// decl, given the set of decls existing prior to this using lookup.
9174 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9175                                 const LookupResult &Previous,
9176                                 UsingShadowDecl *&PrevShadow) {
9177   // Diagnose finding a decl which is not from a base class of the
9178   // current class.  We do this now because there are cases where this
9179   // function will silently decide not to build a shadow decl, which
9180   // will pre-empt further diagnostics.
9181   //
9182   // We don't need to do this in C++11 because we do the check once on
9183   // the qualifier.
9184   //
9185   // FIXME: diagnose the following if we care enough:
9186   //   struct A { int foo; };
9187   //   struct B : A { using A::foo; };
9188   //   template <class T> struct C : A {};
9189   //   template <class T> struct D : C<T> { using B::foo; } // <---
9190   // This is invalid (during instantiation) in C++03 because B::foo
9191   // resolves to the using decl in B, which is not a base class of D<T>.
9192   // We can't diagnose it immediately because C<T> is an unknown
9193   // specialization.  The UsingShadowDecl in D<T> then points directly
9194   // to A::foo, which will look well-formed when we instantiate.
9195   // The right solution is to not collapse the shadow-decl chain.
9196   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9197     DeclContext *OrigDC = Orig->getDeclContext();
9198 
9199     // Handle enums and anonymous structs.
9200     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9201     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9202     while (OrigRec->isAnonymousStructOrUnion())
9203       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9204 
9205     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9206       if (OrigDC == CurContext) {
9207         Diag(Using->getLocation(),
9208              diag::err_using_decl_nested_name_specifier_is_current_class)
9209           << Using->getQualifierLoc().getSourceRange();
9210         Diag(Orig->getLocation(), diag::note_using_decl_target);
9211         Using->setInvalidDecl();
9212         return true;
9213       }
9214 
9215       Diag(Using->getQualifierLoc().getBeginLoc(),
9216            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9217         << Using->getQualifier()
9218         << cast<CXXRecordDecl>(CurContext)
9219         << Using->getQualifierLoc().getSourceRange();
9220       Diag(Orig->getLocation(), diag::note_using_decl_target);
9221       Using->setInvalidDecl();
9222       return true;
9223     }
9224   }
9225 
9226   if (Previous.empty()) return false;
9227 
9228   NamedDecl *Target = Orig;
9229   if (isa<UsingShadowDecl>(Target))
9230     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9231 
9232   // If the target happens to be one of the previous declarations, we
9233   // don't have a conflict.
9234   //
9235   // FIXME: but we might be increasing its access, in which case we
9236   // should redeclare it.
9237   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9238   bool FoundEquivalentDecl = false;
9239   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9240          I != E; ++I) {
9241     NamedDecl *D = (*I)->getUnderlyingDecl();
9242     // We can have UsingDecls in our Previous results because we use the same
9243     // LookupResult for checking whether the UsingDecl itself is a valid
9244     // redeclaration.
9245     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9246       continue;
9247 
9248     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9249       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9250         PrevShadow = Shadow;
9251       FoundEquivalentDecl = true;
9252     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9253       // We don't conflict with an existing using shadow decl of an equivalent
9254       // declaration, but we're not a redeclaration of it.
9255       FoundEquivalentDecl = true;
9256     }
9257 
9258     if (isVisible(D))
9259       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9260   }
9261 
9262   if (FoundEquivalentDecl)
9263     return false;
9264 
9265   if (FunctionDecl *FD = Target->getAsFunction()) {
9266     NamedDecl *OldDecl = nullptr;
9267     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9268                           /*IsForUsingDecl*/ true)) {
9269     case Ovl_Overload:
9270       return false;
9271 
9272     case Ovl_NonFunction:
9273       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9274       break;
9275 
9276     // We found a decl with the exact signature.
9277     case Ovl_Match:
9278       // If we're in a record, we want to hide the target, so we
9279       // return true (without a diagnostic) to tell the caller not to
9280       // build a shadow decl.
9281       if (CurContext->isRecord())
9282         return true;
9283 
9284       // If we're not in a record, this is an error.
9285       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9286       break;
9287     }
9288 
9289     Diag(Target->getLocation(), diag::note_using_decl_target);
9290     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9291     Using->setInvalidDecl();
9292     return true;
9293   }
9294 
9295   // Target is not a function.
9296 
9297   if (isa<TagDecl>(Target)) {
9298     // No conflict between a tag and a non-tag.
9299     if (!Tag) return false;
9300 
9301     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9302     Diag(Target->getLocation(), diag::note_using_decl_target);
9303     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9304     Using->setInvalidDecl();
9305     return true;
9306   }
9307 
9308   // No conflict between a tag and a non-tag.
9309   if (!NonTag) return false;
9310 
9311   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9312   Diag(Target->getLocation(), diag::note_using_decl_target);
9313   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9314   Using->setInvalidDecl();
9315   return true;
9316 }
9317 
9318 /// Determine whether a direct base class is a virtual base class.
9319 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9320   if (!Derived->getNumVBases())
9321     return false;
9322   for (auto &B : Derived->bases())
9323     if (B.getType()->getAsCXXRecordDecl() == Base)
9324       return B.isVirtual();
9325   llvm_unreachable("not a direct base class");
9326 }
9327 
9328 /// Builds a shadow declaration corresponding to a 'using' declaration.
9329 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9330                                             UsingDecl *UD,
9331                                             NamedDecl *Orig,
9332                                             UsingShadowDecl *PrevDecl) {
9333   // If we resolved to another shadow declaration, just coalesce them.
9334   NamedDecl *Target = Orig;
9335   if (isa<UsingShadowDecl>(Target)) {
9336     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9337     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9338   }
9339 
9340   NamedDecl *NonTemplateTarget = Target;
9341   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9342     NonTemplateTarget = TargetTD->getTemplatedDecl();
9343 
9344   UsingShadowDecl *Shadow;
9345   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9346     bool IsVirtualBase =
9347         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9348                             UD->getQualifier()->getAsRecordDecl());
9349     Shadow = ConstructorUsingShadowDecl::Create(
9350         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9351   } else {
9352     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9353                                      Target);
9354   }
9355   UD->addShadowDecl(Shadow);
9356 
9357   Shadow->setAccess(UD->getAccess());
9358   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9359     Shadow->setInvalidDecl();
9360 
9361   Shadow->setPreviousDecl(PrevDecl);
9362 
9363   if (S)
9364     PushOnScopeChains(Shadow, S);
9365   else
9366     CurContext->addDecl(Shadow);
9367 
9368 
9369   return Shadow;
9370 }
9371 
9372 /// Hides a using shadow declaration.  This is required by the current
9373 /// using-decl implementation when a resolvable using declaration in a
9374 /// class is followed by a declaration which would hide or override
9375 /// one or more of the using decl's targets; for example:
9376 ///
9377 ///   struct Base { void foo(int); };
9378 ///   struct Derived : Base {
9379 ///     using Base::foo;
9380 ///     void foo(int);
9381 ///   };
9382 ///
9383 /// The governing language is C++03 [namespace.udecl]p12:
9384 ///
9385 ///   When a using-declaration brings names from a base class into a
9386 ///   derived class scope, member functions in the derived class
9387 ///   override and/or hide member functions with the same name and
9388 ///   parameter types in a base class (rather than conflicting).
9389 ///
9390 /// There are two ways to implement this:
9391 ///   (1) optimistically create shadow decls when they're not hidden
9392 ///       by existing declarations, or
9393 ///   (2) don't create any shadow decls (or at least don't make them
9394 ///       visible) until we've fully parsed/instantiated the class.
9395 /// The problem with (1) is that we might have to retroactively remove
9396 /// a shadow decl, which requires several O(n) operations because the
9397 /// decl structures are (very reasonably) not designed for removal.
9398 /// (2) avoids this but is very fiddly and phase-dependent.
9399 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9400   if (Shadow->getDeclName().getNameKind() ==
9401         DeclarationName::CXXConversionFunctionName)
9402     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9403 
9404   // Remove it from the DeclContext...
9405   Shadow->getDeclContext()->removeDecl(Shadow);
9406 
9407   // ...and the scope, if applicable...
9408   if (S) {
9409     S->RemoveDecl(Shadow);
9410     IdResolver.RemoveDecl(Shadow);
9411   }
9412 
9413   // ...and the using decl.
9414   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9415 
9416   // TODO: complain somehow if Shadow was used.  It shouldn't
9417   // be possible for this to happen, because...?
9418 }
9419 
9420 /// Find the base specifier for a base class with the given type.
9421 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9422                                                 QualType DesiredBase,
9423                                                 bool &AnyDependentBases) {
9424   // Check whether the named type is a direct base class.
9425   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9426   for (auto &Base : Derived->bases()) {
9427     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9428     if (CanonicalDesiredBase == BaseType)
9429       return &Base;
9430     if (BaseType->isDependentType())
9431       AnyDependentBases = true;
9432   }
9433   return nullptr;
9434 }
9435 
9436 namespace {
9437 class UsingValidatorCCC : public CorrectionCandidateCallback {
9438 public:
9439   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9440                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9441       : HasTypenameKeyword(HasTypenameKeyword),
9442         IsInstantiation(IsInstantiation), OldNNS(NNS),
9443         RequireMemberOf(RequireMemberOf) {}
9444 
9445   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9446     NamedDecl *ND = Candidate.getCorrectionDecl();
9447 
9448     // Keywords are not valid here.
9449     if (!ND || isa<NamespaceDecl>(ND))
9450       return false;
9451 
9452     // Completely unqualified names are invalid for a 'using' declaration.
9453     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9454       return false;
9455 
9456     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9457     // reject.
9458 
9459     if (RequireMemberOf) {
9460       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9461       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9462         // No-one ever wants a using-declaration to name an injected-class-name
9463         // of a base class, unless they're declaring an inheriting constructor.
9464         ASTContext &Ctx = ND->getASTContext();
9465         if (!Ctx.getLangOpts().CPlusPlus11)
9466           return false;
9467         QualType FoundType = Ctx.getRecordType(FoundRecord);
9468 
9469         // Check that the injected-class-name is named as a member of its own
9470         // type; we don't want to suggest 'using Derived::Base;', since that
9471         // means something else.
9472         NestedNameSpecifier *Specifier =
9473             Candidate.WillReplaceSpecifier()
9474                 ? Candidate.getCorrectionSpecifier()
9475                 : OldNNS;
9476         if (!Specifier->getAsType() ||
9477             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9478           return false;
9479 
9480         // Check that this inheriting constructor declaration actually names a
9481         // direct base class of the current class.
9482         bool AnyDependentBases = false;
9483         if (!findDirectBaseWithType(RequireMemberOf,
9484                                     Ctx.getRecordType(FoundRecord),
9485                                     AnyDependentBases) &&
9486             !AnyDependentBases)
9487           return false;
9488       } else {
9489         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9490         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9491           return false;
9492 
9493         // FIXME: Check that the base class member is accessible?
9494       }
9495     } else {
9496       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9497       if (FoundRecord && FoundRecord->isInjectedClassName())
9498         return false;
9499     }
9500 
9501     if (isa<TypeDecl>(ND))
9502       return HasTypenameKeyword || !IsInstantiation;
9503 
9504     return !HasTypenameKeyword;
9505   }
9506 
9507 private:
9508   bool HasTypenameKeyword;
9509   bool IsInstantiation;
9510   NestedNameSpecifier *OldNNS;
9511   CXXRecordDecl *RequireMemberOf;
9512 };
9513 } // end anonymous namespace
9514 
9515 /// Builds a using declaration.
9516 ///
9517 /// \param IsInstantiation - Whether this call arises from an
9518 ///   instantiation of an unresolved using declaration.  We treat
9519 ///   the lookup differently for these declarations.
9520 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9521                                        SourceLocation UsingLoc,
9522                                        bool HasTypenameKeyword,
9523                                        SourceLocation TypenameLoc,
9524                                        CXXScopeSpec &SS,
9525                                        DeclarationNameInfo NameInfo,
9526                                        SourceLocation EllipsisLoc,
9527                                        AttributeList *AttrList,
9528                                        bool IsInstantiation) {
9529   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9530   SourceLocation IdentLoc = NameInfo.getLoc();
9531   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9532 
9533   // FIXME: We ignore attributes for now.
9534 
9535   // For an inheriting constructor declaration, the name of the using
9536   // declaration is the name of a constructor in this class, not in the
9537   // base class.
9538   DeclarationNameInfo UsingName = NameInfo;
9539   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9540     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9541       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9542           Context.getCanonicalType(Context.getRecordType(RD))));
9543 
9544   // Do the redeclaration lookup in the current scope.
9545   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9546                         ForVisibleRedeclaration);
9547   Previous.setHideTags(false);
9548   if (S) {
9549     LookupName(Previous, S);
9550 
9551     // It is really dumb that we have to do this.
9552     LookupResult::Filter F = Previous.makeFilter();
9553     while (F.hasNext()) {
9554       NamedDecl *D = F.next();
9555       if (!isDeclInScope(D, CurContext, S))
9556         F.erase();
9557       // If we found a local extern declaration that's not ordinarily visible,
9558       // and this declaration is being added to a non-block scope, ignore it.
9559       // We're only checking for scope conflicts here, not also for violations
9560       // of the linkage rules.
9561       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9562                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9563         F.erase();
9564     }
9565     F.done();
9566   } else {
9567     assert(IsInstantiation && "no scope in non-instantiation");
9568     if (CurContext->isRecord())
9569       LookupQualifiedName(Previous, CurContext);
9570     else {
9571       // No redeclaration check is needed here; in non-member contexts we
9572       // diagnosed all possible conflicts with other using-declarations when
9573       // building the template:
9574       //
9575       // For a dependent non-type using declaration, the only valid case is
9576       // if we instantiate to a single enumerator. We check for conflicts
9577       // between shadow declarations we introduce, and we check in the template
9578       // definition for conflicts between a non-type using declaration and any
9579       // other declaration, which together covers all cases.
9580       //
9581       // A dependent typename using declaration will never successfully
9582       // instantiate, since it will always name a class member, so we reject
9583       // that in the template definition.
9584     }
9585   }
9586 
9587   // Check for invalid redeclarations.
9588   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9589                                   SS, IdentLoc, Previous))
9590     return nullptr;
9591 
9592   // Check for bad qualifiers.
9593   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9594                               IdentLoc))
9595     return nullptr;
9596 
9597   DeclContext *LookupContext = computeDeclContext(SS);
9598   NamedDecl *D;
9599   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9600   if (!LookupContext || EllipsisLoc.isValid()) {
9601     if (HasTypenameKeyword) {
9602       // FIXME: not all declaration name kinds are legal here
9603       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9604                                               UsingLoc, TypenameLoc,
9605                                               QualifierLoc,
9606                                               IdentLoc, NameInfo.getName(),
9607                                               EllipsisLoc);
9608     } else {
9609       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9610                                            QualifierLoc, NameInfo, EllipsisLoc);
9611     }
9612     D->setAccess(AS);
9613     CurContext->addDecl(D);
9614     return D;
9615   }
9616 
9617   auto Build = [&](bool Invalid) {
9618     UsingDecl *UD =
9619         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9620                           UsingName, HasTypenameKeyword);
9621     UD->setAccess(AS);
9622     CurContext->addDecl(UD);
9623     UD->setInvalidDecl(Invalid);
9624     return UD;
9625   };
9626   auto BuildInvalid = [&]{ return Build(true); };
9627   auto BuildValid = [&]{ return Build(false); };
9628 
9629   if (RequireCompleteDeclContext(SS, LookupContext))
9630     return BuildInvalid();
9631 
9632   // Look up the target name.
9633   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9634 
9635   // Unlike most lookups, we don't always want to hide tag
9636   // declarations: tag names are visible through the using declaration
9637   // even if hidden by ordinary names, *except* in a dependent context
9638   // where it's important for the sanity of two-phase lookup.
9639   if (!IsInstantiation)
9640     R.setHideTags(false);
9641 
9642   // For the purposes of this lookup, we have a base object type
9643   // equal to that of the current context.
9644   if (CurContext->isRecord()) {
9645     R.setBaseObjectType(
9646                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9647   }
9648 
9649   LookupQualifiedName(R, LookupContext);
9650 
9651   // Try to correct typos if possible. If constructor name lookup finds no
9652   // results, that means the named class has no explicit constructors, and we
9653   // suppressed declaring implicit ones (probably because it's dependent or
9654   // invalid).
9655   if (R.empty() &&
9656       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9657     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9658     // it will believe that glibc provides a ::gets in cases where it does not,
9659     // and will try to pull it into namespace std with a using-declaration.
9660     // Just ignore the using-declaration in that case.
9661     auto *II = NameInfo.getName().getAsIdentifierInfo();
9662     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9663         CurContext->isStdNamespace() &&
9664         isa<TranslationUnitDecl>(LookupContext) &&
9665         getSourceManager().isInSystemHeader(UsingLoc))
9666       return nullptr;
9667     if (TypoCorrection Corrected = CorrectTypo(
9668             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9669             llvm::make_unique<UsingValidatorCCC>(
9670                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9671                 dyn_cast<CXXRecordDecl>(CurContext)),
9672             CTK_ErrorRecovery)) {
9673       // We reject candidates where DroppedSpecifier == true, hence the
9674       // literal '0' below.
9675       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9676                                 << NameInfo.getName() << LookupContext << 0
9677                                 << SS.getRange());
9678 
9679       // If we picked a correction with no attached Decl we can't do anything
9680       // useful with it, bail out.
9681       NamedDecl *ND = Corrected.getCorrectionDecl();
9682       if (!ND)
9683         return BuildInvalid();
9684 
9685       // If we corrected to an inheriting constructor, handle it as one.
9686       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9687       if (RD && RD->isInjectedClassName()) {
9688         // The parent of the injected class name is the class itself.
9689         RD = cast<CXXRecordDecl>(RD->getParent());
9690 
9691         // Fix up the information we'll use to build the using declaration.
9692         if (Corrected.WillReplaceSpecifier()) {
9693           NestedNameSpecifierLocBuilder Builder;
9694           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9695                               QualifierLoc.getSourceRange());
9696           QualifierLoc = Builder.getWithLocInContext(Context);
9697         }
9698 
9699         // In this case, the name we introduce is the name of a derived class
9700         // constructor.
9701         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9702         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9703             Context.getCanonicalType(Context.getRecordType(CurClass))));
9704         UsingName.setNamedTypeInfo(nullptr);
9705         for (auto *Ctor : LookupConstructors(RD))
9706           R.addDecl(Ctor);
9707         R.resolveKind();
9708       } else {
9709         // FIXME: Pick up all the declarations if we found an overloaded
9710         // function.
9711         UsingName.setName(ND->getDeclName());
9712         R.addDecl(ND);
9713       }
9714     } else {
9715       Diag(IdentLoc, diag::err_no_member)
9716         << NameInfo.getName() << LookupContext << SS.getRange();
9717       return BuildInvalid();
9718     }
9719   }
9720 
9721   if (R.isAmbiguous())
9722     return BuildInvalid();
9723 
9724   if (HasTypenameKeyword) {
9725     // If we asked for a typename and got a non-type decl, error out.
9726     if (!R.getAsSingle<TypeDecl>()) {
9727       Diag(IdentLoc, diag::err_using_typename_non_type);
9728       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9729         Diag((*I)->getUnderlyingDecl()->getLocation(),
9730              diag::note_using_decl_target);
9731       return BuildInvalid();
9732     }
9733   } else {
9734     // If we asked for a non-typename and we got a type, error out,
9735     // but only if this is an instantiation of an unresolved using
9736     // decl.  Otherwise just silently find the type name.
9737     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9738       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9739       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9740       return BuildInvalid();
9741     }
9742   }
9743 
9744   // C++14 [namespace.udecl]p6:
9745   // A using-declaration shall not name a namespace.
9746   if (R.getAsSingle<NamespaceDecl>()) {
9747     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9748       << SS.getRange();
9749     return BuildInvalid();
9750   }
9751 
9752   // C++14 [namespace.udecl]p7:
9753   // A using-declaration shall not name a scoped enumerator.
9754   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9755     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9756       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9757         << SS.getRange();
9758       return BuildInvalid();
9759     }
9760   }
9761 
9762   UsingDecl *UD = BuildValid();
9763 
9764   // Some additional rules apply to inheriting constructors.
9765   if (UsingName.getName().getNameKind() ==
9766         DeclarationName::CXXConstructorName) {
9767     // Suppress access diagnostics; the access check is instead performed at the
9768     // point of use for an inheriting constructor.
9769     R.suppressDiagnostics();
9770     if (CheckInheritingConstructorUsingDecl(UD))
9771       return UD;
9772   }
9773 
9774   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9775     UsingShadowDecl *PrevDecl = nullptr;
9776     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9777       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9778   }
9779 
9780   return UD;
9781 }
9782 
9783 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9784                                     ArrayRef<NamedDecl *> Expansions) {
9785   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9786          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9787          isa<UsingPackDecl>(InstantiatedFrom));
9788 
9789   auto *UPD =
9790       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9791   UPD->setAccess(InstantiatedFrom->getAccess());
9792   CurContext->addDecl(UPD);
9793   return UPD;
9794 }
9795 
9796 /// Additional checks for a using declaration referring to a constructor name.
9797 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9798   assert(!UD->hasTypename() && "expecting a constructor name");
9799 
9800   const Type *SourceType = UD->getQualifier()->getAsType();
9801   assert(SourceType &&
9802          "Using decl naming constructor doesn't have type in scope spec.");
9803   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9804 
9805   // Check whether the named type is a direct base class.
9806   bool AnyDependentBases = false;
9807   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9808                                       AnyDependentBases);
9809   if (!Base && !AnyDependentBases) {
9810     Diag(UD->getUsingLoc(),
9811          diag::err_using_decl_constructor_not_in_direct_base)
9812       << UD->getNameInfo().getSourceRange()
9813       << QualType(SourceType, 0) << TargetClass;
9814     UD->setInvalidDecl();
9815     return true;
9816   }
9817 
9818   if (Base)
9819     Base->setInheritConstructors();
9820 
9821   return false;
9822 }
9823 
9824 /// Checks that the given using declaration is not an invalid
9825 /// redeclaration.  Note that this is checking only for the using decl
9826 /// itself, not for any ill-formedness among the UsingShadowDecls.
9827 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9828                                        bool HasTypenameKeyword,
9829                                        const CXXScopeSpec &SS,
9830                                        SourceLocation NameLoc,
9831                                        const LookupResult &Prev) {
9832   NestedNameSpecifier *Qual = SS.getScopeRep();
9833 
9834   // C++03 [namespace.udecl]p8:
9835   // C++0x [namespace.udecl]p10:
9836   //   A using-declaration is a declaration and can therefore be used
9837   //   repeatedly where (and only where) multiple declarations are
9838   //   allowed.
9839   //
9840   // That's in non-member contexts.
9841   if (!CurContext->getRedeclContext()->isRecord()) {
9842     // A dependent qualifier outside a class can only ever resolve to an
9843     // enumeration type. Therefore it conflicts with any other non-type
9844     // declaration in the same scope.
9845     // FIXME: How should we check for dependent type-type conflicts at block
9846     // scope?
9847     if (Qual->isDependent() && !HasTypenameKeyword) {
9848       for (auto *D : Prev) {
9849         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9850           bool OldCouldBeEnumerator =
9851               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9852           Diag(NameLoc,
9853                OldCouldBeEnumerator ? diag::err_redefinition
9854                                     : diag::err_redefinition_different_kind)
9855               << Prev.getLookupName();
9856           Diag(D->getLocation(), diag::note_previous_definition);
9857           return true;
9858         }
9859       }
9860     }
9861     return false;
9862   }
9863 
9864   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9865     NamedDecl *D = *I;
9866 
9867     bool DTypename;
9868     NestedNameSpecifier *DQual;
9869     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9870       DTypename = UD->hasTypename();
9871       DQual = UD->getQualifier();
9872     } else if (UnresolvedUsingValueDecl *UD
9873                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9874       DTypename = false;
9875       DQual = UD->getQualifier();
9876     } else if (UnresolvedUsingTypenameDecl *UD
9877                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9878       DTypename = true;
9879       DQual = UD->getQualifier();
9880     } else continue;
9881 
9882     // using decls differ if one says 'typename' and the other doesn't.
9883     // FIXME: non-dependent using decls?
9884     if (HasTypenameKeyword != DTypename) continue;
9885 
9886     // using decls differ if they name different scopes (but note that
9887     // template instantiation can cause this check to trigger when it
9888     // didn't before instantiation).
9889     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9890         Context.getCanonicalNestedNameSpecifier(DQual))
9891       continue;
9892 
9893     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9894     Diag(D->getLocation(), diag::note_using_decl) << 1;
9895     return true;
9896   }
9897 
9898   return false;
9899 }
9900 
9901 
9902 /// Checks that the given nested-name qualifier used in a using decl
9903 /// in the current context is appropriately related to the current
9904 /// scope.  If an error is found, diagnoses it and returns true.
9905 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9906                                    bool HasTypename,
9907                                    const CXXScopeSpec &SS,
9908                                    const DeclarationNameInfo &NameInfo,
9909                                    SourceLocation NameLoc) {
9910   DeclContext *NamedContext = computeDeclContext(SS);
9911 
9912   if (!CurContext->isRecord()) {
9913     // C++03 [namespace.udecl]p3:
9914     // C++0x [namespace.udecl]p8:
9915     //   A using-declaration for a class member shall be a member-declaration.
9916 
9917     // If we weren't able to compute a valid scope, it might validly be a
9918     // dependent class scope or a dependent enumeration unscoped scope. If
9919     // we have a 'typename' keyword, the scope must resolve to a class type.
9920     if ((HasTypename && !NamedContext) ||
9921         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9922       auto *RD = NamedContext
9923                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9924                      : nullptr;
9925       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9926         RD = nullptr;
9927 
9928       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9929         << SS.getRange();
9930 
9931       // If we have a complete, non-dependent source type, try to suggest a
9932       // way to get the same effect.
9933       if (!RD)
9934         return true;
9935 
9936       // Find what this using-declaration was referring to.
9937       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9938       R.setHideTags(false);
9939       R.suppressDiagnostics();
9940       LookupQualifiedName(R, RD);
9941 
9942       if (R.getAsSingle<TypeDecl>()) {
9943         if (getLangOpts().CPlusPlus11) {
9944           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9945           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9946             << 0 // alias declaration
9947             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9948                                           NameInfo.getName().getAsString() +
9949                                               " = ");
9950         } else {
9951           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9952           SourceLocation InsertLoc =
9953               getLocForEndOfToken(NameInfo.getLocEnd());
9954           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9955             << 1 // typedef declaration
9956             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9957             << FixItHint::CreateInsertion(
9958                    InsertLoc, " " + NameInfo.getName().getAsString());
9959         }
9960       } else if (R.getAsSingle<VarDecl>()) {
9961         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9962         // repeating the type of the static data member here.
9963         FixItHint FixIt;
9964         if (getLangOpts().CPlusPlus11) {
9965           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9966           FixIt = FixItHint::CreateReplacement(
9967               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9968         }
9969 
9970         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9971           << 2 // reference declaration
9972           << FixIt;
9973       } else if (R.getAsSingle<EnumConstantDecl>()) {
9974         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9975         // repeating the type of the enumeration here, and we can't do so if
9976         // the type is anonymous.
9977         FixItHint FixIt;
9978         if (getLangOpts().CPlusPlus11) {
9979           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9980           FixIt = FixItHint::CreateReplacement(
9981               UsingLoc,
9982               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9983         }
9984 
9985         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9986           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9987           << FixIt;
9988       }
9989       return true;
9990     }
9991 
9992     // Otherwise, this might be valid.
9993     return false;
9994   }
9995 
9996   // The current scope is a record.
9997 
9998   // If the named context is dependent, we can't decide much.
9999   if (!NamedContext) {
10000     // FIXME: in C++0x, we can diagnose if we can prove that the
10001     // nested-name-specifier does not refer to a base class, which is
10002     // still possible in some cases.
10003 
10004     // Otherwise we have to conservatively report that things might be
10005     // okay.
10006     return false;
10007   }
10008 
10009   if (!NamedContext->isRecord()) {
10010     // Ideally this would point at the last name in the specifier,
10011     // but we don't have that level of source info.
10012     Diag(SS.getRange().getBegin(),
10013          diag::err_using_decl_nested_name_specifier_is_not_class)
10014       << SS.getScopeRep() << SS.getRange();
10015     return true;
10016   }
10017 
10018   if (!NamedContext->isDependentContext() &&
10019       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10020     return true;
10021 
10022   if (getLangOpts().CPlusPlus11) {
10023     // C++11 [namespace.udecl]p3:
10024     //   In a using-declaration used as a member-declaration, the
10025     //   nested-name-specifier shall name a base class of the class
10026     //   being defined.
10027 
10028     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10029                                  cast<CXXRecordDecl>(NamedContext))) {
10030       if (CurContext == NamedContext) {
10031         Diag(NameLoc,
10032              diag::err_using_decl_nested_name_specifier_is_current_class)
10033           << SS.getRange();
10034         return true;
10035       }
10036 
10037       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10038         Diag(SS.getRange().getBegin(),
10039              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10040           << SS.getScopeRep()
10041           << cast<CXXRecordDecl>(CurContext)
10042           << SS.getRange();
10043       }
10044       return true;
10045     }
10046 
10047     return false;
10048   }
10049 
10050   // C++03 [namespace.udecl]p4:
10051   //   A using-declaration used as a member-declaration shall refer
10052   //   to a member of a base class of the class being defined [etc.].
10053 
10054   // Salient point: SS doesn't have to name a base class as long as
10055   // lookup only finds members from base classes.  Therefore we can
10056   // diagnose here only if we can prove that that can't happen,
10057   // i.e. if the class hierarchies provably don't intersect.
10058 
10059   // TODO: it would be nice if "definitely valid" results were cached
10060   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10061   // need to be repeated.
10062 
10063   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10064   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10065     Bases.insert(Base);
10066     return true;
10067   };
10068 
10069   // Collect all bases. Return false if we find a dependent base.
10070   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10071     return false;
10072 
10073   // Returns true if the base is dependent or is one of the accumulated base
10074   // classes.
10075   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10076     return !Bases.count(Base);
10077   };
10078 
10079   // Return false if the class has a dependent base or if it or one
10080   // of its bases is present in the base set of the current context.
10081   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10082       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10083     return false;
10084 
10085   Diag(SS.getRange().getBegin(),
10086        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10087     << SS.getScopeRep()
10088     << cast<CXXRecordDecl>(CurContext)
10089     << SS.getRange();
10090 
10091   return true;
10092 }
10093 
10094 Decl *Sema::ActOnAliasDeclaration(Scope *S,
10095                                   AccessSpecifier AS,
10096                                   MultiTemplateParamsArg TemplateParamLists,
10097                                   SourceLocation UsingLoc,
10098                                   UnqualifiedId &Name,
10099                                   AttributeList *AttrList,
10100                                   TypeResult Type,
10101                                   Decl *DeclFromDeclSpec) {
10102   // Skip up to the relevant declaration scope.
10103   while (S->isTemplateParamScope())
10104     S = S->getParent();
10105   assert((S->getFlags() & Scope::DeclScope) &&
10106          "got alias-declaration outside of declaration scope");
10107 
10108   if (Type.isInvalid())
10109     return nullptr;
10110 
10111   bool Invalid = false;
10112   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10113   TypeSourceInfo *TInfo = nullptr;
10114   GetTypeFromParser(Type.get(), &TInfo);
10115 
10116   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10117     return nullptr;
10118 
10119   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10120                                       UPPC_DeclarationType)) {
10121     Invalid = true;
10122     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10123                                              TInfo->getTypeLoc().getBeginLoc());
10124   }
10125 
10126   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10127                         TemplateParamLists.size()
10128                             ? forRedeclarationInCurContext()
10129                             : ForVisibleRedeclaration);
10130   LookupName(Previous, S);
10131 
10132   // Warn about shadowing the name of a template parameter.
10133   if (Previous.isSingleResult() &&
10134       Previous.getFoundDecl()->isTemplateParameter()) {
10135     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10136     Previous.clear();
10137   }
10138 
10139   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10140          "name in alias declaration must be an identifier");
10141   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10142                                                Name.StartLocation,
10143                                                Name.Identifier, TInfo);
10144 
10145   NewTD->setAccess(AS);
10146 
10147   if (Invalid)
10148     NewTD->setInvalidDecl();
10149 
10150   ProcessDeclAttributeList(S, NewTD, AttrList);
10151   AddPragmaAttributes(S, NewTD);
10152 
10153   CheckTypedefForVariablyModifiedType(S, NewTD);
10154   Invalid |= NewTD->isInvalidDecl();
10155 
10156   bool Redeclaration = false;
10157 
10158   NamedDecl *NewND;
10159   if (TemplateParamLists.size()) {
10160     TypeAliasTemplateDecl *OldDecl = nullptr;
10161     TemplateParameterList *OldTemplateParams = nullptr;
10162 
10163     if (TemplateParamLists.size() != 1) {
10164       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10165         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10166          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10167     }
10168     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10169 
10170     // Check that we can declare a template here.
10171     if (CheckTemplateDeclScope(S, TemplateParams))
10172       return nullptr;
10173 
10174     // Only consider previous declarations in the same scope.
10175     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10176                          /*ExplicitInstantiationOrSpecialization*/false);
10177     if (!Previous.empty()) {
10178       Redeclaration = true;
10179 
10180       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10181       if (!OldDecl && !Invalid) {
10182         Diag(UsingLoc, diag::err_redefinition_different_kind)
10183           << Name.Identifier;
10184 
10185         NamedDecl *OldD = Previous.getRepresentativeDecl();
10186         if (OldD->getLocation().isValid())
10187           Diag(OldD->getLocation(), diag::note_previous_definition);
10188 
10189         Invalid = true;
10190       }
10191 
10192       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10193         if (TemplateParameterListsAreEqual(TemplateParams,
10194                                            OldDecl->getTemplateParameters(),
10195                                            /*Complain=*/true,
10196                                            TPL_TemplateMatch))
10197           OldTemplateParams = OldDecl->getTemplateParameters();
10198         else
10199           Invalid = true;
10200 
10201         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10202         if (!Invalid &&
10203             !Context.hasSameType(OldTD->getUnderlyingType(),
10204                                  NewTD->getUnderlyingType())) {
10205           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10206           // but we can't reasonably accept it.
10207           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10208             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10209           if (OldTD->getLocation().isValid())
10210             Diag(OldTD->getLocation(), diag::note_previous_definition);
10211           Invalid = true;
10212         }
10213       }
10214     }
10215 
10216     // Merge any previous default template arguments into our parameters,
10217     // and check the parameter list.
10218     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10219                                    TPC_TypeAliasTemplate))
10220       return nullptr;
10221 
10222     TypeAliasTemplateDecl *NewDecl =
10223       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10224                                     Name.Identifier, TemplateParams,
10225                                     NewTD);
10226     NewTD->setDescribedAliasTemplate(NewDecl);
10227 
10228     NewDecl->setAccess(AS);
10229 
10230     if (Invalid)
10231       NewDecl->setInvalidDecl();
10232     else if (OldDecl) {
10233       NewDecl->setPreviousDecl(OldDecl);
10234       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10235     }
10236 
10237     NewND = NewDecl;
10238   } else {
10239     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10240       setTagNameForLinkagePurposes(TD, NewTD);
10241       handleTagNumbering(TD, S);
10242     }
10243     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10244     NewND = NewTD;
10245   }
10246 
10247   PushOnScopeChains(NewND, S);
10248   ActOnDocumentableDecl(NewND);
10249   return NewND;
10250 }
10251 
10252 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10253                                    SourceLocation AliasLoc,
10254                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10255                                    SourceLocation IdentLoc,
10256                                    IdentifierInfo *Ident) {
10257 
10258   // Lookup the namespace name.
10259   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10260   LookupParsedName(R, S, &SS);
10261 
10262   if (R.isAmbiguous())
10263     return nullptr;
10264 
10265   if (R.empty()) {
10266     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10267       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10268       return nullptr;
10269     }
10270   }
10271   assert(!R.isAmbiguous() && !R.empty());
10272   NamedDecl *ND = R.getRepresentativeDecl();
10273 
10274   // Check if we have a previous declaration with the same name.
10275   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10276                      ForVisibleRedeclaration);
10277   LookupName(PrevR, S);
10278 
10279   // Check we're not shadowing a template parameter.
10280   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10281     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10282     PrevR.clear();
10283   }
10284 
10285   // Filter out any other lookup result from an enclosing scope.
10286   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10287                        /*AllowInlineNamespace*/false);
10288 
10289   // Find the previous declaration and check that we can redeclare it.
10290   NamespaceAliasDecl *Prev = nullptr;
10291   if (PrevR.isSingleResult()) {
10292     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10293     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10294       // We already have an alias with the same name that points to the same
10295       // namespace; check that it matches.
10296       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10297         Prev = AD;
10298       } else if (isVisible(PrevDecl)) {
10299         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10300           << Alias;
10301         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10302           << AD->getNamespace();
10303         return nullptr;
10304       }
10305     } else if (isVisible(PrevDecl)) {
10306       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10307                             ? diag::err_redefinition
10308                             : diag::err_redefinition_different_kind;
10309       Diag(AliasLoc, DiagID) << Alias;
10310       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10311       return nullptr;
10312     }
10313   }
10314 
10315   // The use of a nested name specifier may trigger deprecation warnings.
10316   DiagnoseUseOfDecl(ND, IdentLoc);
10317 
10318   NamespaceAliasDecl *AliasDecl =
10319     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10320                                Alias, SS.getWithLocInContext(Context),
10321                                IdentLoc, ND);
10322   if (Prev)
10323     AliasDecl->setPreviousDecl(Prev);
10324 
10325   PushOnScopeChains(AliasDecl, S);
10326   return AliasDecl;
10327 }
10328 
10329 namespace {
10330 struct SpecialMemberExceptionSpecInfo
10331     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10332   SourceLocation Loc;
10333   Sema::ImplicitExceptionSpecification ExceptSpec;
10334 
10335   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10336                                  Sema::CXXSpecialMember CSM,
10337                                  Sema::InheritedConstructorInfo *ICI,
10338                                  SourceLocation Loc)
10339       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10340 
10341   bool visitBase(CXXBaseSpecifier *Base);
10342   bool visitField(FieldDecl *FD);
10343 
10344   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10345                            unsigned Quals);
10346 
10347   void visitSubobjectCall(Subobject Subobj,
10348                           Sema::SpecialMemberOverloadResult SMOR);
10349 };
10350 }
10351 
10352 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10353   auto *RT = Base->getType()->getAs<RecordType>();
10354   if (!RT)
10355     return false;
10356 
10357   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10358   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10359   if (auto *BaseCtor = SMOR.getMethod()) {
10360     visitSubobjectCall(Base, BaseCtor);
10361     return false;
10362   }
10363 
10364   visitClassSubobject(BaseClass, Base, 0);
10365   return false;
10366 }
10367 
10368 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10369   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10370     Expr *E = FD->getInClassInitializer();
10371     if (!E)
10372       // FIXME: It's a little wasteful to build and throw away a
10373       // CXXDefaultInitExpr here.
10374       // FIXME: We should have a single context note pointing at Loc, and
10375       // this location should be MD->getLocation() instead, since that's
10376       // the location where we actually use the default init expression.
10377       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10378     if (E)
10379       ExceptSpec.CalledExpr(E);
10380   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10381                             ->getAs<RecordType>()) {
10382     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10383                         FD->getType().getCVRQualifiers());
10384   }
10385   return false;
10386 }
10387 
10388 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10389                                                          Subobject Subobj,
10390                                                          unsigned Quals) {
10391   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10392   bool IsMutable = Field && Field->isMutable();
10393   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10394 }
10395 
10396 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10397     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10398   // Note, if lookup fails, it doesn't matter what exception specification we
10399   // choose because the special member will be deleted.
10400   if (CXXMethodDecl *MD = SMOR.getMethod())
10401     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10402 }
10403 
10404 static Sema::ImplicitExceptionSpecification
10405 ComputeDefaultedSpecialMemberExceptionSpec(
10406     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10407     Sema::InheritedConstructorInfo *ICI) {
10408   CXXRecordDecl *ClassDecl = MD->getParent();
10409 
10410   // C++ [except.spec]p14:
10411   //   An implicitly declared special member function (Clause 12) shall have an
10412   //   exception-specification. [...]
10413   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10414   if (ClassDecl->isInvalidDecl())
10415     return Info.ExceptSpec;
10416 
10417   // C++1z [except.spec]p7:
10418   //   [Look for exceptions thrown by] a constructor selected [...] to
10419   //   initialize a potentially constructed subobject,
10420   // C++1z [except.spec]p8:
10421   //   The exception specification for an implicitly-declared destructor, or a
10422   //   destructor without a noexcept-specifier, is potentially-throwing if and
10423   //   only if any of the destructors for any of its potentially constructed
10424   //   subojects is potentially throwing.
10425   // FIXME: We respect the first rule but ignore the "potentially constructed"
10426   // in the second rule to resolve a core issue (no number yet) that would have
10427   // us reject:
10428   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10429   //   struct B : A {};
10430   //   struct C : B { void f(); };
10431   // ... due to giving B::~B() a non-throwing exception specification.
10432   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10433                                 : Info.VisitAllBases);
10434 
10435   return Info.ExceptSpec;
10436 }
10437 
10438 namespace {
10439 /// RAII object to register a special member as being currently declared.
10440 struct DeclaringSpecialMember {
10441   Sema &S;
10442   Sema::SpecialMemberDecl D;
10443   Sema::ContextRAII SavedContext;
10444   bool WasAlreadyBeingDeclared;
10445 
10446   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10447       : S(S), D(RD, CSM), SavedContext(S, RD) {
10448     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10449     if (WasAlreadyBeingDeclared)
10450       // This almost never happens, but if it does, ensure that our cache
10451       // doesn't contain a stale result.
10452       S.SpecialMemberCache.clear();
10453     else {
10454       // Register a note to be produced if we encounter an error while
10455       // declaring the special member.
10456       Sema::CodeSynthesisContext Ctx;
10457       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10458       // FIXME: We don't have a location to use here. Using the class's
10459       // location maintains the fiction that we declare all special members
10460       // with the class, but (1) it's not clear that lying about that helps our
10461       // users understand what's going on, and (2) there may be outer contexts
10462       // on the stack (some of which are relevant) and printing them exposes
10463       // our lies.
10464       Ctx.PointOfInstantiation = RD->getLocation();
10465       Ctx.Entity = RD;
10466       Ctx.SpecialMember = CSM;
10467       S.pushCodeSynthesisContext(Ctx);
10468     }
10469   }
10470   ~DeclaringSpecialMember() {
10471     if (!WasAlreadyBeingDeclared) {
10472       S.SpecialMembersBeingDeclared.erase(D);
10473       S.popCodeSynthesisContext();
10474     }
10475   }
10476 
10477   /// \brief Are we already trying to declare this special member?
10478   bool isAlreadyBeingDeclared() const {
10479     return WasAlreadyBeingDeclared;
10480   }
10481 };
10482 }
10483 
10484 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10485   // Look up any existing declarations, but don't trigger declaration of all
10486   // implicit special members with this name.
10487   DeclarationName Name = FD->getDeclName();
10488   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10489                  ForExternalRedeclaration);
10490   for (auto *D : FD->getParent()->lookup(Name))
10491     if (auto *Acceptable = R.getAcceptableDecl(D))
10492       R.addDecl(Acceptable);
10493   R.resolveKind();
10494   R.suppressDiagnostics();
10495 
10496   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10497 }
10498 
10499 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10500                                                      CXXRecordDecl *ClassDecl) {
10501   // C++ [class.ctor]p5:
10502   //   A default constructor for a class X is a constructor of class X
10503   //   that can be called without an argument. If there is no
10504   //   user-declared constructor for class X, a default constructor is
10505   //   implicitly declared. An implicitly-declared default constructor
10506   //   is an inline public member of its class.
10507   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10508          "Should not build implicit default constructor!");
10509 
10510   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10511   if (DSM.isAlreadyBeingDeclared())
10512     return nullptr;
10513 
10514   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10515                                                      CXXDefaultConstructor,
10516                                                      false);
10517 
10518   // Create the actual constructor declaration.
10519   CanQualType ClassType
10520     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10521   SourceLocation ClassLoc = ClassDecl->getLocation();
10522   DeclarationName Name
10523     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10524   DeclarationNameInfo NameInfo(Name, ClassLoc);
10525   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10526       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10527       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10528       /*isImplicitlyDeclared=*/true, Constexpr);
10529   DefaultCon->setAccess(AS_public);
10530   DefaultCon->setDefaulted();
10531 
10532   if (getLangOpts().CUDA) {
10533     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10534                                             DefaultCon,
10535                                             /* ConstRHS */ false,
10536                                             /* Diagnose */ false);
10537   }
10538 
10539   // Build an exception specification pointing back at this constructor.
10540   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10541   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10542 
10543   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10544   // constructors is easy to compute.
10545   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10546 
10547   // Note that we have declared this constructor.
10548   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10549 
10550   Scope *S = getScopeForContext(ClassDecl);
10551   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10552 
10553   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10554     SetDeclDeleted(DefaultCon, ClassLoc);
10555 
10556   if (S)
10557     PushOnScopeChains(DefaultCon, S, false);
10558   ClassDecl->addDecl(DefaultCon);
10559 
10560   return DefaultCon;
10561 }
10562 
10563 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10564                                             CXXConstructorDecl *Constructor) {
10565   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10566           !Constructor->doesThisDeclarationHaveABody() &&
10567           !Constructor->isDeleted()) &&
10568     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10569   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10570     return;
10571 
10572   CXXRecordDecl *ClassDecl = Constructor->getParent();
10573   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10574 
10575   SynthesizedFunctionScope Scope(*this, Constructor);
10576 
10577   // The exception specification is needed because we are defining the
10578   // function.
10579   ResolveExceptionSpec(CurrentLocation,
10580                        Constructor->getType()->castAs<FunctionProtoType>());
10581   MarkVTableUsed(CurrentLocation, ClassDecl);
10582 
10583   // Add a context note for diagnostics produced after this point.
10584   Scope.addContextNote(CurrentLocation);
10585 
10586   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10587     Constructor->setInvalidDecl();
10588     return;
10589   }
10590 
10591   SourceLocation Loc = Constructor->getLocEnd().isValid()
10592                            ? Constructor->getLocEnd()
10593                            : Constructor->getLocation();
10594   Constructor->setBody(new (Context) CompoundStmt(Loc));
10595   Constructor->markUsed(Context);
10596 
10597   if (ASTMutationListener *L = getASTMutationListener()) {
10598     L->CompletedImplicitDefinition(Constructor);
10599   }
10600 
10601   DiagnoseUninitializedFields(*this, Constructor);
10602 }
10603 
10604 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10605   // Perform any delayed checks on exception specifications.
10606   CheckDelayedMemberExceptionSpecs();
10607 }
10608 
10609 /// Find or create the fake constructor we synthesize to model constructing an
10610 /// object of a derived class via a constructor of a base class.
10611 CXXConstructorDecl *
10612 Sema::findInheritingConstructor(SourceLocation Loc,
10613                                 CXXConstructorDecl *BaseCtor,
10614                                 ConstructorUsingShadowDecl *Shadow) {
10615   CXXRecordDecl *Derived = Shadow->getParent();
10616   SourceLocation UsingLoc = Shadow->getLocation();
10617 
10618   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10619   // For now we use the name of the base class constructor as a member of the
10620   // derived class to indicate a (fake) inherited constructor name.
10621   DeclarationName Name = BaseCtor->getDeclName();
10622 
10623   // Check to see if we already have a fake constructor for this inherited
10624   // constructor call.
10625   for (NamedDecl *Ctor : Derived->lookup(Name))
10626     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10627                                ->getInheritedConstructor()
10628                                .getConstructor(),
10629                            BaseCtor))
10630       return cast<CXXConstructorDecl>(Ctor);
10631 
10632   DeclarationNameInfo NameInfo(Name, UsingLoc);
10633   TypeSourceInfo *TInfo =
10634       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10635   FunctionProtoTypeLoc ProtoLoc =
10636       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10637 
10638   // Check the inherited constructor is valid and find the list of base classes
10639   // from which it was inherited.
10640   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10641 
10642   bool Constexpr =
10643       BaseCtor->isConstexpr() &&
10644       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10645                                         false, BaseCtor, &ICI);
10646 
10647   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10648       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10649       BaseCtor->isExplicit(), /*Inline=*/true,
10650       /*ImplicitlyDeclared=*/true, Constexpr,
10651       InheritedConstructor(Shadow, BaseCtor));
10652   if (Shadow->isInvalidDecl())
10653     DerivedCtor->setInvalidDecl();
10654 
10655   // Build an unevaluated exception specification for this fake constructor.
10656   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10657   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10658   EPI.ExceptionSpec.Type = EST_Unevaluated;
10659   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10660   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10661                                                FPT->getParamTypes(), EPI));
10662 
10663   // Build the parameter declarations.
10664   SmallVector<ParmVarDecl *, 16> ParamDecls;
10665   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10666     TypeSourceInfo *TInfo =
10667         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10668     ParmVarDecl *PD = ParmVarDecl::Create(
10669         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10670         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10671     PD->setScopeInfo(0, I);
10672     PD->setImplicit();
10673     // Ensure attributes are propagated onto parameters (this matters for
10674     // format, pass_object_size, ...).
10675     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10676     ParamDecls.push_back(PD);
10677     ProtoLoc.setParam(I, PD);
10678   }
10679 
10680   // Set up the new constructor.
10681   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10682   DerivedCtor->setAccess(BaseCtor->getAccess());
10683   DerivedCtor->setParams(ParamDecls);
10684   Derived->addDecl(DerivedCtor);
10685 
10686   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10687     SetDeclDeleted(DerivedCtor, UsingLoc);
10688 
10689   return DerivedCtor;
10690 }
10691 
10692 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10693   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10694                                Ctor->getInheritedConstructor().getShadowDecl());
10695   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10696                             /*Diagnose*/true);
10697 }
10698 
10699 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10700                                        CXXConstructorDecl *Constructor) {
10701   CXXRecordDecl *ClassDecl = Constructor->getParent();
10702   assert(Constructor->getInheritedConstructor() &&
10703          !Constructor->doesThisDeclarationHaveABody() &&
10704          !Constructor->isDeleted());
10705   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10706     return;
10707 
10708   // Initializations are performed "as if by a defaulted default constructor",
10709   // so enter the appropriate scope.
10710   SynthesizedFunctionScope Scope(*this, Constructor);
10711 
10712   // The exception specification is needed because we are defining the
10713   // function.
10714   ResolveExceptionSpec(CurrentLocation,
10715                        Constructor->getType()->castAs<FunctionProtoType>());
10716   MarkVTableUsed(CurrentLocation, ClassDecl);
10717 
10718   // Add a context note for diagnostics produced after this point.
10719   Scope.addContextNote(CurrentLocation);
10720 
10721   ConstructorUsingShadowDecl *Shadow =
10722       Constructor->getInheritedConstructor().getShadowDecl();
10723   CXXConstructorDecl *InheritedCtor =
10724       Constructor->getInheritedConstructor().getConstructor();
10725 
10726   // [class.inhctor.init]p1:
10727   //   initialization proceeds as if a defaulted default constructor is used to
10728   //   initialize the D object and each base class subobject from which the
10729   //   constructor was inherited
10730 
10731   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10732   CXXRecordDecl *RD = Shadow->getParent();
10733   SourceLocation InitLoc = Shadow->getLocation();
10734 
10735   // Build explicit initializers for all base classes from which the
10736   // constructor was inherited.
10737   SmallVector<CXXCtorInitializer*, 8> Inits;
10738   for (bool VBase : {false, true}) {
10739     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10740       if (B.isVirtual() != VBase)
10741         continue;
10742 
10743       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10744       if (!BaseRD)
10745         continue;
10746 
10747       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10748       if (!BaseCtor.first)
10749         continue;
10750 
10751       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10752       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10753           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10754 
10755       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10756       Inits.push_back(new (Context) CXXCtorInitializer(
10757           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10758           SourceLocation()));
10759     }
10760   }
10761 
10762   // We now proceed as if for a defaulted default constructor, with the relevant
10763   // initializers replaced.
10764 
10765   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
10766     Constructor->setInvalidDecl();
10767     return;
10768   }
10769 
10770   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10771   Constructor->markUsed(Context);
10772 
10773   if (ASTMutationListener *L = getASTMutationListener()) {
10774     L->CompletedImplicitDefinition(Constructor);
10775   }
10776 
10777   DiagnoseUninitializedFields(*this, Constructor);
10778 }
10779 
10780 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10781   // C++ [class.dtor]p2:
10782   //   If a class has no user-declared destructor, a destructor is
10783   //   declared implicitly. An implicitly-declared destructor is an
10784   //   inline public member of its class.
10785   assert(ClassDecl->needsImplicitDestructor());
10786 
10787   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10788   if (DSM.isAlreadyBeingDeclared())
10789     return nullptr;
10790 
10791   // Create the actual destructor declaration.
10792   CanQualType ClassType
10793     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10794   SourceLocation ClassLoc = ClassDecl->getLocation();
10795   DeclarationName Name
10796     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10797   DeclarationNameInfo NameInfo(Name, ClassLoc);
10798   CXXDestructorDecl *Destructor
10799       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10800                                   QualType(), nullptr, /*isInline=*/true,
10801                                   /*isImplicitlyDeclared=*/true);
10802   Destructor->setAccess(AS_public);
10803   Destructor->setDefaulted();
10804 
10805   if (getLangOpts().CUDA) {
10806     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10807                                             Destructor,
10808                                             /* ConstRHS */ false,
10809                                             /* Diagnose */ false);
10810   }
10811 
10812   // Build an exception specification pointing back at this destructor.
10813   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10814   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10815 
10816   // We don't need to use SpecialMemberIsTrivial here; triviality for
10817   // destructors is easy to compute.
10818   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10819   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
10820                                 ClassDecl->hasTrivialDestructorForCall());
10821 
10822   // Note that we have declared this destructor.
10823   ++ASTContext::NumImplicitDestructorsDeclared;
10824 
10825   Scope *S = getScopeForContext(ClassDecl);
10826   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10827 
10828   // We can't check whether an implicit destructor is deleted before we complete
10829   // the definition of the class, because its validity depends on the alignment
10830   // of the class. We'll check this from ActOnFields once the class is complete.
10831   if (ClassDecl->isCompleteDefinition() &&
10832       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10833     SetDeclDeleted(Destructor, ClassLoc);
10834 
10835   // Introduce this destructor into its scope.
10836   if (S)
10837     PushOnScopeChains(Destructor, S, false);
10838   ClassDecl->addDecl(Destructor);
10839 
10840   return Destructor;
10841 }
10842 
10843 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10844                                     CXXDestructorDecl *Destructor) {
10845   assert((Destructor->isDefaulted() &&
10846           !Destructor->doesThisDeclarationHaveABody() &&
10847           !Destructor->isDeleted()) &&
10848          "DefineImplicitDestructor - call it for implicit default dtor");
10849   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
10850     return;
10851 
10852   CXXRecordDecl *ClassDecl = Destructor->getParent();
10853   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10854 
10855   SynthesizedFunctionScope Scope(*this, Destructor);
10856 
10857   // The exception specification is needed because we are defining the
10858   // function.
10859   ResolveExceptionSpec(CurrentLocation,
10860                        Destructor->getType()->castAs<FunctionProtoType>());
10861   MarkVTableUsed(CurrentLocation, ClassDecl);
10862 
10863   // Add a context note for diagnostics produced after this point.
10864   Scope.addContextNote(CurrentLocation);
10865 
10866   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10867                                          Destructor->getParent());
10868 
10869   if (CheckDestructor(Destructor)) {
10870     Destructor->setInvalidDecl();
10871     return;
10872   }
10873 
10874   SourceLocation Loc = Destructor->getLocEnd().isValid()
10875                            ? Destructor->getLocEnd()
10876                            : Destructor->getLocation();
10877   Destructor->setBody(new (Context) CompoundStmt(Loc));
10878   Destructor->markUsed(Context);
10879 
10880   if (ASTMutationListener *L = getASTMutationListener()) {
10881     L->CompletedImplicitDefinition(Destructor);
10882   }
10883 }
10884 
10885 /// \brief Perform any semantic analysis which needs to be delayed until all
10886 /// pending class member declarations have been parsed.
10887 void Sema::ActOnFinishCXXMemberDecls() {
10888   // If the context is an invalid C++ class, just suppress these checks.
10889   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10890     if (Record->isInvalidDecl()) {
10891       DelayedDefaultedMemberExceptionSpecs.clear();
10892       DelayedExceptionSpecChecks.clear();
10893       return;
10894     }
10895     checkForMultipleExportedDefaultConstructors(*this, Record);
10896   }
10897 }
10898 
10899 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10900   referenceDLLExportedClassMethods();
10901 }
10902 
10903 void Sema::referenceDLLExportedClassMethods() {
10904   if (!DelayedDllExportClasses.empty()) {
10905     // Calling ReferenceDllExportedMethods might cause the current function to
10906     // be called again, so use a local copy of DelayedDllExportClasses.
10907     SmallVector<CXXRecordDecl *, 4> WorkList;
10908     std::swap(DelayedDllExportClasses, WorkList);
10909     for (CXXRecordDecl *Class : WorkList)
10910       ReferenceDllExportedMethods(*this, Class);
10911   }
10912 }
10913 
10914 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10915                                          CXXDestructorDecl *Destructor) {
10916   assert(getLangOpts().CPlusPlus11 &&
10917          "adjusting dtor exception specs was introduced in c++11");
10918 
10919   // C++11 [class.dtor]p3:
10920   //   A declaration of a destructor that does not have an exception-
10921   //   specification is implicitly considered to have the same exception-
10922   //   specification as an implicit declaration.
10923   const FunctionProtoType *DtorType = Destructor->getType()->
10924                                         getAs<FunctionProtoType>();
10925   if (DtorType->hasExceptionSpec())
10926     return;
10927 
10928   // Replace the destructor's type, building off the existing one. Fortunately,
10929   // the only thing of interest in the destructor type is its extended info.
10930   // The return and arguments are fixed.
10931   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10932   EPI.ExceptionSpec.Type = EST_Unevaluated;
10933   EPI.ExceptionSpec.SourceDecl = Destructor;
10934   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10935 
10936   // FIXME: If the destructor has a body that could throw, and the newly created
10937   // spec doesn't allow exceptions, we should emit a warning, because this
10938   // change in behavior can break conforming C++03 programs at runtime.
10939   // However, we don't have a body or an exception specification yet, so it
10940   // needs to be done somewhere else.
10941 }
10942 
10943 namespace {
10944 /// \brief An abstract base class for all helper classes used in building the
10945 //  copy/move operators. These classes serve as factory functions and help us
10946 //  avoid using the same Expr* in the AST twice.
10947 class ExprBuilder {
10948   ExprBuilder(const ExprBuilder&) = delete;
10949   ExprBuilder &operator=(const ExprBuilder&) = delete;
10950 
10951 protected:
10952   static Expr *assertNotNull(Expr *E) {
10953     assert(E && "Expression construction must not fail.");
10954     return E;
10955   }
10956 
10957 public:
10958   ExprBuilder() {}
10959   virtual ~ExprBuilder() {}
10960 
10961   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10962 };
10963 
10964 class RefBuilder: public ExprBuilder {
10965   VarDecl *Var;
10966   QualType VarType;
10967 
10968 public:
10969   Expr *build(Sema &S, SourceLocation Loc) const override {
10970     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10971   }
10972 
10973   RefBuilder(VarDecl *Var, QualType VarType)
10974       : Var(Var), VarType(VarType) {}
10975 };
10976 
10977 class ThisBuilder: public ExprBuilder {
10978 public:
10979   Expr *build(Sema &S, SourceLocation Loc) const override {
10980     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10981   }
10982 };
10983 
10984 class CastBuilder: public ExprBuilder {
10985   const ExprBuilder &Builder;
10986   QualType Type;
10987   ExprValueKind Kind;
10988   const CXXCastPath &Path;
10989 
10990 public:
10991   Expr *build(Sema &S, SourceLocation Loc) const override {
10992     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10993                                              CK_UncheckedDerivedToBase, Kind,
10994                                              &Path).get());
10995   }
10996 
10997   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10998               const CXXCastPath &Path)
10999       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11000 };
11001 
11002 class DerefBuilder: public ExprBuilder {
11003   const ExprBuilder &Builder;
11004 
11005 public:
11006   Expr *build(Sema &S, SourceLocation Loc) const override {
11007     return assertNotNull(
11008         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11009   }
11010 
11011   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11012 };
11013 
11014 class MemberBuilder: public ExprBuilder {
11015   const ExprBuilder &Builder;
11016   QualType Type;
11017   CXXScopeSpec SS;
11018   bool IsArrow;
11019   LookupResult &MemberLookup;
11020 
11021 public:
11022   Expr *build(Sema &S, SourceLocation Loc) const override {
11023     return assertNotNull(S.BuildMemberReferenceExpr(
11024         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11025         nullptr, MemberLookup, nullptr, nullptr).get());
11026   }
11027 
11028   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11029                 LookupResult &MemberLookup)
11030       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11031         MemberLookup(MemberLookup) {}
11032 };
11033 
11034 class MoveCastBuilder: public ExprBuilder {
11035   const ExprBuilder &Builder;
11036 
11037 public:
11038   Expr *build(Sema &S, SourceLocation Loc) const override {
11039     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11040   }
11041 
11042   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11043 };
11044 
11045 class LvalueConvBuilder: public ExprBuilder {
11046   const ExprBuilder &Builder;
11047 
11048 public:
11049   Expr *build(Sema &S, SourceLocation Loc) const override {
11050     return assertNotNull(
11051         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11052   }
11053 
11054   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11055 };
11056 
11057 class SubscriptBuilder: public ExprBuilder {
11058   const ExprBuilder &Base;
11059   const ExprBuilder &Index;
11060 
11061 public:
11062   Expr *build(Sema &S, SourceLocation Loc) const override {
11063     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11064         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11065   }
11066 
11067   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11068       : Base(Base), Index(Index) {}
11069 };
11070 
11071 } // end anonymous namespace
11072 
11073 /// When generating a defaulted copy or move assignment operator, if a field
11074 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11075 /// do so. This optimization only applies for arrays of scalars, and for arrays
11076 /// of class type where the selected copy/move-assignment operator is trivial.
11077 static StmtResult
11078 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11079                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11080   // Compute the size of the memory buffer to be copied.
11081   QualType SizeType = S.Context.getSizeType();
11082   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11083                    S.Context.getTypeSizeInChars(T).getQuantity());
11084 
11085   // Take the address of the field references for "from" and "to". We
11086   // directly construct UnaryOperators here because semantic analysis
11087   // does not permit us to take the address of an xvalue.
11088   Expr *From = FromB.build(S, Loc);
11089   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11090                          S.Context.getPointerType(From->getType()),
11091                          VK_RValue, OK_Ordinary, Loc, false);
11092   Expr *To = ToB.build(S, Loc);
11093   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11094                        S.Context.getPointerType(To->getType()),
11095                        VK_RValue, OK_Ordinary, Loc, false);
11096 
11097   const Type *E = T->getBaseElementTypeUnsafe();
11098   bool NeedsCollectableMemCpy =
11099     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11100 
11101   // Create a reference to the __builtin_objc_memmove_collectable function
11102   StringRef MemCpyName = NeedsCollectableMemCpy ?
11103     "__builtin_objc_memmove_collectable" :
11104     "__builtin_memcpy";
11105   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11106                  Sema::LookupOrdinaryName);
11107   S.LookupName(R, S.TUScope, true);
11108 
11109   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11110   if (!MemCpy)
11111     // Something went horribly wrong earlier, and we will have complained
11112     // about it.
11113     return StmtError();
11114 
11115   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11116                                             VK_RValue, Loc, nullptr);
11117   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11118 
11119   Expr *CallArgs[] = {
11120     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11121   };
11122   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11123                                     Loc, CallArgs, Loc);
11124 
11125   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11126   return Call.getAs<Stmt>();
11127 }
11128 
11129 /// \brief Builds a statement that copies/moves the given entity from \p From to
11130 /// \c To.
11131 ///
11132 /// This routine is used to copy/move the members of a class with an
11133 /// implicitly-declared copy/move assignment operator. When the entities being
11134 /// copied are arrays, this routine builds for loops to copy them.
11135 ///
11136 /// \param S The Sema object used for type-checking.
11137 ///
11138 /// \param Loc The location where the implicit copy/move is being generated.
11139 ///
11140 /// \param T The type of the expressions being copied/moved. Both expressions
11141 /// must have this type.
11142 ///
11143 /// \param To The expression we are copying/moving to.
11144 ///
11145 /// \param From The expression we are copying/moving from.
11146 ///
11147 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11148 /// Otherwise, it's a non-static member subobject.
11149 ///
11150 /// \param Copying Whether we're copying or moving.
11151 ///
11152 /// \param Depth Internal parameter recording the depth of the recursion.
11153 ///
11154 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11155 /// if a memcpy should be used instead.
11156 static StmtResult
11157 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11158                                  const ExprBuilder &To, const ExprBuilder &From,
11159                                  bool CopyingBaseSubobject, bool Copying,
11160                                  unsigned Depth = 0) {
11161   // C++11 [class.copy]p28:
11162   //   Each subobject is assigned in the manner appropriate to its type:
11163   //
11164   //     - if the subobject is of class type, as if by a call to operator= with
11165   //       the subobject as the object expression and the corresponding
11166   //       subobject of x as a single function argument (as if by explicit
11167   //       qualification; that is, ignoring any possible virtual overriding
11168   //       functions in more derived classes);
11169   //
11170   // C++03 [class.copy]p13:
11171   //     - if the subobject is of class type, the copy assignment operator for
11172   //       the class is used (as if by explicit qualification; that is,
11173   //       ignoring any possible virtual overriding functions in more derived
11174   //       classes);
11175   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11176     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11177 
11178     // Look for operator=.
11179     DeclarationName Name
11180       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11181     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11182     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11183 
11184     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11185     // operator.
11186     if (!S.getLangOpts().CPlusPlus11) {
11187       LookupResult::Filter F = OpLookup.makeFilter();
11188       while (F.hasNext()) {
11189         NamedDecl *D = F.next();
11190         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11191           if (Method->isCopyAssignmentOperator() ||
11192               (!Copying && Method->isMoveAssignmentOperator()))
11193             continue;
11194 
11195         F.erase();
11196       }
11197       F.done();
11198     }
11199 
11200     // Suppress the protected check (C++ [class.protected]) for each of the
11201     // assignment operators we found. This strange dance is required when
11202     // we're assigning via a base classes's copy-assignment operator. To
11203     // ensure that we're getting the right base class subobject (without
11204     // ambiguities), we need to cast "this" to that subobject type; to
11205     // ensure that we don't go through the virtual call mechanism, we need
11206     // to qualify the operator= name with the base class (see below). However,
11207     // this means that if the base class has a protected copy assignment
11208     // operator, the protected member access check will fail. So, we
11209     // rewrite "protected" access to "public" access in this case, since we
11210     // know by construction that we're calling from a derived class.
11211     if (CopyingBaseSubobject) {
11212       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11213            L != LEnd; ++L) {
11214         if (L.getAccess() == AS_protected)
11215           L.setAccess(AS_public);
11216       }
11217     }
11218 
11219     // Create the nested-name-specifier that will be used to qualify the
11220     // reference to operator=; this is required to suppress the virtual
11221     // call mechanism.
11222     CXXScopeSpec SS;
11223     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11224     SS.MakeTrivial(S.Context,
11225                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11226                                                CanonicalT),
11227                    Loc);
11228 
11229     // Create the reference to operator=.
11230     ExprResult OpEqualRef
11231       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11232                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11233                                    /*FirstQualifierInScope=*/nullptr,
11234                                    OpLookup,
11235                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11236                                    /*SuppressQualifierCheck=*/true);
11237     if (OpEqualRef.isInvalid())
11238       return StmtError();
11239 
11240     // Build the call to the assignment operator.
11241 
11242     Expr *FromInst = From.build(S, Loc);
11243     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11244                                                   OpEqualRef.getAs<Expr>(),
11245                                                   Loc, FromInst, Loc);
11246     if (Call.isInvalid())
11247       return StmtError();
11248 
11249     // If we built a call to a trivial 'operator=' while copying an array,
11250     // bail out. We'll replace the whole shebang with a memcpy.
11251     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11252     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11253       return StmtResult((Stmt*)nullptr);
11254 
11255     // Convert to an expression-statement, and clean up any produced
11256     // temporaries.
11257     return S.ActOnExprStmt(Call);
11258   }
11259 
11260   //     - if the subobject is of scalar type, the built-in assignment
11261   //       operator is used.
11262   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11263   if (!ArrayTy) {
11264     ExprResult Assignment = S.CreateBuiltinBinOp(
11265         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11266     if (Assignment.isInvalid())
11267       return StmtError();
11268     return S.ActOnExprStmt(Assignment);
11269   }
11270 
11271   //     - if the subobject is an array, each element is assigned, in the
11272   //       manner appropriate to the element type;
11273 
11274   // Construct a loop over the array bounds, e.g.,
11275   //
11276   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11277   //
11278   // that will copy each of the array elements.
11279   QualType SizeType = S.Context.getSizeType();
11280 
11281   // Create the iteration variable.
11282   IdentifierInfo *IterationVarName = nullptr;
11283   {
11284     SmallString<8> Str;
11285     llvm::raw_svector_ostream OS(Str);
11286     OS << "__i" << Depth;
11287     IterationVarName = &S.Context.Idents.get(OS.str());
11288   }
11289   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11290                                           IterationVarName, SizeType,
11291                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11292                                           SC_None);
11293 
11294   // Initialize the iteration variable to zero.
11295   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11296   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11297 
11298   // Creates a reference to the iteration variable.
11299   RefBuilder IterationVarRef(IterationVar, SizeType);
11300   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11301 
11302   // Create the DeclStmt that holds the iteration variable.
11303   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11304 
11305   // Subscript the "from" and "to" expressions with the iteration variable.
11306   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11307   MoveCastBuilder FromIndexMove(FromIndexCopy);
11308   const ExprBuilder *FromIndex;
11309   if (Copying)
11310     FromIndex = &FromIndexCopy;
11311   else
11312     FromIndex = &FromIndexMove;
11313 
11314   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11315 
11316   // Build the copy/move for an individual element of the array.
11317   StmtResult Copy =
11318     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11319                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11320                                      Copying, Depth + 1);
11321   // Bail out if copying fails or if we determined that we should use memcpy.
11322   if (Copy.isInvalid() || !Copy.get())
11323     return Copy;
11324 
11325   // Create the comparison against the array bound.
11326   llvm::APInt Upper
11327     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11328   Expr *Comparison
11329     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11330                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11331                                      BO_NE, S.Context.BoolTy,
11332                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11333 
11334   // Create the pre-increment of the iteration variable. We can determine
11335   // whether the increment will overflow based on the value of the array
11336   // bound.
11337   Expr *Increment = new (S.Context)
11338       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11339                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11340 
11341   // Construct the loop that copies all elements of this array.
11342   return S.ActOnForStmt(
11343       Loc, Loc, InitStmt,
11344       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11345       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11346 }
11347 
11348 static StmtResult
11349 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11350                       const ExprBuilder &To, const ExprBuilder &From,
11351                       bool CopyingBaseSubobject, bool Copying) {
11352   // Maybe we should use a memcpy?
11353   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11354       T.isTriviallyCopyableType(S.Context))
11355     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11356 
11357   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11358                                                      CopyingBaseSubobject,
11359                                                      Copying, 0));
11360 
11361   // If we ended up picking a trivial assignment operator for an array of a
11362   // non-trivially-copyable class type, just emit a memcpy.
11363   if (!Result.isInvalid() && !Result.get())
11364     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11365 
11366   return Result;
11367 }
11368 
11369 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11370   // Note: The following rules are largely analoguous to the copy
11371   // constructor rules. Note that virtual bases are not taken into account
11372   // for determining the argument type of the operator. Note also that
11373   // operators taking an object instead of a reference are allowed.
11374   assert(ClassDecl->needsImplicitCopyAssignment());
11375 
11376   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11377   if (DSM.isAlreadyBeingDeclared())
11378     return nullptr;
11379 
11380   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11381   QualType RetType = Context.getLValueReferenceType(ArgType);
11382   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11383   if (Const)
11384     ArgType = ArgType.withConst();
11385   ArgType = Context.getLValueReferenceType(ArgType);
11386 
11387   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11388                                                      CXXCopyAssignment,
11389                                                      Const);
11390 
11391   //   An implicitly-declared copy assignment operator is an inline public
11392   //   member of its class.
11393   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11394   SourceLocation ClassLoc = ClassDecl->getLocation();
11395   DeclarationNameInfo NameInfo(Name, ClassLoc);
11396   CXXMethodDecl *CopyAssignment =
11397       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11398                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11399                             /*isInline=*/true, Constexpr, SourceLocation());
11400   CopyAssignment->setAccess(AS_public);
11401   CopyAssignment->setDefaulted();
11402   CopyAssignment->setImplicit();
11403 
11404   if (getLangOpts().CUDA) {
11405     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11406                                             CopyAssignment,
11407                                             /* ConstRHS */ Const,
11408                                             /* Diagnose */ false);
11409   }
11410 
11411   // Build an exception specification pointing back at this member.
11412   FunctionProtoType::ExtProtoInfo EPI =
11413       getImplicitMethodEPI(*this, CopyAssignment);
11414   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11415 
11416   // Add the parameter to the operator.
11417   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11418                                                ClassLoc, ClassLoc,
11419                                                /*Id=*/nullptr, ArgType,
11420                                                /*TInfo=*/nullptr, SC_None,
11421                                                nullptr);
11422   CopyAssignment->setParams(FromParam);
11423 
11424   CopyAssignment->setTrivial(
11425     ClassDecl->needsOverloadResolutionForCopyAssignment()
11426       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11427       : ClassDecl->hasTrivialCopyAssignment());
11428 
11429   // Note that we have added this copy-assignment operator.
11430   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11431 
11432   Scope *S = getScopeForContext(ClassDecl);
11433   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11434 
11435   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11436     SetDeclDeleted(CopyAssignment, ClassLoc);
11437 
11438   if (S)
11439     PushOnScopeChains(CopyAssignment, S, false);
11440   ClassDecl->addDecl(CopyAssignment);
11441 
11442   return CopyAssignment;
11443 }
11444 
11445 /// Diagnose an implicit copy operation for a class which is odr-used, but
11446 /// which is deprecated because the class has a user-declared copy constructor,
11447 /// copy assignment operator, or destructor.
11448 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11449   assert(CopyOp->isImplicit());
11450 
11451   CXXRecordDecl *RD = CopyOp->getParent();
11452   CXXMethodDecl *UserDeclaredOperation = nullptr;
11453 
11454   // In Microsoft mode, assignment operations don't affect constructors and
11455   // vice versa.
11456   if (RD->hasUserDeclaredDestructor()) {
11457     UserDeclaredOperation = RD->getDestructor();
11458   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11459              RD->hasUserDeclaredCopyConstructor() &&
11460              !S.getLangOpts().MSVCCompat) {
11461     // Find any user-declared copy constructor.
11462     for (auto *I : RD->ctors()) {
11463       if (I->isCopyConstructor()) {
11464         UserDeclaredOperation = I;
11465         break;
11466       }
11467     }
11468     assert(UserDeclaredOperation);
11469   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11470              RD->hasUserDeclaredCopyAssignment() &&
11471              !S.getLangOpts().MSVCCompat) {
11472     // Find any user-declared move assignment operator.
11473     for (auto *I : RD->methods()) {
11474       if (I->isCopyAssignmentOperator()) {
11475         UserDeclaredOperation = I;
11476         break;
11477       }
11478     }
11479     assert(UserDeclaredOperation);
11480   }
11481 
11482   if (UserDeclaredOperation) {
11483     S.Diag(UserDeclaredOperation->getLocation(),
11484          diag::warn_deprecated_copy_operation)
11485       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11486       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11487   }
11488 }
11489 
11490 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11491                                         CXXMethodDecl *CopyAssignOperator) {
11492   assert((CopyAssignOperator->isDefaulted() &&
11493           CopyAssignOperator->isOverloadedOperator() &&
11494           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11495           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11496           !CopyAssignOperator->isDeleted()) &&
11497          "DefineImplicitCopyAssignment called for wrong function");
11498   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11499     return;
11500 
11501   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11502   if (ClassDecl->isInvalidDecl()) {
11503     CopyAssignOperator->setInvalidDecl();
11504     return;
11505   }
11506 
11507   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11508 
11509   // The exception specification is needed because we are defining the
11510   // function.
11511   ResolveExceptionSpec(CurrentLocation,
11512                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11513 
11514   // Add a context note for diagnostics produced after this point.
11515   Scope.addContextNote(CurrentLocation);
11516 
11517   // C++11 [class.copy]p18:
11518   //   The [definition of an implicitly declared copy assignment operator] is
11519   //   deprecated if the class has a user-declared copy constructor or a
11520   //   user-declared destructor.
11521   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11522     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11523 
11524   // C++0x [class.copy]p30:
11525   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11526   //   for a non-union class X performs memberwise copy assignment of its
11527   //   subobjects. The direct base classes of X are assigned first, in the
11528   //   order of their declaration in the base-specifier-list, and then the
11529   //   immediate non-static data members of X are assigned, in the order in
11530   //   which they were declared in the class definition.
11531 
11532   // The statements that form the synthesized function body.
11533   SmallVector<Stmt*, 8> Statements;
11534 
11535   // The parameter for the "other" object, which we are copying from.
11536   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11537   Qualifiers OtherQuals = Other->getType().getQualifiers();
11538   QualType OtherRefType = Other->getType();
11539   if (const LValueReferenceType *OtherRef
11540                                 = OtherRefType->getAs<LValueReferenceType>()) {
11541     OtherRefType = OtherRef->getPointeeType();
11542     OtherQuals = OtherRefType.getQualifiers();
11543   }
11544 
11545   // Our location for everything implicitly-generated.
11546   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11547                            ? CopyAssignOperator->getLocEnd()
11548                            : CopyAssignOperator->getLocation();
11549 
11550   // Builds a DeclRefExpr for the "other" object.
11551   RefBuilder OtherRef(Other, OtherRefType);
11552 
11553   // Builds the "this" pointer.
11554   ThisBuilder This;
11555 
11556   // Assign base classes.
11557   bool Invalid = false;
11558   for (auto &Base : ClassDecl->bases()) {
11559     // Form the assignment:
11560     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11561     QualType BaseType = Base.getType().getUnqualifiedType();
11562     if (!BaseType->isRecordType()) {
11563       Invalid = true;
11564       continue;
11565     }
11566 
11567     CXXCastPath BasePath;
11568     BasePath.push_back(&Base);
11569 
11570     // Construct the "from" expression, which is an implicit cast to the
11571     // appropriately-qualified base type.
11572     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11573                      VK_LValue, BasePath);
11574 
11575     // Dereference "this".
11576     DerefBuilder DerefThis(This);
11577     CastBuilder To(DerefThis,
11578                    Context.getCVRQualifiedType(
11579                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11580                    VK_LValue, BasePath);
11581 
11582     // Build the copy.
11583     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11584                                             To, From,
11585                                             /*CopyingBaseSubobject=*/true,
11586                                             /*Copying=*/true);
11587     if (Copy.isInvalid()) {
11588       CopyAssignOperator->setInvalidDecl();
11589       return;
11590     }
11591 
11592     // Success! Record the copy.
11593     Statements.push_back(Copy.getAs<Expr>());
11594   }
11595 
11596   // Assign non-static members.
11597   for (auto *Field : ClassDecl->fields()) {
11598     // FIXME: We should form some kind of AST representation for the implied
11599     // memcpy in a union copy operation.
11600     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11601       continue;
11602 
11603     if (Field->isInvalidDecl()) {
11604       Invalid = true;
11605       continue;
11606     }
11607 
11608     // Check for members of reference type; we can't copy those.
11609     if (Field->getType()->isReferenceType()) {
11610       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11611         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11612       Diag(Field->getLocation(), diag::note_declared_at);
11613       Invalid = true;
11614       continue;
11615     }
11616 
11617     // Check for members of const-qualified, non-class type.
11618     QualType BaseType = Context.getBaseElementType(Field->getType());
11619     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11620       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11621         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11622       Diag(Field->getLocation(), diag::note_declared_at);
11623       Invalid = true;
11624       continue;
11625     }
11626 
11627     // Suppress assigning zero-width bitfields.
11628     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11629       continue;
11630 
11631     QualType FieldType = Field->getType().getNonReferenceType();
11632     if (FieldType->isIncompleteArrayType()) {
11633       assert(ClassDecl->hasFlexibleArrayMember() &&
11634              "Incomplete array type is not valid");
11635       continue;
11636     }
11637 
11638     // Build references to the field in the object we're copying from and to.
11639     CXXScopeSpec SS; // Intentionally empty
11640     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11641                               LookupMemberName);
11642     MemberLookup.addDecl(Field);
11643     MemberLookup.resolveKind();
11644 
11645     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11646 
11647     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11648 
11649     // Build the copy of this field.
11650     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11651                                             To, From,
11652                                             /*CopyingBaseSubobject=*/false,
11653                                             /*Copying=*/true);
11654     if (Copy.isInvalid()) {
11655       CopyAssignOperator->setInvalidDecl();
11656       return;
11657     }
11658 
11659     // Success! Record the copy.
11660     Statements.push_back(Copy.getAs<Stmt>());
11661   }
11662 
11663   if (!Invalid) {
11664     // Add a "return *this;"
11665     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11666 
11667     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11668     if (Return.isInvalid())
11669       Invalid = true;
11670     else
11671       Statements.push_back(Return.getAs<Stmt>());
11672   }
11673 
11674   if (Invalid) {
11675     CopyAssignOperator->setInvalidDecl();
11676     return;
11677   }
11678 
11679   StmtResult Body;
11680   {
11681     CompoundScopeRAII CompoundScope(*this);
11682     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11683                              /*isStmtExpr=*/false);
11684     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11685   }
11686   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11687   CopyAssignOperator->markUsed(Context);
11688 
11689   if (ASTMutationListener *L = getASTMutationListener()) {
11690     L->CompletedImplicitDefinition(CopyAssignOperator);
11691   }
11692 }
11693 
11694 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11695   assert(ClassDecl->needsImplicitMoveAssignment());
11696 
11697   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11698   if (DSM.isAlreadyBeingDeclared())
11699     return nullptr;
11700 
11701   // Note: The following rules are largely analoguous to the move
11702   // constructor rules.
11703 
11704   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11705   QualType RetType = Context.getLValueReferenceType(ArgType);
11706   ArgType = Context.getRValueReferenceType(ArgType);
11707 
11708   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11709                                                      CXXMoveAssignment,
11710                                                      false);
11711 
11712   //   An implicitly-declared move assignment operator is an inline public
11713   //   member of its class.
11714   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11715   SourceLocation ClassLoc = ClassDecl->getLocation();
11716   DeclarationNameInfo NameInfo(Name, ClassLoc);
11717   CXXMethodDecl *MoveAssignment =
11718       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11719                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11720                             /*isInline=*/true, Constexpr, SourceLocation());
11721   MoveAssignment->setAccess(AS_public);
11722   MoveAssignment->setDefaulted();
11723   MoveAssignment->setImplicit();
11724 
11725   if (getLangOpts().CUDA) {
11726     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11727                                             MoveAssignment,
11728                                             /* ConstRHS */ false,
11729                                             /* Diagnose */ false);
11730   }
11731 
11732   // Build an exception specification pointing back at this member.
11733   FunctionProtoType::ExtProtoInfo EPI =
11734       getImplicitMethodEPI(*this, MoveAssignment);
11735   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11736 
11737   // Add the parameter to the operator.
11738   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11739                                                ClassLoc, ClassLoc,
11740                                                /*Id=*/nullptr, ArgType,
11741                                                /*TInfo=*/nullptr, SC_None,
11742                                                nullptr);
11743   MoveAssignment->setParams(FromParam);
11744 
11745   MoveAssignment->setTrivial(
11746     ClassDecl->needsOverloadResolutionForMoveAssignment()
11747       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11748       : ClassDecl->hasTrivialMoveAssignment());
11749 
11750   // Note that we have added this copy-assignment operator.
11751   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11752 
11753   Scope *S = getScopeForContext(ClassDecl);
11754   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11755 
11756   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11757     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11758     SetDeclDeleted(MoveAssignment, ClassLoc);
11759   }
11760 
11761   if (S)
11762     PushOnScopeChains(MoveAssignment, S, false);
11763   ClassDecl->addDecl(MoveAssignment);
11764 
11765   return MoveAssignment;
11766 }
11767 
11768 /// Check if we're implicitly defining a move assignment operator for a class
11769 /// with virtual bases. Such a move assignment might move-assign the virtual
11770 /// base multiple times.
11771 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11772                                                SourceLocation CurrentLocation) {
11773   assert(!Class->isDependentContext() && "should not define dependent move");
11774 
11775   // Only a virtual base could get implicitly move-assigned multiple times.
11776   // Only a non-trivial move assignment can observe this. We only want to
11777   // diagnose if we implicitly define an assignment operator that assigns
11778   // two base classes, both of which move-assign the same virtual base.
11779   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11780       Class->getNumBases() < 2)
11781     return;
11782 
11783   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11784   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11785   VBaseMap VBases;
11786 
11787   for (auto &BI : Class->bases()) {
11788     Worklist.push_back(&BI);
11789     while (!Worklist.empty()) {
11790       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11791       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11792 
11793       // If the base has no non-trivial move assignment operators,
11794       // we don't care about moves from it.
11795       if (!Base->hasNonTrivialMoveAssignment())
11796         continue;
11797 
11798       // If there's nothing virtual here, skip it.
11799       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11800         continue;
11801 
11802       // If we're not actually going to call a move assignment for this base,
11803       // or the selected move assignment is trivial, skip it.
11804       Sema::SpecialMemberOverloadResult SMOR =
11805         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11806                               /*ConstArg*/false, /*VolatileArg*/false,
11807                               /*RValueThis*/true, /*ConstThis*/false,
11808                               /*VolatileThis*/false);
11809       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11810           !SMOR.getMethod()->isMoveAssignmentOperator())
11811         continue;
11812 
11813       if (BaseSpec->isVirtual()) {
11814         // We're going to move-assign this virtual base, and its move
11815         // assignment operator is not trivial. If this can happen for
11816         // multiple distinct direct bases of Class, diagnose it. (If it
11817         // only happens in one base, we'll diagnose it when synthesizing
11818         // that base class's move assignment operator.)
11819         CXXBaseSpecifier *&Existing =
11820             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11821                 .first->second;
11822         if (Existing && Existing != &BI) {
11823           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11824             << Class << Base;
11825           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11826             << (Base->getCanonicalDecl() ==
11827                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11828             << Base << Existing->getType() << Existing->getSourceRange();
11829           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11830             << (Base->getCanonicalDecl() ==
11831                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11832             << Base << BI.getType() << BaseSpec->getSourceRange();
11833 
11834           // Only diagnose each vbase once.
11835           Existing = nullptr;
11836         }
11837       } else {
11838         // Only walk over bases that have defaulted move assignment operators.
11839         // We assume that any user-provided move assignment operator handles
11840         // the multiple-moves-of-vbase case itself somehow.
11841         if (!SMOR.getMethod()->isDefaulted())
11842           continue;
11843 
11844         // We're going to move the base classes of Base. Add them to the list.
11845         for (auto &BI : Base->bases())
11846           Worklist.push_back(&BI);
11847       }
11848     }
11849   }
11850 }
11851 
11852 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11853                                         CXXMethodDecl *MoveAssignOperator) {
11854   assert((MoveAssignOperator->isDefaulted() &&
11855           MoveAssignOperator->isOverloadedOperator() &&
11856           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11857           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11858           !MoveAssignOperator->isDeleted()) &&
11859          "DefineImplicitMoveAssignment called for wrong function");
11860   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
11861     return;
11862 
11863   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11864   if (ClassDecl->isInvalidDecl()) {
11865     MoveAssignOperator->setInvalidDecl();
11866     return;
11867   }
11868 
11869   // C++0x [class.copy]p28:
11870   //   The implicitly-defined or move assignment operator for a non-union class
11871   //   X performs memberwise move assignment of its subobjects. The direct base
11872   //   classes of X are assigned first, in the order of their declaration in the
11873   //   base-specifier-list, and then the immediate non-static data members of X
11874   //   are assigned, in the order in which they were declared in the class
11875   //   definition.
11876 
11877   // Issue a warning if our implicit move assignment operator will move
11878   // from a virtual base more than once.
11879   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11880 
11881   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11882 
11883   // The exception specification is needed because we are defining the
11884   // function.
11885   ResolveExceptionSpec(CurrentLocation,
11886                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11887 
11888   // Add a context note for diagnostics produced after this point.
11889   Scope.addContextNote(CurrentLocation);
11890 
11891   // The statements that form the synthesized function body.
11892   SmallVector<Stmt*, 8> Statements;
11893 
11894   // The parameter for the "other" object, which we are move from.
11895   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11896   QualType OtherRefType = Other->getType()->
11897       getAs<RValueReferenceType>()->getPointeeType();
11898   assert(!OtherRefType.getQualifiers() &&
11899          "Bad argument type of defaulted move assignment");
11900 
11901   // Our location for everything implicitly-generated.
11902   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11903                            ? MoveAssignOperator->getLocEnd()
11904                            : MoveAssignOperator->getLocation();
11905 
11906   // Builds a reference to the "other" object.
11907   RefBuilder OtherRef(Other, OtherRefType);
11908   // Cast to rvalue.
11909   MoveCastBuilder MoveOther(OtherRef);
11910 
11911   // Builds the "this" pointer.
11912   ThisBuilder This;
11913 
11914   // Assign base classes.
11915   bool Invalid = false;
11916   for (auto &Base : ClassDecl->bases()) {
11917     // C++11 [class.copy]p28:
11918     //   It is unspecified whether subobjects representing virtual base classes
11919     //   are assigned more than once by the implicitly-defined copy assignment
11920     //   operator.
11921     // FIXME: Do not assign to a vbase that will be assigned by some other base
11922     // class. For a move-assignment, this can result in the vbase being moved
11923     // multiple times.
11924 
11925     // Form the assignment:
11926     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11927     QualType BaseType = Base.getType().getUnqualifiedType();
11928     if (!BaseType->isRecordType()) {
11929       Invalid = true;
11930       continue;
11931     }
11932 
11933     CXXCastPath BasePath;
11934     BasePath.push_back(&Base);
11935 
11936     // Construct the "from" expression, which is an implicit cast to the
11937     // appropriately-qualified base type.
11938     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11939 
11940     // Dereference "this".
11941     DerefBuilder DerefThis(This);
11942 
11943     // Implicitly cast "this" to the appropriately-qualified base type.
11944     CastBuilder To(DerefThis,
11945                    Context.getCVRQualifiedType(
11946                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11947                    VK_LValue, BasePath);
11948 
11949     // Build the move.
11950     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11951                                             To, From,
11952                                             /*CopyingBaseSubobject=*/true,
11953                                             /*Copying=*/false);
11954     if (Move.isInvalid()) {
11955       MoveAssignOperator->setInvalidDecl();
11956       return;
11957     }
11958 
11959     // Success! Record the move.
11960     Statements.push_back(Move.getAs<Expr>());
11961   }
11962 
11963   // Assign non-static members.
11964   for (auto *Field : ClassDecl->fields()) {
11965     // FIXME: We should form some kind of AST representation for the implied
11966     // memcpy in a union copy operation.
11967     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11968       continue;
11969 
11970     if (Field->isInvalidDecl()) {
11971       Invalid = true;
11972       continue;
11973     }
11974 
11975     // Check for members of reference type; we can't move those.
11976     if (Field->getType()->isReferenceType()) {
11977       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11978         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11979       Diag(Field->getLocation(), diag::note_declared_at);
11980       Invalid = true;
11981       continue;
11982     }
11983 
11984     // Check for members of const-qualified, non-class type.
11985     QualType BaseType = Context.getBaseElementType(Field->getType());
11986     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11987       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11988         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11989       Diag(Field->getLocation(), diag::note_declared_at);
11990       Invalid = true;
11991       continue;
11992     }
11993 
11994     // Suppress assigning zero-width bitfields.
11995     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11996       continue;
11997 
11998     QualType FieldType = Field->getType().getNonReferenceType();
11999     if (FieldType->isIncompleteArrayType()) {
12000       assert(ClassDecl->hasFlexibleArrayMember() &&
12001              "Incomplete array type is not valid");
12002       continue;
12003     }
12004 
12005     // Build references to the field in the object we're copying from and to.
12006     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12007                               LookupMemberName);
12008     MemberLookup.addDecl(Field);
12009     MemberLookup.resolveKind();
12010     MemberBuilder From(MoveOther, OtherRefType,
12011                        /*IsArrow=*/false, MemberLookup);
12012     MemberBuilder To(This, getCurrentThisType(),
12013                      /*IsArrow=*/true, MemberLookup);
12014 
12015     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12016         "Member reference with rvalue base must be rvalue except for reference "
12017         "members, which aren't allowed for move assignment.");
12018 
12019     // Build the move of this field.
12020     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12021                                             To, From,
12022                                             /*CopyingBaseSubobject=*/false,
12023                                             /*Copying=*/false);
12024     if (Move.isInvalid()) {
12025       MoveAssignOperator->setInvalidDecl();
12026       return;
12027     }
12028 
12029     // Success! Record the copy.
12030     Statements.push_back(Move.getAs<Stmt>());
12031   }
12032 
12033   if (!Invalid) {
12034     // Add a "return *this;"
12035     ExprResult ThisObj =
12036         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12037 
12038     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12039     if (Return.isInvalid())
12040       Invalid = true;
12041     else
12042       Statements.push_back(Return.getAs<Stmt>());
12043   }
12044 
12045   if (Invalid) {
12046     MoveAssignOperator->setInvalidDecl();
12047     return;
12048   }
12049 
12050   StmtResult Body;
12051   {
12052     CompoundScopeRAII CompoundScope(*this);
12053     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12054                              /*isStmtExpr=*/false);
12055     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12056   }
12057   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12058   MoveAssignOperator->markUsed(Context);
12059 
12060   if (ASTMutationListener *L = getASTMutationListener()) {
12061     L->CompletedImplicitDefinition(MoveAssignOperator);
12062   }
12063 }
12064 
12065 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12066                                                     CXXRecordDecl *ClassDecl) {
12067   // C++ [class.copy]p4:
12068   //   If the class definition does not explicitly declare a copy
12069   //   constructor, one is declared implicitly.
12070   assert(ClassDecl->needsImplicitCopyConstructor());
12071 
12072   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12073   if (DSM.isAlreadyBeingDeclared())
12074     return nullptr;
12075 
12076   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12077   QualType ArgType = ClassType;
12078   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12079   if (Const)
12080     ArgType = ArgType.withConst();
12081   ArgType = Context.getLValueReferenceType(ArgType);
12082 
12083   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12084                                                      CXXCopyConstructor,
12085                                                      Const);
12086 
12087   DeclarationName Name
12088     = Context.DeclarationNames.getCXXConstructorName(
12089                                            Context.getCanonicalType(ClassType));
12090   SourceLocation ClassLoc = ClassDecl->getLocation();
12091   DeclarationNameInfo NameInfo(Name, ClassLoc);
12092 
12093   //   An implicitly-declared copy constructor is an inline public
12094   //   member of its class.
12095   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12096       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12097       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12098       Constexpr);
12099   CopyConstructor->setAccess(AS_public);
12100   CopyConstructor->setDefaulted();
12101 
12102   if (getLangOpts().CUDA) {
12103     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12104                                             CopyConstructor,
12105                                             /* ConstRHS */ Const,
12106                                             /* Diagnose */ false);
12107   }
12108 
12109   // Build an exception specification pointing back at this member.
12110   FunctionProtoType::ExtProtoInfo EPI =
12111       getImplicitMethodEPI(*this, CopyConstructor);
12112   CopyConstructor->setType(
12113       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12114 
12115   // Add the parameter to the constructor.
12116   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12117                                                ClassLoc, ClassLoc,
12118                                                /*IdentifierInfo=*/nullptr,
12119                                                ArgType, /*TInfo=*/nullptr,
12120                                                SC_None, nullptr);
12121   CopyConstructor->setParams(FromParam);
12122 
12123   CopyConstructor->setTrivial(
12124       ClassDecl->needsOverloadResolutionForCopyConstructor()
12125           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12126           : ClassDecl->hasTrivialCopyConstructor());
12127 
12128   CopyConstructor->setTrivialForCall(
12129       ClassDecl->hasAttr<TrivialABIAttr>() ||
12130       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12131            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12132              TAH_ConsiderTrivialABI)
12133            : ClassDecl->hasTrivialCopyConstructorForCall()));
12134 
12135   // Note that we have declared this constructor.
12136   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12137 
12138   Scope *S = getScopeForContext(ClassDecl);
12139   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12140 
12141   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12142     ClassDecl->setImplicitCopyConstructorIsDeleted();
12143     SetDeclDeleted(CopyConstructor, ClassLoc);
12144   }
12145 
12146   if (S)
12147     PushOnScopeChains(CopyConstructor, S, false);
12148   ClassDecl->addDecl(CopyConstructor);
12149 
12150   return CopyConstructor;
12151 }
12152 
12153 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12154                                          CXXConstructorDecl *CopyConstructor) {
12155   assert((CopyConstructor->isDefaulted() &&
12156           CopyConstructor->isCopyConstructor() &&
12157           !CopyConstructor->doesThisDeclarationHaveABody() &&
12158           !CopyConstructor->isDeleted()) &&
12159          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12160   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12161     return;
12162 
12163   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12164   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12165 
12166   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12167 
12168   // The exception specification is needed because we are defining the
12169   // function.
12170   ResolveExceptionSpec(CurrentLocation,
12171                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12172   MarkVTableUsed(CurrentLocation, ClassDecl);
12173 
12174   // Add a context note for diagnostics produced after this point.
12175   Scope.addContextNote(CurrentLocation);
12176 
12177   // C++11 [class.copy]p7:
12178   //   The [definition of an implicitly declared copy constructor] is
12179   //   deprecated if the class has a user-declared copy assignment operator
12180   //   or a user-declared destructor.
12181   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12182     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12183 
12184   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12185     CopyConstructor->setInvalidDecl();
12186   }  else {
12187     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12188                              ? CopyConstructor->getLocEnd()
12189                              : CopyConstructor->getLocation();
12190     Sema::CompoundScopeRAII CompoundScope(*this);
12191     CopyConstructor->setBody(
12192         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12193     CopyConstructor->markUsed(Context);
12194   }
12195 
12196   if (ASTMutationListener *L = getASTMutationListener()) {
12197     L->CompletedImplicitDefinition(CopyConstructor);
12198   }
12199 }
12200 
12201 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12202                                                     CXXRecordDecl *ClassDecl) {
12203   assert(ClassDecl->needsImplicitMoveConstructor());
12204 
12205   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12206   if (DSM.isAlreadyBeingDeclared())
12207     return nullptr;
12208 
12209   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12210   QualType ArgType = Context.getRValueReferenceType(ClassType);
12211 
12212   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12213                                                      CXXMoveConstructor,
12214                                                      false);
12215 
12216   DeclarationName Name
12217     = Context.DeclarationNames.getCXXConstructorName(
12218                                            Context.getCanonicalType(ClassType));
12219   SourceLocation ClassLoc = ClassDecl->getLocation();
12220   DeclarationNameInfo NameInfo(Name, ClassLoc);
12221 
12222   // C++11 [class.copy]p11:
12223   //   An implicitly-declared copy/move constructor is an inline public
12224   //   member of its class.
12225   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12226       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12227       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12228       Constexpr);
12229   MoveConstructor->setAccess(AS_public);
12230   MoveConstructor->setDefaulted();
12231 
12232   if (getLangOpts().CUDA) {
12233     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12234                                             MoveConstructor,
12235                                             /* ConstRHS */ false,
12236                                             /* Diagnose */ false);
12237   }
12238 
12239   // Build an exception specification pointing back at this member.
12240   FunctionProtoType::ExtProtoInfo EPI =
12241       getImplicitMethodEPI(*this, MoveConstructor);
12242   MoveConstructor->setType(
12243       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12244 
12245   // Add the parameter to the constructor.
12246   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12247                                                ClassLoc, ClassLoc,
12248                                                /*IdentifierInfo=*/nullptr,
12249                                                ArgType, /*TInfo=*/nullptr,
12250                                                SC_None, nullptr);
12251   MoveConstructor->setParams(FromParam);
12252 
12253   MoveConstructor->setTrivial(
12254       ClassDecl->needsOverloadResolutionForMoveConstructor()
12255           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12256           : ClassDecl->hasTrivialMoveConstructor());
12257 
12258   MoveConstructor->setTrivialForCall(
12259       ClassDecl->hasAttr<TrivialABIAttr>() ||
12260       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12261            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12262                                     TAH_ConsiderTrivialABI)
12263            : ClassDecl->hasTrivialMoveConstructorForCall()));
12264 
12265   // Note that we have declared this constructor.
12266   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12267 
12268   Scope *S = getScopeForContext(ClassDecl);
12269   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12270 
12271   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12272     ClassDecl->setImplicitMoveConstructorIsDeleted();
12273     SetDeclDeleted(MoveConstructor, ClassLoc);
12274   }
12275 
12276   if (S)
12277     PushOnScopeChains(MoveConstructor, S, false);
12278   ClassDecl->addDecl(MoveConstructor);
12279 
12280   return MoveConstructor;
12281 }
12282 
12283 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12284                                          CXXConstructorDecl *MoveConstructor) {
12285   assert((MoveConstructor->isDefaulted() &&
12286           MoveConstructor->isMoveConstructor() &&
12287           !MoveConstructor->doesThisDeclarationHaveABody() &&
12288           !MoveConstructor->isDeleted()) &&
12289          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12290   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12291     return;
12292 
12293   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12294   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12295 
12296   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12297 
12298   // The exception specification is needed because we are defining the
12299   // function.
12300   ResolveExceptionSpec(CurrentLocation,
12301                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12302   MarkVTableUsed(CurrentLocation, ClassDecl);
12303 
12304   // Add a context note for diagnostics produced after this point.
12305   Scope.addContextNote(CurrentLocation);
12306 
12307   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12308     MoveConstructor->setInvalidDecl();
12309   } else {
12310     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12311                              ? MoveConstructor->getLocEnd()
12312                              : MoveConstructor->getLocation();
12313     Sema::CompoundScopeRAII CompoundScope(*this);
12314     MoveConstructor->setBody(ActOnCompoundStmt(
12315         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12316     MoveConstructor->markUsed(Context);
12317   }
12318 
12319   if (ASTMutationListener *L = getASTMutationListener()) {
12320     L->CompletedImplicitDefinition(MoveConstructor);
12321   }
12322 }
12323 
12324 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12325   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12326 }
12327 
12328 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12329                             SourceLocation CurrentLocation,
12330                             CXXConversionDecl *Conv) {
12331   SynthesizedFunctionScope Scope(*this, Conv);
12332   assert(!Conv->getReturnType()->isUndeducedType());
12333 
12334   CXXRecordDecl *Lambda = Conv->getParent();
12335   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12336   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12337 
12338   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12339     CallOp = InstantiateFunctionDeclaration(
12340         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12341     if (!CallOp)
12342       return;
12343 
12344     Invoker = InstantiateFunctionDeclaration(
12345         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12346     if (!Invoker)
12347       return;
12348   }
12349 
12350   if (CallOp->isInvalidDecl())
12351     return;
12352 
12353   // Mark the call operator referenced (and add to pending instantiations
12354   // if necessary).
12355   // For both the conversion and static-invoker template specializations
12356   // we construct their body's in this function, so no need to add them
12357   // to the PendingInstantiations.
12358   MarkFunctionReferenced(CurrentLocation, CallOp);
12359 
12360   // Fill in the __invoke function with a dummy implementation. IR generation
12361   // will fill in the actual details. Update its type in case it contained
12362   // an 'auto'.
12363   Invoker->markUsed(Context);
12364   Invoker->setReferenced();
12365   Invoker->setType(Conv->getReturnType()->getPointeeType());
12366   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12367 
12368   // Construct the body of the conversion function { return __invoke; }.
12369   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12370                                        VK_LValue, Conv->getLocation()).get();
12371   assert(FunctionRef && "Can't refer to __invoke function?");
12372   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12373   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12374                                      Conv->getLocation()));
12375   Conv->markUsed(Context);
12376   Conv->setReferenced();
12377 
12378   if (ASTMutationListener *L = getASTMutationListener()) {
12379     L->CompletedImplicitDefinition(Conv);
12380     L->CompletedImplicitDefinition(Invoker);
12381   }
12382 }
12383 
12384 
12385 
12386 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12387        SourceLocation CurrentLocation,
12388        CXXConversionDecl *Conv)
12389 {
12390   assert(!Conv->getParent()->isGenericLambda());
12391 
12392   SynthesizedFunctionScope Scope(*this, Conv);
12393 
12394   // Copy-initialize the lambda object as needed to capture it.
12395   Expr *This = ActOnCXXThis(CurrentLocation).get();
12396   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12397 
12398   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12399                                                         Conv->getLocation(),
12400                                                         Conv, DerefThis);
12401 
12402   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12403   // behavior.  Note that only the general conversion function does this
12404   // (since it's unusable otherwise); in the case where we inline the
12405   // block literal, it has block literal lifetime semantics.
12406   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12407     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12408                                           CK_CopyAndAutoreleaseBlockObject,
12409                                           BuildBlock.get(), nullptr, VK_RValue);
12410 
12411   if (BuildBlock.isInvalid()) {
12412     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12413     Conv->setInvalidDecl();
12414     return;
12415   }
12416 
12417   // Create the return statement that returns the block from the conversion
12418   // function.
12419   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12420   if (Return.isInvalid()) {
12421     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12422     Conv->setInvalidDecl();
12423     return;
12424   }
12425 
12426   // Set the body of the conversion function.
12427   Stmt *ReturnS = Return.get();
12428   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12429                                      Conv->getLocation()));
12430   Conv->markUsed(Context);
12431 
12432   // We're done; notify the mutation listener, if any.
12433   if (ASTMutationListener *L = getASTMutationListener()) {
12434     L->CompletedImplicitDefinition(Conv);
12435   }
12436 }
12437 
12438 /// \brief Determine whether the given list arguments contains exactly one
12439 /// "real" (non-default) argument.
12440 static bool hasOneRealArgument(MultiExprArg Args) {
12441   switch (Args.size()) {
12442   case 0:
12443     return false;
12444 
12445   default:
12446     if (!Args[1]->isDefaultArgument())
12447       return false;
12448 
12449     LLVM_FALLTHROUGH;
12450   case 1:
12451     return !Args[0]->isDefaultArgument();
12452   }
12453 
12454   return false;
12455 }
12456 
12457 ExprResult
12458 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12459                             NamedDecl *FoundDecl,
12460                             CXXConstructorDecl *Constructor,
12461                             MultiExprArg ExprArgs,
12462                             bool HadMultipleCandidates,
12463                             bool IsListInitialization,
12464                             bool IsStdInitListInitialization,
12465                             bool RequiresZeroInit,
12466                             unsigned ConstructKind,
12467                             SourceRange ParenRange) {
12468   bool Elidable = false;
12469 
12470   // C++0x [class.copy]p34:
12471   //   When certain criteria are met, an implementation is allowed to
12472   //   omit the copy/move construction of a class object, even if the
12473   //   copy/move constructor and/or destructor for the object have
12474   //   side effects. [...]
12475   //     - when a temporary class object that has not been bound to a
12476   //       reference (12.2) would be copied/moved to a class object
12477   //       with the same cv-unqualified type, the copy/move operation
12478   //       can be omitted by constructing the temporary object
12479   //       directly into the target of the omitted copy/move
12480   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12481       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12482     Expr *SubExpr = ExprArgs[0];
12483     Elidable = SubExpr->isTemporaryObject(
12484         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12485   }
12486 
12487   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12488                                FoundDecl, Constructor,
12489                                Elidable, ExprArgs, HadMultipleCandidates,
12490                                IsListInitialization,
12491                                IsStdInitListInitialization, RequiresZeroInit,
12492                                ConstructKind, ParenRange);
12493 }
12494 
12495 ExprResult
12496 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12497                             NamedDecl *FoundDecl,
12498                             CXXConstructorDecl *Constructor,
12499                             bool Elidable,
12500                             MultiExprArg ExprArgs,
12501                             bool HadMultipleCandidates,
12502                             bool IsListInitialization,
12503                             bool IsStdInitListInitialization,
12504                             bool RequiresZeroInit,
12505                             unsigned ConstructKind,
12506                             SourceRange ParenRange) {
12507   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12508     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12509     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12510       return ExprError();
12511   }
12512 
12513   return BuildCXXConstructExpr(
12514       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12515       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12516       RequiresZeroInit, ConstructKind, ParenRange);
12517 }
12518 
12519 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12520 /// including handling of its default argument expressions.
12521 ExprResult
12522 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12523                             CXXConstructorDecl *Constructor,
12524                             bool Elidable,
12525                             MultiExprArg ExprArgs,
12526                             bool HadMultipleCandidates,
12527                             bool IsListInitialization,
12528                             bool IsStdInitListInitialization,
12529                             bool RequiresZeroInit,
12530                             unsigned ConstructKind,
12531                             SourceRange ParenRange) {
12532   assert(declaresSameEntity(
12533              Constructor->getParent(),
12534              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12535          "given constructor for wrong type");
12536   MarkFunctionReferenced(ConstructLoc, Constructor);
12537   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12538     return ExprError();
12539 
12540   return CXXConstructExpr::Create(
12541       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12542       ExprArgs, HadMultipleCandidates, IsListInitialization,
12543       IsStdInitListInitialization, RequiresZeroInit,
12544       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12545       ParenRange);
12546 }
12547 
12548 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12549   assert(Field->hasInClassInitializer());
12550 
12551   // If we already have the in-class initializer nothing needs to be done.
12552   if (Field->getInClassInitializer())
12553     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12554 
12555   // If we might have already tried and failed to instantiate, don't try again.
12556   if (Field->isInvalidDecl())
12557     return ExprError();
12558 
12559   // Maybe we haven't instantiated the in-class initializer. Go check the
12560   // pattern FieldDecl to see if it has one.
12561   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12562 
12563   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12564     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12565     DeclContext::lookup_result Lookup =
12566         ClassPattern->lookup(Field->getDeclName());
12567 
12568     // Lookup can return at most two results: the pattern for the field, or the
12569     // injected class name of the parent record. No other member can have the
12570     // same name as the field.
12571     // In modules mode, lookup can return multiple results (coming from
12572     // different modules).
12573     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12574            "more than two lookup results for field name");
12575     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12576     if (!Pattern) {
12577       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12578              "cannot have other non-field member with same name");
12579       for (auto L : Lookup)
12580         if (isa<FieldDecl>(L)) {
12581           Pattern = cast<FieldDecl>(L);
12582           break;
12583         }
12584       assert(Pattern && "We must have set the Pattern!");
12585     }
12586 
12587     if (!Pattern->hasInClassInitializer() ||
12588         InstantiateInClassInitializer(Loc, Field, Pattern,
12589                                       getTemplateInstantiationArgs(Field))) {
12590       // Don't diagnose this again.
12591       Field->setInvalidDecl();
12592       return ExprError();
12593     }
12594     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12595   }
12596 
12597   // DR1351:
12598   //   If the brace-or-equal-initializer of a non-static data member
12599   //   invokes a defaulted default constructor of its class or of an
12600   //   enclosing class in a potentially evaluated subexpression, the
12601   //   program is ill-formed.
12602   //
12603   // This resolution is unworkable: the exception specification of the
12604   // default constructor can be needed in an unevaluated context, in
12605   // particular, in the operand of a noexcept-expression, and we can be
12606   // unable to compute an exception specification for an enclosed class.
12607   //
12608   // Any attempt to resolve the exception specification of a defaulted default
12609   // constructor before the initializer is lexically complete will ultimately
12610   // come here at which point we can diagnose it.
12611   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12612   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12613       << OutermostClass << Field;
12614   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12615   // Recover by marking the field invalid, unless we're in a SFINAE context.
12616   if (!isSFINAEContext())
12617     Field->setInvalidDecl();
12618   return ExprError();
12619 }
12620 
12621 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12622   if (VD->isInvalidDecl()) return;
12623 
12624   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12625   if (ClassDecl->isInvalidDecl()) return;
12626   if (ClassDecl->hasIrrelevantDestructor()) return;
12627   if (ClassDecl->isDependentContext()) return;
12628 
12629   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12630   MarkFunctionReferenced(VD->getLocation(), Destructor);
12631   CheckDestructorAccess(VD->getLocation(), Destructor,
12632                         PDiag(diag::err_access_dtor_var)
12633                         << VD->getDeclName()
12634                         << VD->getType());
12635   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12636 
12637   if (Destructor->isTrivial()) return;
12638   if (!VD->hasGlobalStorage()) return;
12639 
12640   // Emit warning for non-trivial dtor in global scope (a real global,
12641   // class-static, function-static).
12642   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12643 
12644   // TODO: this should be re-enabled for static locals by !CXAAtExit
12645   if (!VD->isStaticLocal())
12646     Diag(VD->getLocation(), diag::warn_global_destructor);
12647 }
12648 
12649 /// \brief Given a constructor and the set of arguments provided for the
12650 /// constructor, convert the arguments and add any required default arguments
12651 /// to form a proper call to this constructor.
12652 ///
12653 /// \returns true if an error occurred, false otherwise.
12654 bool
12655 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12656                               MultiExprArg ArgsPtr,
12657                               SourceLocation Loc,
12658                               SmallVectorImpl<Expr*> &ConvertedArgs,
12659                               bool AllowExplicit,
12660                               bool IsListInitialization) {
12661   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12662   unsigned NumArgs = ArgsPtr.size();
12663   Expr **Args = ArgsPtr.data();
12664 
12665   const FunctionProtoType *Proto
12666     = Constructor->getType()->getAs<FunctionProtoType>();
12667   assert(Proto && "Constructor without a prototype?");
12668   unsigned NumParams = Proto->getNumParams();
12669 
12670   // If too few arguments are available, we'll fill in the rest with defaults.
12671   if (NumArgs < NumParams)
12672     ConvertedArgs.reserve(NumParams);
12673   else
12674     ConvertedArgs.reserve(NumArgs);
12675 
12676   VariadicCallType CallType =
12677     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12678   SmallVector<Expr *, 8> AllArgs;
12679   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12680                                         Proto, 0,
12681                                         llvm::makeArrayRef(Args, NumArgs),
12682                                         AllArgs,
12683                                         CallType, AllowExplicit,
12684                                         IsListInitialization);
12685   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12686 
12687   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12688 
12689   CheckConstructorCall(Constructor,
12690                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12691                        Proto, Loc);
12692 
12693   return Invalid;
12694 }
12695 
12696 static inline bool
12697 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12698                                        const FunctionDecl *FnDecl) {
12699   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12700   if (isa<NamespaceDecl>(DC)) {
12701     return SemaRef.Diag(FnDecl->getLocation(),
12702                         diag::err_operator_new_delete_declared_in_namespace)
12703       << FnDecl->getDeclName();
12704   }
12705 
12706   if (isa<TranslationUnitDecl>(DC) &&
12707       FnDecl->getStorageClass() == SC_Static) {
12708     return SemaRef.Diag(FnDecl->getLocation(),
12709                         diag::err_operator_new_delete_declared_static)
12710       << FnDecl->getDeclName();
12711   }
12712 
12713   return false;
12714 }
12715 
12716 static inline bool
12717 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12718                             CanQualType ExpectedResultType,
12719                             CanQualType ExpectedFirstParamType,
12720                             unsigned DependentParamTypeDiag,
12721                             unsigned InvalidParamTypeDiag) {
12722   QualType ResultType =
12723       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12724 
12725   // Check that the result type is not dependent.
12726   if (ResultType->isDependentType())
12727     return SemaRef.Diag(FnDecl->getLocation(),
12728                         diag::err_operator_new_delete_dependent_result_type)
12729     << FnDecl->getDeclName() << ExpectedResultType;
12730 
12731   // Check that the result type is what we expect.
12732   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12733     return SemaRef.Diag(FnDecl->getLocation(),
12734                         diag::err_operator_new_delete_invalid_result_type)
12735     << FnDecl->getDeclName() << ExpectedResultType;
12736 
12737   // A function template must have at least 2 parameters.
12738   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12739     return SemaRef.Diag(FnDecl->getLocation(),
12740                       diag::err_operator_new_delete_template_too_few_parameters)
12741         << FnDecl->getDeclName();
12742 
12743   // The function decl must have at least 1 parameter.
12744   if (FnDecl->getNumParams() == 0)
12745     return SemaRef.Diag(FnDecl->getLocation(),
12746                         diag::err_operator_new_delete_too_few_parameters)
12747       << FnDecl->getDeclName();
12748 
12749   // Check the first parameter type is not dependent.
12750   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12751   if (FirstParamType->isDependentType())
12752     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12753       << FnDecl->getDeclName() << ExpectedFirstParamType;
12754 
12755   // Check that the first parameter type is what we expect.
12756   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12757       ExpectedFirstParamType)
12758     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12759     << FnDecl->getDeclName() << ExpectedFirstParamType;
12760 
12761   return false;
12762 }
12763 
12764 static bool
12765 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12766   // C++ [basic.stc.dynamic.allocation]p1:
12767   //   A program is ill-formed if an allocation function is declared in a
12768   //   namespace scope other than global scope or declared static in global
12769   //   scope.
12770   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12771     return true;
12772 
12773   CanQualType SizeTy =
12774     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12775 
12776   // C++ [basic.stc.dynamic.allocation]p1:
12777   //  The return type shall be void*. The first parameter shall have type
12778   //  std::size_t.
12779   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12780                                   SizeTy,
12781                                   diag::err_operator_new_dependent_param_type,
12782                                   diag::err_operator_new_param_type))
12783     return true;
12784 
12785   // C++ [basic.stc.dynamic.allocation]p1:
12786   //  The first parameter shall not have an associated default argument.
12787   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12788     return SemaRef.Diag(FnDecl->getLocation(),
12789                         diag::err_operator_new_default_arg)
12790       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12791 
12792   return false;
12793 }
12794 
12795 static bool
12796 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12797   // C++ [basic.stc.dynamic.deallocation]p1:
12798   //   A program is ill-formed if deallocation functions are declared in a
12799   //   namespace scope other than global scope or declared static in global
12800   //   scope.
12801   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12802     return true;
12803 
12804   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
12805 
12806   // C++ P0722:
12807   //   Within a class C, the first parameter of a destroying operator delete
12808   //   shall be of type C *. The first parameter of any other deallocation
12809   //   function shall be of type void *.
12810   CanQualType ExpectedFirstParamType =
12811       MD && MD->isDestroyingOperatorDelete()
12812           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
12813                 SemaRef.Context.getRecordType(MD->getParent())))
12814           : SemaRef.Context.VoidPtrTy;
12815 
12816   // C++ [basic.stc.dynamic.deallocation]p2:
12817   //   Each deallocation function shall return void
12818   if (CheckOperatorNewDeleteTypes(
12819           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
12820           diag::err_operator_delete_dependent_param_type,
12821           diag::err_operator_delete_param_type))
12822     return true;
12823 
12824   // C++ P0722:
12825   //   A destroying operator delete shall be a usual deallocation function.
12826   if (MD && !MD->getParent()->isDependentContext() &&
12827       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
12828     SemaRef.Diag(MD->getLocation(),
12829                  diag::err_destroying_operator_delete_not_usual);
12830     return true;
12831   }
12832 
12833   return false;
12834 }
12835 
12836 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12837 /// of this overloaded operator is well-formed. If so, returns false;
12838 /// otherwise, emits appropriate diagnostics and returns true.
12839 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12840   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12841          "Expected an overloaded operator declaration");
12842 
12843   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12844 
12845   // C++ [over.oper]p5:
12846   //   The allocation and deallocation functions, operator new,
12847   //   operator new[], operator delete and operator delete[], are
12848   //   described completely in 3.7.3. The attributes and restrictions
12849   //   found in the rest of this subclause do not apply to them unless
12850   //   explicitly stated in 3.7.3.
12851   if (Op == OO_Delete || Op == OO_Array_Delete)
12852     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12853 
12854   if (Op == OO_New || Op == OO_Array_New)
12855     return CheckOperatorNewDeclaration(*this, FnDecl);
12856 
12857   // C++ [over.oper]p6:
12858   //   An operator function shall either be a non-static member
12859   //   function or be a non-member function and have at least one
12860   //   parameter whose type is a class, a reference to a class, an
12861   //   enumeration, or a reference to an enumeration.
12862   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12863     if (MethodDecl->isStatic())
12864       return Diag(FnDecl->getLocation(),
12865                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12866   } else {
12867     bool ClassOrEnumParam = false;
12868     for (auto Param : FnDecl->parameters()) {
12869       QualType ParamType = Param->getType().getNonReferenceType();
12870       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12871           ParamType->isEnumeralType()) {
12872         ClassOrEnumParam = true;
12873         break;
12874       }
12875     }
12876 
12877     if (!ClassOrEnumParam)
12878       return Diag(FnDecl->getLocation(),
12879                   diag::err_operator_overload_needs_class_or_enum)
12880         << FnDecl->getDeclName();
12881   }
12882 
12883   // C++ [over.oper]p8:
12884   //   An operator function cannot have default arguments (8.3.6),
12885   //   except where explicitly stated below.
12886   //
12887   // Only the function-call operator allows default arguments
12888   // (C++ [over.call]p1).
12889   if (Op != OO_Call) {
12890     for (auto Param : FnDecl->parameters()) {
12891       if (Param->hasDefaultArg())
12892         return Diag(Param->getLocation(),
12893                     diag::err_operator_overload_default_arg)
12894           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12895     }
12896   }
12897 
12898   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12899     { false, false, false }
12900 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12901     , { Unary, Binary, MemberOnly }
12902 #include "clang/Basic/OperatorKinds.def"
12903   };
12904 
12905   bool CanBeUnaryOperator = OperatorUses[Op][0];
12906   bool CanBeBinaryOperator = OperatorUses[Op][1];
12907   bool MustBeMemberOperator = OperatorUses[Op][2];
12908 
12909   // C++ [over.oper]p8:
12910   //   [...] Operator functions cannot have more or fewer parameters
12911   //   than the number required for the corresponding operator, as
12912   //   described in the rest of this subclause.
12913   unsigned NumParams = FnDecl->getNumParams()
12914                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12915   if (Op != OO_Call &&
12916       ((NumParams == 1 && !CanBeUnaryOperator) ||
12917        (NumParams == 2 && !CanBeBinaryOperator) ||
12918        (NumParams < 1) || (NumParams > 2))) {
12919     // We have the wrong number of parameters.
12920     unsigned ErrorKind;
12921     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12922       ErrorKind = 2;  // 2 -> unary or binary.
12923     } else if (CanBeUnaryOperator) {
12924       ErrorKind = 0;  // 0 -> unary
12925     } else {
12926       assert(CanBeBinaryOperator &&
12927              "All non-call overloaded operators are unary or binary!");
12928       ErrorKind = 1;  // 1 -> binary
12929     }
12930 
12931     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12932       << FnDecl->getDeclName() << NumParams << ErrorKind;
12933   }
12934 
12935   // Overloaded operators other than operator() cannot be variadic.
12936   if (Op != OO_Call &&
12937       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12938     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12939       << FnDecl->getDeclName();
12940   }
12941 
12942   // Some operators must be non-static member functions.
12943   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12944     return Diag(FnDecl->getLocation(),
12945                 diag::err_operator_overload_must_be_member)
12946       << FnDecl->getDeclName();
12947   }
12948 
12949   // C++ [over.inc]p1:
12950   //   The user-defined function called operator++ implements the
12951   //   prefix and postfix ++ operator. If this function is a member
12952   //   function with no parameters, or a non-member function with one
12953   //   parameter of class or enumeration type, it defines the prefix
12954   //   increment operator ++ for objects of that type. If the function
12955   //   is a member function with one parameter (which shall be of type
12956   //   int) or a non-member function with two parameters (the second
12957   //   of which shall be of type int), it defines the postfix
12958   //   increment operator ++ for objects of that type.
12959   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12960     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12961     QualType ParamType = LastParam->getType();
12962 
12963     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12964         !ParamType->isDependentType())
12965       return Diag(LastParam->getLocation(),
12966                   diag::err_operator_overload_post_incdec_must_be_int)
12967         << LastParam->getType() << (Op == OO_MinusMinus);
12968   }
12969 
12970   return false;
12971 }
12972 
12973 static bool
12974 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12975                                           FunctionTemplateDecl *TpDecl) {
12976   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12977 
12978   // Must have one or two template parameters.
12979   if (TemplateParams->size() == 1) {
12980     NonTypeTemplateParmDecl *PmDecl =
12981         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12982 
12983     // The template parameter must be a char parameter pack.
12984     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12985         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12986       return false;
12987 
12988   } else if (TemplateParams->size() == 2) {
12989     TemplateTypeParmDecl *PmType =
12990         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12991     NonTypeTemplateParmDecl *PmArgs =
12992         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12993 
12994     // The second template parameter must be a parameter pack with the
12995     // first template parameter as its type.
12996     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12997         PmArgs->isTemplateParameterPack()) {
12998       const TemplateTypeParmType *TArgs =
12999           PmArgs->getType()->getAs<TemplateTypeParmType>();
13000       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13001           TArgs->getIndex() == PmType->getIndex()) {
13002         if (!SemaRef.inTemplateInstantiation())
13003           SemaRef.Diag(TpDecl->getLocation(),
13004                        diag::ext_string_literal_operator_template);
13005         return false;
13006       }
13007     }
13008   }
13009 
13010   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13011                diag::err_literal_operator_template)
13012       << TpDecl->getTemplateParameters()->getSourceRange();
13013   return true;
13014 }
13015 
13016 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13017 /// of this literal operator function is well-formed. If so, returns
13018 /// false; otherwise, emits appropriate diagnostics and returns true.
13019 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13020   if (isa<CXXMethodDecl>(FnDecl)) {
13021     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13022       << FnDecl->getDeclName();
13023     return true;
13024   }
13025 
13026   if (FnDecl->isExternC()) {
13027     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13028     if (const LinkageSpecDecl *LSD =
13029             FnDecl->getDeclContext()->getExternCContext())
13030       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13031     return true;
13032   }
13033 
13034   // This might be the definition of a literal operator template.
13035   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13036 
13037   // This might be a specialization of a literal operator template.
13038   if (!TpDecl)
13039     TpDecl = FnDecl->getPrimaryTemplate();
13040 
13041   // template <char...> type operator "" name() and
13042   // template <class T, T...> type operator "" name() are the only valid
13043   // template signatures, and the only valid signatures with no parameters.
13044   if (TpDecl) {
13045     if (FnDecl->param_size() != 0) {
13046       Diag(FnDecl->getLocation(),
13047            diag::err_literal_operator_template_with_params);
13048       return true;
13049     }
13050 
13051     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13052       return true;
13053 
13054   } else if (FnDecl->param_size() == 1) {
13055     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13056 
13057     QualType ParamType = Param->getType().getUnqualifiedType();
13058 
13059     // Only unsigned long long int, long double, any character type, and const
13060     // char * are allowed as the only parameters.
13061     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13062         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13063         Context.hasSameType(ParamType, Context.CharTy) ||
13064         Context.hasSameType(ParamType, Context.WideCharTy) ||
13065         Context.hasSameType(ParamType, Context.Char16Ty) ||
13066         Context.hasSameType(ParamType, Context.Char32Ty)) {
13067     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13068       QualType InnerType = Ptr->getPointeeType();
13069 
13070       // Pointer parameter must be a const char *.
13071       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13072                                 Context.CharTy) &&
13073             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13074         Diag(Param->getSourceRange().getBegin(),
13075              diag::err_literal_operator_param)
13076             << ParamType << "'const char *'" << Param->getSourceRange();
13077         return true;
13078       }
13079 
13080     } else if (ParamType->isRealFloatingType()) {
13081       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13082           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13083       return true;
13084 
13085     } else if (ParamType->isIntegerType()) {
13086       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13087           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13088       return true;
13089 
13090     } else {
13091       Diag(Param->getSourceRange().getBegin(),
13092            diag::err_literal_operator_invalid_param)
13093           << ParamType << Param->getSourceRange();
13094       return true;
13095     }
13096 
13097   } else if (FnDecl->param_size() == 2) {
13098     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13099 
13100     // First, verify that the first parameter is correct.
13101 
13102     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13103 
13104     // Two parameter function must have a pointer to const as a
13105     // first parameter; let's strip those qualifiers.
13106     const PointerType *PT = FirstParamType->getAs<PointerType>();
13107 
13108     if (!PT) {
13109       Diag((*Param)->getSourceRange().getBegin(),
13110            diag::err_literal_operator_param)
13111           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13112       return true;
13113     }
13114 
13115     QualType PointeeType = PT->getPointeeType();
13116     // First parameter must be const
13117     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13118       Diag((*Param)->getSourceRange().getBegin(),
13119            diag::err_literal_operator_param)
13120           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13121       return true;
13122     }
13123 
13124     QualType InnerType = PointeeType.getUnqualifiedType();
13125     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
13126     // are allowed as the first parameter to a two-parameter function
13127     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13128           Context.hasSameType(InnerType, Context.WideCharTy) ||
13129           Context.hasSameType(InnerType, Context.Char16Ty) ||
13130           Context.hasSameType(InnerType, Context.Char32Ty))) {
13131       Diag((*Param)->getSourceRange().getBegin(),
13132            diag::err_literal_operator_param)
13133           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13134       return true;
13135     }
13136 
13137     // Move on to the second and final parameter.
13138     ++Param;
13139 
13140     // The second parameter must be a std::size_t.
13141     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13142     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13143       Diag((*Param)->getSourceRange().getBegin(),
13144            diag::err_literal_operator_param)
13145           << SecondParamType << Context.getSizeType()
13146           << (*Param)->getSourceRange();
13147       return true;
13148     }
13149   } else {
13150     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13151     return true;
13152   }
13153 
13154   // Parameters are good.
13155 
13156   // A parameter-declaration-clause containing a default argument is not
13157   // equivalent to any of the permitted forms.
13158   for (auto Param : FnDecl->parameters()) {
13159     if (Param->hasDefaultArg()) {
13160       Diag(Param->getDefaultArgRange().getBegin(),
13161            diag::err_literal_operator_default_argument)
13162         << Param->getDefaultArgRange();
13163       break;
13164     }
13165   }
13166 
13167   StringRef LiteralName
13168     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13169   if (LiteralName[0] != '_' &&
13170       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13171     // C++11 [usrlit.suffix]p1:
13172     //   Literal suffix identifiers that do not start with an underscore
13173     //   are reserved for future standardization.
13174     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13175       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13176   }
13177 
13178   return false;
13179 }
13180 
13181 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13182 /// linkage specification, including the language and (if present)
13183 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13184 /// language string literal. LBraceLoc, if valid, provides the location of
13185 /// the '{' brace. Otherwise, this linkage specification does not
13186 /// have any braces.
13187 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13188                                            Expr *LangStr,
13189                                            SourceLocation LBraceLoc) {
13190   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13191   if (!Lit->isAscii()) {
13192     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13193       << LangStr->getSourceRange();
13194     return nullptr;
13195   }
13196 
13197   StringRef Lang = Lit->getString();
13198   LinkageSpecDecl::LanguageIDs Language;
13199   if (Lang == "C")
13200     Language = LinkageSpecDecl::lang_c;
13201   else if (Lang == "C++")
13202     Language = LinkageSpecDecl::lang_cxx;
13203   else {
13204     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13205       << LangStr->getSourceRange();
13206     return nullptr;
13207   }
13208 
13209   // FIXME: Add all the various semantics of linkage specifications
13210 
13211   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13212                                                LangStr->getExprLoc(), Language,
13213                                                LBraceLoc.isValid());
13214   CurContext->addDecl(D);
13215   PushDeclContext(S, D);
13216   return D;
13217 }
13218 
13219 /// ActOnFinishLinkageSpecification - Complete the definition of
13220 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13221 /// valid, it's the position of the closing '}' brace in a linkage
13222 /// specification that uses braces.
13223 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13224                                             Decl *LinkageSpec,
13225                                             SourceLocation RBraceLoc) {
13226   if (RBraceLoc.isValid()) {
13227     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13228     LSDecl->setRBraceLoc(RBraceLoc);
13229   }
13230   PopDeclContext();
13231   return LinkageSpec;
13232 }
13233 
13234 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13235                                   AttributeList *AttrList,
13236                                   SourceLocation SemiLoc) {
13237   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13238   // Attribute declarations appertain to empty declaration so we handle
13239   // them here.
13240   if (AttrList)
13241     ProcessDeclAttributeList(S, ED, AttrList);
13242 
13243   CurContext->addDecl(ED);
13244   return ED;
13245 }
13246 
13247 /// \brief Perform semantic analysis for the variable declaration that
13248 /// occurs within a C++ catch clause, returning the newly-created
13249 /// variable.
13250 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13251                                          TypeSourceInfo *TInfo,
13252                                          SourceLocation StartLoc,
13253                                          SourceLocation Loc,
13254                                          IdentifierInfo *Name) {
13255   bool Invalid = false;
13256   QualType ExDeclType = TInfo->getType();
13257 
13258   // Arrays and functions decay.
13259   if (ExDeclType->isArrayType())
13260     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13261   else if (ExDeclType->isFunctionType())
13262     ExDeclType = Context.getPointerType(ExDeclType);
13263 
13264   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13265   // The exception-declaration shall not denote a pointer or reference to an
13266   // incomplete type, other than [cv] void*.
13267   // N2844 forbids rvalue references.
13268   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13269     Diag(Loc, diag::err_catch_rvalue_ref);
13270     Invalid = true;
13271   }
13272 
13273   if (ExDeclType->isVariablyModifiedType()) {
13274     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13275     Invalid = true;
13276   }
13277 
13278   QualType BaseType = ExDeclType;
13279   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13280   unsigned DK = diag::err_catch_incomplete;
13281   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13282     BaseType = Ptr->getPointeeType();
13283     Mode = 1;
13284     DK = diag::err_catch_incomplete_ptr;
13285   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13286     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13287     BaseType = Ref->getPointeeType();
13288     Mode = 2;
13289     DK = diag::err_catch_incomplete_ref;
13290   }
13291   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13292       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13293     Invalid = true;
13294 
13295   if (!Invalid && !ExDeclType->isDependentType() &&
13296       RequireNonAbstractType(Loc, ExDeclType,
13297                              diag::err_abstract_type_in_decl,
13298                              AbstractVariableType))
13299     Invalid = true;
13300 
13301   // Only the non-fragile NeXT runtime currently supports C++ catches
13302   // of ObjC types, and no runtime supports catching ObjC types by value.
13303   if (!Invalid && getLangOpts().ObjC1) {
13304     QualType T = ExDeclType;
13305     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13306       T = RT->getPointeeType();
13307 
13308     if (T->isObjCObjectType()) {
13309       Diag(Loc, diag::err_objc_object_catch);
13310       Invalid = true;
13311     } else if (T->isObjCObjectPointerType()) {
13312       // FIXME: should this be a test for macosx-fragile specifically?
13313       if (getLangOpts().ObjCRuntime.isFragile())
13314         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13315     }
13316   }
13317 
13318   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13319                                     ExDeclType, TInfo, SC_None);
13320   ExDecl->setExceptionVariable(true);
13321 
13322   // In ARC, infer 'retaining' for variables of retainable type.
13323   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13324     Invalid = true;
13325 
13326   if (!Invalid && !ExDeclType->isDependentType()) {
13327     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13328       // Insulate this from anything else we might currently be parsing.
13329       EnterExpressionEvaluationContext scope(
13330           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13331 
13332       // C++ [except.handle]p16:
13333       //   The object declared in an exception-declaration or, if the
13334       //   exception-declaration does not specify a name, a temporary (12.2) is
13335       //   copy-initialized (8.5) from the exception object. [...]
13336       //   The object is destroyed when the handler exits, after the destruction
13337       //   of any automatic objects initialized within the handler.
13338       //
13339       // We just pretend to initialize the object with itself, then make sure
13340       // it can be destroyed later.
13341       QualType initType = Context.getExceptionObjectType(ExDeclType);
13342 
13343       InitializedEntity entity =
13344         InitializedEntity::InitializeVariable(ExDecl);
13345       InitializationKind initKind =
13346         InitializationKind::CreateCopy(Loc, SourceLocation());
13347 
13348       Expr *opaqueValue =
13349         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13350       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13351       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13352       if (result.isInvalid())
13353         Invalid = true;
13354       else {
13355         // If the constructor used was non-trivial, set this as the
13356         // "initializer".
13357         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13358         if (!construct->getConstructor()->isTrivial()) {
13359           Expr *init = MaybeCreateExprWithCleanups(construct);
13360           ExDecl->setInit(init);
13361         }
13362 
13363         // And make sure it's destructable.
13364         FinalizeVarWithDestructor(ExDecl, recordType);
13365       }
13366     }
13367   }
13368 
13369   if (Invalid)
13370     ExDecl->setInvalidDecl();
13371 
13372   return ExDecl;
13373 }
13374 
13375 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13376 /// handler.
13377 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13378   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13379   bool Invalid = D.isInvalidType();
13380 
13381   // Check for unexpanded parameter packs.
13382   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13383                                       UPPC_ExceptionType)) {
13384     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13385                                              D.getIdentifierLoc());
13386     Invalid = true;
13387   }
13388 
13389   IdentifierInfo *II = D.getIdentifier();
13390   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13391                                              LookupOrdinaryName,
13392                                              ForVisibleRedeclaration)) {
13393     // The scope should be freshly made just for us. There is just no way
13394     // it contains any previous declaration, except for function parameters in
13395     // a function-try-block's catch statement.
13396     assert(!S->isDeclScope(PrevDecl));
13397     if (isDeclInScope(PrevDecl, CurContext, S)) {
13398       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13399         << D.getIdentifier();
13400       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13401       Invalid = true;
13402     } else if (PrevDecl->isTemplateParameter())
13403       // Maybe we will complain about the shadowed template parameter.
13404       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13405   }
13406 
13407   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13408     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13409       << D.getCXXScopeSpec().getRange();
13410     Invalid = true;
13411   }
13412 
13413   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13414                                               D.getLocStart(),
13415                                               D.getIdentifierLoc(),
13416                                               D.getIdentifier());
13417   if (Invalid)
13418     ExDecl->setInvalidDecl();
13419 
13420   // Add the exception declaration into this scope.
13421   if (II)
13422     PushOnScopeChains(ExDecl, S);
13423   else
13424     CurContext->addDecl(ExDecl);
13425 
13426   ProcessDeclAttributes(S, ExDecl, D);
13427   return ExDecl;
13428 }
13429 
13430 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13431                                          Expr *AssertExpr,
13432                                          Expr *AssertMessageExpr,
13433                                          SourceLocation RParenLoc) {
13434   StringLiteral *AssertMessage =
13435       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13436 
13437   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13438     return nullptr;
13439 
13440   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13441                                       AssertMessage, RParenLoc, false);
13442 }
13443 
13444 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13445                                          Expr *AssertExpr,
13446                                          StringLiteral *AssertMessage,
13447                                          SourceLocation RParenLoc,
13448                                          bool Failed) {
13449   assert(AssertExpr != nullptr && "Expected non-null condition");
13450   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13451       !Failed) {
13452     // In a static_assert-declaration, the constant-expression shall be a
13453     // constant expression that can be contextually converted to bool.
13454     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13455     if (Converted.isInvalid())
13456       Failed = true;
13457 
13458     llvm::APSInt Cond;
13459     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13460           diag::err_static_assert_expression_is_not_constant,
13461           /*AllowFold=*/false).isInvalid())
13462       Failed = true;
13463 
13464     if (!Failed && !Cond) {
13465       SmallString<256> MsgBuffer;
13466       llvm::raw_svector_ostream Msg(MsgBuffer);
13467       if (AssertMessage)
13468         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13469 
13470       Expr *InnerCond = nullptr;
13471       std::string InnerCondDescription;
13472       std::tie(InnerCond, InnerCondDescription) =
13473         findFailedBooleanCondition(Converted.get(),
13474                                    /*AllowTopLevelCond=*/false);
13475       if (InnerCond) {
13476         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13477           << InnerCondDescription << !AssertMessage
13478           << Msg.str() << InnerCond->getSourceRange();
13479       } else {
13480         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13481           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13482       }
13483       Failed = true;
13484     }
13485   }
13486 
13487   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13488                                                   /*DiscardedValue*/false,
13489                                                   /*IsConstexpr*/true);
13490   if (FullAssertExpr.isInvalid())
13491     Failed = true;
13492   else
13493     AssertExpr = FullAssertExpr.get();
13494 
13495   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13496                                         AssertExpr, AssertMessage, RParenLoc,
13497                                         Failed);
13498 
13499   CurContext->addDecl(Decl);
13500   return Decl;
13501 }
13502 
13503 /// \brief Perform semantic analysis of the given friend type declaration.
13504 ///
13505 /// \returns A friend declaration that.
13506 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13507                                       SourceLocation FriendLoc,
13508                                       TypeSourceInfo *TSInfo) {
13509   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13510 
13511   QualType T = TSInfo->getType();
13512   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13513 
13514   // C++03 [class.friend]p2:
13515   //   An elaborated-type-specifier shall be used in a friend declaration
13516   //   for a class.*
13517   //
13518   //   * The class-key of the elaborated-type-specifier is required.
13519   if (!CodeSynthesisContexts.empty()) {
13520     // Do not complain about the form of friend template types during any kind
13521     // of code synthesis. For template instantiation, we will have complained
13522     // when the template was defined.
13523   } else {
13524     if (!T->isElaboratedTypeSpecifier()) {
13525       // If we evaluated the type to a record type, suggest putting
13526       // a tag in front.
13527       if (const RecordType *RT = T->getAs<RecordType>()) {
13528         RecordDecl *RD = RT->getDecl();
13529 
13530         SmallString<16> InsertionText(" ");
13531         InsertionText += RD->getKindName();
13532 
13533         Diag(TypeRange.getBegin(),
13534              getLangOpts().CPlusPlus11 ?
13535                diag::warn_cxx98_compat_unelaborated_friend_type :
13536                diag::ext_unelaborated_friend_type)
13537           << (unsigned) RD->getTagKind()
13538           << T
13539           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13540                                         InsertionText);
13541       } else {
13542         Diag(FriendLoc,
13543              getLangOpts().CPlusPlus11 ?
13544                diag::warn_cxx98_compat_nonclass_type_friend :
13545                diag::ext_nonclass_type_friend)
13546           << T
13547           << TypeRange;
13548       }
13549     } else if (T->getAs<EnumType>()) {
13550       Diag(FriendLoc,
13551            getLangOpts().CPlusPlus11 ?
13552              diag::warn_cxx98_compat_enum_friend :
13553              diag::ext_enum_friend)
13554         << T
13555         << TypeRange;
13556     }
13557 
13558     // C++11 [class.friend]p3:
13559     //   A friend declaration that does not declare a function shall have one
13560     //   of the following forms:
13561     //     friend elaborated-type-specifier ;
13562     //     friend simple-type-specifier ;
13563     //     friend typename-specifier ;
13564     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13565       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13566   }
13567 
13568   //   If the type specifier in a friend declaration designates a (possibly
13569   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13570   //   the friend declaration is ignored.
13571   return FriendDecl::Create(Context, CurContext,
13572                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13573                             FriendLoc);
13574 }
13575 
13576 /// Handle a friend tag declaration where the scope specifier was
13577 /// templated.
13578 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13579                                     unsigned TagSpec, SourceLocation TagLoc,
13580                                     CXXScopeSpec &SS,
13581                                     IdentifierInfo *Name,
13582                                     SourceLocation NameLoc,
13583                                     AttributeList *Attr,
13584                                     MultiTemplateParamsArg TempParamLists) {
13585   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13586 
13587   bool IsMemberSpecialization = false;
13588   bool Invalid = false;
13589 
13590   if (TemplateParameterList *TemplateParams =
13591           MatchTemplateParametersToScopeSpecifier(
13592               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13593               IsMemberSpecialization, Invalid)) {
13594     if (TemplateParams->size() > 0) {
13595       // This is a declaration of a class template.
13596       if (Invalid)
13597         return nullptr;
13598 
13599       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13600                                 NameLoc, Attr, TemplateParams, AS_public,
13601                                 /*ModulePrivateLoc=*/SourceLocation(),
13602                                 FriendLoc, TempParamLists.size() - 1,
13603                                 TempParamLists.data()).get();
13604     } else {
13605       // The "template<>" header is extraneous.
13606       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13607         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13608       IsMemberSpecialization = true;
13609     }
13610   }
13611 
13612   if (Invalid) return nullptr;
13613 
13614   bool isAllExplicitSpecializations = true;
13615   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13616     if (TempParamLists[I]->size()) {
13617       isAllExplicitSpecializations = false;
13618       break;
13619     }
13620   }
13621 
13622   // FIXME: don't ignore attributes.
13623 
13624   // If it's explicit specializations all the way down, just forget
13625   // about the template header and build an appropriate non-templated
13626   // friend.  TODO: for source fidelity, remember the headers.
13627   if (isAllExplicitSpecializations) {
13628     if (SS.isEmpty()) {
13629       bool Owned = false;
13630       bool IsDependent = false;
13631       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13632                       Attr, AS_public,
13633                       /*ModulePrivateLoc=*/SourceLocation(),
13634                       MultiTemplateParamsArg(), Owned, IsDependent,
13635                       /*ScopedEnumKWLoc=*/SourceLocation(),
13636                       /*ScopedEnumUsesClassTag=*/false,
13637                       /*UnderlyingType=*/TypeResult(),
13638                       /*IsTypeSpecifier=*/false,
13639                       /*IsTemplateParamOrArg=*/false);
13640     }
13641 
13642     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13643     ElaboratedTypeKeyword Keyword
13644       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13645     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13646                                    *Name, NameLoc);
13647     if (T.isNull())
13648       return nullptr;
13649 
13650     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13651     if (isa<DependentNameType>(T)) {
13652       DependentNameTypeLoc TL =
13653           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13654       TL.setElaboratedKeywordLoc(TagLoc);
13655       TL.setQualifierLoc(QualifierLoc);
13656       TL.setNameLoc(NameLoc);
13657     } else {
13658       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13659       TL.setElaboratedKeywordLoc(TagLoc);
13660       TL.setQualifierLoc(QualifierLoc);
13661       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13662     }
13663 
13664     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13665                                             TSI, FriendLoc, TempParamLists);
13666     Friend->setAccess(AS_public);
13667     CurContext->addDecl(Friend);
13668     return Friend;
13669   }
13670 
13671   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13672 
13673 
13674 
13675   // Handle the case of a templated-scope friend class.  e.g.
13676   //   template <class T> class A<T>::B;
13677   // FIXME: we don't support these right now.
13678   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13679     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13680   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13681   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13682   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13683   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13684   TL.setElaboratedKeywordLoc(TagLoc);
13685   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13686   TL.setNameLoc(NameLoc);
13687 
13688   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13689                                           TSI, FriendLoc, TempParamLists);
13690   Friend->setAccess(AS_public);
13691   Friend->setUnsupportedFriend(true);
13692   CurContext->addDecl(Friend);
13693   return Friend;
13694 }
13695 
13696 
13697 /// Handle a friend type declaration.  This works in tandem with
13698 /// ActOnTag.
13699 ///
13700 /// Notes on friend class templates:
13701 ///
13702 /// We generally treat friend class declarations as if they were
13703 /// declaring a class.  So, for example, the elaborated type specifier
13704 /// in a friend declaration is required to obey the restrictions of a
13705 /// class-head (i.e. no typedefs in the scope chain), template
13706 /// parameters are required to match up with simple template-ids, &c.
13707 /// However, unlike when declaring a template specialization, it's
13708 /// okay to refer to a template specialization without an empty
13709 /// template parameter declaration, e.g.
13710 ///   friend class A<T>::B<unsigned>;
13711 /// We permit this as a special case; if there are any template
13712 /// parameters present at all, require proper matching, i.e.
13713 ///   template <> template \<class T> friend class A<int>::B;
13714 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13715                                 MultiTemplateParamsArg TempParams) {
13716   SourceLocation Loc = DS.getLocStart();
13717 
13718   assert(DS.isFriendSpecified());
13719   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13720 
13721   // Try to convert the decl specifier to a type.  This works for
13722   // friend templates because ActOnTag never produces a ClassTemplateDecl
13723   // for a TUK_Friend.
13724   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
13725   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13726   QualType T = TSI->getType();
13727   if (TheDeclarator.isInvalidType())
13728     return nullptr;
13729 
13730   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13731     return nullptr;
13732 
13733   // This is definitely an error in C++98.  It's probably meant to
13734   // be forbidden in C++0x, too, but the specification is just
13735   // poorly written.
13736   //
13737   // The problem is with declarations like the following:
13738   //   template <T> friend A<T>::foo;
13739   // where deciding whether a class C is a friend or not now hinges
13740   // on whether there exists an instantiation of A that causes
13741   // 'foo' to equal C.  There are restrictions on class-heads
13742   // (which we declare (by fiat) elaborated friend declarations to
13743   // be) that makes this tractable.
13744   //
13745   // FIXME: handle "template <> friend class A<T>;", which
13746   // is possibly well-formed?  Who even knows?
13747   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13748     Diag(Loc, diag::err_tagless_friend_type_template)
13749       << DS.getSourceRange();
13750     return nullptr;
13751   }
13752 
13753   // C++98 [class.friend]p1: A friend of a class is a function
13754   //   or class that is not a member of the class . . .
13755   // This is fixed in DR77, which just barely didn't make the C++03
13756   // deadline.  It's also a very silly restriction that seriously
13757   // affects inner classes and which nobody else seems to implement;
13758   // thus we never diagnose it, not even in -pedantic.
13759   //
13760   // But note that we could warn about it: it's always useless to
13761   // friend one of your own members (it's not, however, worthless to
13762   // friend a member of an arbitrary specialization of your template).
13763 
13764   Decl *D;
13765   if (!TempParams.empty())
13766     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13767                                    TempParams,
13768                                    TSI,
13769                                    DS.getFriendSpecLoc());
13770   else
13771     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13772 
13773   if (!D)
13774     return nullptr;
13775 
13776   D->setAccess(AS_public);
13777   CurContext->addDecl(D);
13778 
13779   return D;
13780 }
13781 
13782 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13783                                         MultiTemplateParamsArg TemplateParams) {
13784   const DeclSpec &DS = D.getDeclSpec();
13785 
13786   assert(DS.isFriendSpecified());
13787   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13788 
13789   SourceLocation Loc = D.getIdentifierLoc();
13790   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13791 
13792   // C++ [class.friend]p1
13793   //   A friend of a class is a function or class....
13794   // Note that this sees through typedefs, which is intended.
13795   // It *doesn't* see through dependent types, which is correct
13796   // according to [temp.arg.type]p3:
13797   //   If a declaration acquires a function type through a
13798   //   type dependent on a template-parameter and this causes
13799   //   a declaration that does not use the syntactic form of a
13800   //   function declarator to have a function type, the program
13801   //   is ill-formed.
13802   if (!TInfo->getType()->isFunctionType()) {
13803     Diag(Loc, diag::err_unexpected_friend);
13804 
13805     // It might be worthwhile to try to recover by creating an
13806     // appropriate declaration.
13807     return nullptr;
13808   }
13809 
13810   // C++ [namespace.memdef]p3
13811   //  - If a friend declaration in a non-local class first declares a
13812   //    class or function, the friend class or function is a member
13813   //    of the innermost enclosing namespace.
13814   //  - The name of the friend is not found by simple name lookup
13815   //    until a matching declaration is provided in that namespace
13816   //    scope (either before or after the class declaration granting
13817   //    friendship).
13818   //  - If a friend function is called, its name may be found by the
13819   //    name lookup that considers functions from namespaces and
13820   //    classes associated with the types of the function arguments.
13821   //  - When looking for a prior declaration of a class or a function
13822   //    declared as a friend, scopes outside the innermost enclosing
13823   //    namespace scope are not considered.
13824 
13825   CXXScopeSpec &SS = D.getCXXScopeSpec();
13826   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13827   DeclarationName Name = NameInfo.getName();
13828   assert(Name);
13829 
13830   // Check for unexpanded parameter packs.
13831   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13832       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13833       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13834     return nullptr;
13835 
13836   // The context we found the declaration in, or in which we should
13837   // create the declaration.
13838   DeclContext *DC;
13839   Scope *DCScope = S;
13840   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13841                         ForExternalRedeclaration);
13842 
13843   // There are five cases here.
13844   //   - There's no scope specifier and we're in a local class. Only look
13845   //     for functions declared in the immediately-enclosing block scope.
13846   // We recover from invalid scope qualifiers as if they just weren't there.
13847   FunctionDecl *FunctionContainingLocalClass = nullptr;
13848   if ((SS.isInvalid() || !SS.isSet()) &&
13849       (FunctionContainingLocalClass =
13850            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13851     // C++11 [class.friend]p11:
13852     //   If a friend declaration appears in a local class and the name
13853     //   specified is an unqualified name, a prior declaration is
13854     //   looked up without considering scopes that are outside the
13855     //   innermost enclosing non-class scope. For a friend function
13856     //   declaration, if there is no prior declaration, the program is
13857     //   ill-formed.
13858 
13859     // Find the innermost enclosing non-class scope. This is the block
13860     // scope containing the local class definition (or for a nested class,
13861     // the outer local class).
13862     DCScope = S->getFnParent();
13863 
13864     // Look up the function name in the scope.
13865     Previous.clear(LookupLocalFriendName);
13866     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13867 
13868     if (!Previous.empty()) {
13869       // All possible previous declarations must have the same context:
13870       // either they were declared at block scope or they are members of
13871       // one of the enclosing local classes.
13872       DC = Previous.getRepresentativeDecl()->getDeclContext();
13873     } else {
13874       // This is ill-formed, but provide the context that we would have
13875       // declared the function in, if we were permitted to, for error recovery.
13876       DC = FunctionContainingLocalClass;
13877     }
13878     adjustContextForLocalExternDecl(DC);
13879 
13880     // C++ [class.friend]p6:
13881     //   A function can be defined in a friend declaration of a class if and
13882     //   only if the class is a non-local class (9.8), the function name is
13883     //   unqualified, and the function has namespace scope.
13884     if (D.isFunctionDefinition()) {
13885       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13886     }
13887 
13888   //   - There's no scope specifier, in which case we just go to the
13889   //     appropriate scope and look for a function or function template
13890   //     there as appropriate.
13891   } else if (SS.isInvalid() || !SS.isSet()) {
13892     // C++11 [namespace.memdef]p3:
13893     //   If the name in a friend declaration is neither qualified nor
13894     //   a template-id and the declaration is a function or an
13895     //   elaborated-type-specifier, the lookup to determine whether
13896     //   the entity has been previously declared shall not consider
13897     //   any scopes outside the innermost enclosing namespace.
13898     bool isTemplateId =
13899         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
13900 
13901     // Find the appropriate context according to the above.
13902     DC = CurContext;
13903 
13904     // Skip class contexts.  If someone can cite chapter and verse
13905     // for this behavior, that would be nice --- it's what GCC and
13906     // EDG do, and it seems like a reasonable intent, but the spec
13907     // really only says that checks for unqualified existing
13908     // declarations should stop at the nearest enclosing namespace,
13909     // not that they should only consider the nearest enclosing
13910     // namespace.
13911     while (DC->isRecord())
13912       DC = DC->getParent();
13913 
13914     DeclContext *LookupDC = DC;
13915     while (LookupDC->isTransparentContext())
13916       LookupDC = LookupDC->getParent();
13917 
13918     while (true) {
13919       LookupQualifiedName(Previous, LookupDC);
13920 
13921       if (!Previous.empty()) {
13922         DC = LookupDC;
13923         break;
13924       }
13925 
13926       if (isTemplateId) {
13927         if (isa<TranslationUnitDecl>(LookupDC)) break;
13928       } else {
13929         if (LookupDC->isFileContext()) break;
13930       }
13931       LookupDC = LookupDC->getParent();
13932     }
13933 
13934     DCScope = getScopeForDeclContext(S, DC);
13935 
13936   //   - There's a non-dependent scope specifier, in which case we
13937   //     compute it and do a previous lookup there for a function
13938   //     or function template.
13939   } else if (!SS.getScopeRep()->isDependent()) {
13940     DC = computeDeclContext(SS);
13941     if (!DC) return nullptr;
13942 
13943     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13944 
13945     LookupQualifiedName(Previous, DC);
13946 
13947     // Ignore things found implicitly in the wrong scope.
13948     // TODO: better diagnostics for this case.  Suggesting the right
13949     // qualified scope would be nice...
13950     LookupResult::Filter F = Previous.makeFilter();
13951     while (F.hasNext()) {
13952       NamedDecl *D = F.next();
13953       if (!DC->InEnclosingNamespaceSetOf(
13954               D->getDeclContext()->getRedeclContext()))
13955         F.erase();
13956     }
13957     F.done();
13958 
13959     if (Previous.empty()) {
13960       D.setInvalidType();
13961       Diag(Loc, diag::err_qualified_friend_not_found)
13962           << Name << TInfo->getType();
13963       return nullptr;
13964     }
13965 
13966     // C++ [class.friend]p1: A friend of a class is a function or
13967     //   class that is not a member of the class . . .
13968     if (DC->Equals(CurContext))
13969       Diag(DS.getFriendSpecLoc(),
13970            getLangOpts().CPlusPlus11 ?
13971              diag::warn_cxx98_compat_friend_is_member :
13972              diag::err_friend_is_member);
13973 
13974     if (D.isFunctionDefinition()) {
13975       // C++ [class.friend]p6:
13976       //   A function can be defined in a friend declaration of a class if and
13977       //   only if the class is a non-local class (9.8), the function name is
13978       //   unqualified, and the function has namespace scope.
13979       SemaDiagnosticBuilder DB
13980         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13981 
13982       DB << SS.getScopeRep();
13983       if (DC->isFileContext())
13984         DB << FixItHint::CreateRemoval(SS.getRange());
13985       SS.clear();
13986     }
13987 
13988   //   - There's a scope specifier that does not match any template
13989   //     parameter lists, in which case we use some arbitrary context,
13990   //     create a method or method template, and wait for instantiation.
13991   //   - There's a scope specifier that does match some template
13992   //     parameter lists, which we don't handle right now.
13993   } else {
13994     if (D.isFunctionDefinition()) {
13995       // C++ [class.friend]p6:
13996       //   A function can be defined in a friend declaration of a class if and
13997       //   only if the class is a non-local class (9.8), the function name is
13998       //   unqualified, and the function has namespace scope.
13999       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14000         << SS.getScopeRep();
14001     }
14002 
14003     DC = CurContext;
14004     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14005   }
14006 
14007   if (!DC->isRecord()) {
14008     int DiagArg = -1;
14009     switch (D.getName().getKind()) {
14010     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14011     case UnqualifiedIdKind::IK_ConstructorName:
14012       DiagArg = 0;
14013       break;
14014     case UnqualifiedIdKind::IK_DestructorName:
14015       DiagArg = 1;
14016       break;
14017     case UnqualifiedIdKind::IK_ConversionFunctionId:
14018       DiagArg = 2;
14019       break;
14020     case UnqualifiedIdKind::IK_DeductionGuideName:
14021       DiagArg = 3;
14022       break;
14023     case UnqualifiedIdKind::IK_Identifier:
14024     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14025     case UnqualifiedIdKind::IK_LiteralOperatorId:
14026     case UnqualifiedIdKind::IK_OperatorFunctionId:
14027     case UnqualifiedIdKind::IK_TemplateId:
14028       break;
14029     }
14030     // This implies that it has to be an operator or function.
14031     if (DiagArg >= 0) {
14032       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14033       return nullptr;
14034     }
14035   }
14036 
14037   // FIXME: This is an egregious hack to cope with cases where the scope stack
14038   // does not contain the declaration context, i.e., in an out-of-line
14039   // definition of a class.
14040   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14041   if (!DCScope) {
14042     FakeDCScope.setEntity(DC);
14043     DCScope = &FakeDCScope;
14044   }
14045 
14046   bool AddToScope = true;
14047   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14048                                           TemplateParams, AddToScope);
14049   if (!ND) return nullptr;
14050 
14051   assert(ND->getLexicalDeclContext() == CurContext);
14052 
14053   // If we performed typo correction, we might have added a scope specifier
14054   // and changed the decl context.
14055   DC = ND->getDeclContext();
14056 
14057   // Add the function declaration to the appropriate lookup tables,
14058   // adjusting the redeclarations list as necessary.  We don't
14059   // want to do this yet if the friending class is dependent.
14060   //
14061   // Also update the scope-based lookup if the target context's
14062   // lookup context is in lexical scope.
14063   if (!CurContext->isDependentContext()) {
14064     DC = DC->getRedeclContext();
14065     DC->makeDeclVisibleInContext(ND);
14066     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14067       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14068   }
14069 
14070   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14071                                        D.getIdentifierLoc(), ND,
14072                                        DS.getFriendSpecLoc());
14073   FrD->setAccess(AS_public);
14074   CurContext->addDecl(FrD);
14075 
14076   if (ND->isInvalidDecl()) {
14077     FrD->setInvalidDecl();
14078   } else {
14079     if (DC->isRecord()) CheckFriendAccess(ND);
14080 
14081     FunctionDecl *FD;
14082     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14083       FD = FTD->getTemplatedDecl();
14084     else
14085       FD = cast<FunctionDecl>(ND);
14086 
14087     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14088     // default argument expression, that declaration shall be a definition
14089     // and shall be the only declaration of the function or function
14090     // template in the translation unit.
14091     if (functionDeclHasDefaultArgument(FD)) {
14092       // We can't look at FD->getPreviousDecl() because it may not have been set
14093       // if we're in a dependent context. If the function is known to be a
14094       // redeclaration, we will have narrowed Previous down to the right decl.
14095       if (D.isRedeclaration()) {
14096         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14097         Diag(Previous.getRepresentativeDecl()->getLocation(),
14098              diag::note_previous_declaration);
14099       } else if (!D.isFunctionDefinition())
14100         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14101     }
14102 
14103     // Mark templated-scope function declarations as unsupported.
14104     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14105       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14106         << SS.getScopeRep() << SS.getRange()
14107         << cast<CXXRecordDecl>(CurContext);
14108       FrD->setUnsupportedFriend(true);
14109     }
14110   }
14111 
14112   return ND;
14113 }
14114 
14115 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14116   AdjustDeclIfTemplate(Dcl);
14117 
14118   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14119   if (!Fn) {
14120     Diag(DelLoc, diag::err_deleted_non_function);
14121     return;
14122   }
14123 
14124   // Deleted function does not have a body.
14125   Fn->setWillHaveBody(false);
14126 
14127   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14128     // Don't consider the implicit declaration we generate for explicit
14129     // specializations. FIXME: Do not generate these implicit declarations.
14130     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14131          Prev->getPreviousDecl()) &&
14132         !Prev->isDefined()) {
14133       Diag(DelLoc, diag::err_deleted_decl_not_first);
14134       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14135            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14136                               : diag::note_previous_declaration);
14137     }
14138     // If the declaration wasn't the first, we delete the function anyway for
14139     // recovery.
14140     Fn = Fn->getCanonicalDecl();
14141   }
14142 
14143   // dllimport/dllexport cannot be deleted.
14144   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14145     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14146     Fn->setInvalidDecl();
14147   }
14148 
14149   if (Fn->isDeleted())
14150     return;
14151 
14152   // See if we're deleting a function which is already known to override a
14153   // non-deleted virtual function.
14154   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14155     bool IssuedDiagnostic = false;
14156     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14157       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14158         if (!IssuedDiagnostic) {
14159           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14160           IssuedDiagnostic = true;
14161         }
14162         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14163       }
14164     }
14165     // If this function was implicitly deleted because it was defaulted,
14166     // explain why it was deleted.
14167     if (IssuedDiagnostic && MD->isDefaulted())
14168       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14169                                 /*Diagnose*/true);
14170   }
14171 
14172   // C++11 [basic.start.main]p3:
14173   //   A program that defines main as deleted [...] is ill-formed.
14174   if (Fn->isMain())
14175     Diag(DelLoc, diag::err_deleted_main);
14176 
14177   // C++11 [dcl.fct.def.delete]p4:
14178   //  A deleted function is implicitly inline.
14179   Fn->setImplicitlyInline();
14180   Fn->setDeletedAsWritten();
14181 }
14182 
14183 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14184   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14185 
14186   if (MD) {
14187     if (MD->getParent()->isDependentType()) {
14188       MD->setDefaulted();
14189       MD->setExplicitlyDefaulted();
14190       return;
14191     }
14192 
14193     CXXSpecialMember Member = getSpecialMember(MD);
14194     if (Member == CXXInvalid) {
14195       if (!MD->isInvalidDecl())
14196         Diag(DefaultLoc, diag::err_default_special_members);
14197       return;
14198     }
14199 
14200     MD->setDefaulted();
14201     MD->setExplicitlyDefaulted();
14202 
14203     // Unset that we will have a body for this function. We might not,
14204     // if it turns out to be trivial, and we don't need this marking now
14205     // that we've marked it as defaulted.
14206     MD->setWillHaveBody(false);
14207 
14208     // If this definition appears within the record, do the checking when
14209     // the record is complete.
14210     const FunctionDecl *Primary = MD;
14211     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14212       // Ask the template instantiation pattern that actually had the
14213       // '= default' on it.
14214       Primary = Pattern;
14215 
14216     // If the method was defaulted on its first declaration, we will have
14217     // already performed the checking in CheckCompletedCXXClass. Such a
14218     // declaration doesn't trigger an implicit definition.
14219     if (Primary->getCanonicalDecl()->isDefaulted())
14220       return;
14221 
14222     CheckExplicitlyDefaultedSpecialMember(MD);
14223 
14224     if (!MD->isInvalidDecl())
14225       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14226   } else {
14227     Diag(DefaultLoc, diag::err_default_special_members);
14228   }
14229 }
14230 
14231 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14232   for (Stmt *SubStmt : S->children()) {
14233     if (!SubStmt)
14234       continue;
14235     if (isa<ReturnStmt>(SubStmt))
14236       Self.Diag(SubStmt->getLocStart(),
14237            diag::err_return_in_constructor_handler);
14238     if (!isa<Expr>(SubStmt))
14239       SearchForReturnInStmt(Self, SubStmt);
14240   }
14241 }
14242 
14243 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14244   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14245     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14246     SearchForReturnInStmt(*this, Handler);
14247   }
14248 }
14249 
14250 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14251                                              const CXXMethodDecl *Old) {
14252   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14253   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14254 
14255   if (OldFT->hasExtParameterInfos()) {
14256     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14257       // A parameter of the overriding method should be annotated with noescape
14258       // if the corresponding parameter of the overridden method is annotated.
14259       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14260           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14261         Diag(New->getParamDecl(I)->getLocation(),
14262              diag::warn_overriding_method_missing_noescape);
14263         Diag(Old->getParamDecl(I)->getLocation(),
14264              diag::note_overridden_marked_noescape);
14265       }
14266   }
14267 
14268   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14269 
14270   // If the calling conventions match, everything is fine
14271   if (NewCC == OldCC)
14272     return false;
14273 
14274   // If the calling conventions mismatch because the new function is static,
14275   // suppress the calling convention mismatch error; the error about static
14276   // function override (err_static_overrides_virtual from
14277   // Sema::CheckFunctionDeclaration) is more clear.
14278   if (New->getStorageClass() == SC_Static)
14279     return false;
14280 
14281   Diag(New->getLocation(),
14282        diag::err_conflicting_overriding_cc_attributes)
14283     << New->getDeclName() << New->getType() << Old->getType();
14284   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14285   return true;
14286 }
14287 
14288 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14289                                              const CXXMethodDecl *Old) {
14290   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14291   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14292 
14293   if (Context.hasSameType(NewTy, OldTy) ||
14294       NewTy->isDependentType() || OldTy->isDependentType())
14295     return false;
14296 
14297   // Check if the return types are covariant
14298   QualType NewClassTy, OldClassTy;
14299 
14300   /// Both types must be pointers or references to classes.
14301   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14302     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14303       NewClassTy = NewPT->getPointeeType();
14304       OldClassTy = OldPT->getPointeeType();
14305     }
14306   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14307     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14308       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14309         NewClassTy = NewRT->getPointeeType();
14310         OldClassTy = OldRT->getPointeeType();
14311       }
14312     }
14313   }
14314 
14315   // The return types aren't either both pointers or references to a class type.
14316   if (NewClassTy.isNull()) {
14317     Diag(New->getLocation(),
14318          diag::err_different_return_type_for_overriding_virtual_function)
14319         << New->getDeclName() << NewTy << OldTy
14320         << New->getReturnTypeSourceRange();
14321     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14322         << Old->getReturnTypeSourceRange();
14323 
14324     return true;
14325   }
14326 
14327   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14328     // C++14 [class.virtual]p8:
14329     //   If the class type in the covariant return type of D::f differs from
14330     //   that of B::f, the class type in the return type of D::f shall be
14331     //   complete at the point of declaration of D::f or shall be the class
14332     //   type D.
14333     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14334       if (!RT->isBeingDefined() &&
14335           RequireCompleteType(New->getLocation(), NewClassTy,
14336                               diag::err_covariant_return_incomplete,
14337                               New->getDeclName()))
14338         return true;
14339     }
14340 
14341     // Check if the new class derives from the old class.
14342     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14343       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14344           << New->getDeclName() << NewTy << OldTy
14345           << New->getReturnTypeSourceRange();
14346       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14347           << Old->getReturnTypeSourceRange();
14348       return true;
14349     }
14350 
14351     // Check if we the conversion from derived to base is valid.
14352     if (CheckDerivedToBaseConversion(
14353             NewClassTy, OldClassTy,
14354             diag::err_covariant_return_inaccessible_base,
14355             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14356             New->getLocation(), New->getReturnTypeSourceRange(),
14357             New->getDeclName(), nullptr)) {
14358       // FIXME: this note won't trigger for delayed access control
14359       // diagnostics, and it's impossible to get an undelayed error
14360       // here from access control during the original parse because
14361       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14362       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14363           << Old->getReturnTypeSourceRange();
14364       return true;
14365     }
14366   }
14367 
14368   // The qualifiers of the return types must be the same.
14369   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14370     Diag(New->getLocation(),
14371          diag::err_covariant_return_type_different_qualifications)
14372         << New->getDeclName() << NewTy << OldTy
14373         << New->getReturnTypeSourceRange();
14374     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14375         << Old->getReturnTypeSourceRange();
14376     return true;
14377   }
14378 
14379 
14380   // The new class type must have the same or less qualifiers as the old type.
14381   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14382     Diag(New->getLocation(),
14383          diag::err_covariant_return_type_class_type_more_qualified)
14384         << New->getDeclName() << NewTy << OldTy
14385         << New->getReturnTypeSourceRange();
14386     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14387         << Old->getReturnTypeSourceRange();
14388     return true;
14389   }
14390 
14391   return false;
14392 }
14393 
14394 /// \brief Mark the given method pure.
14395 ///
14396 /// \param Method the method to be marked pure.
14397 ///
14398 /// \param InitRange the source range that covers the "0" initializer.
14399 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14400   SourceLocation EndLoc = InitRange.getEnd();
14401   if (EndLoc.isValid())
14402     Method->setRangeEnd(EndLoc);
14403 
14404   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14405     Method->setPure();
14406     return false;
14407   }
14408 
14409   if (!Method->isInvalidDecl())
14410     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14411       << Method->getDeclName() << InitRange;
14412   return true;
14413 }
14414 
14415 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14416   if (D->getFriendObjectKind())
14417     Diag(D->getLocation(), diag::err_pure_friend);
14418   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14419     CheckPureMethod(M, ZeroLoc);
14420   else
14421     Diag(D->getLocation(), diag::err_illegal_initializer);
14422 }
14423 
14424 /// \brief Determine whether the given declaration is a global variable or
14425 /// static data member.
14426 static bool isNonlocalVariable(const Decl *D) {
14427   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14428     return Var->hasGlobalStorage();
14429 
14430   return false;
14431 }
14432 
14433 /// Invoked when we are about to parse an initializer for the declaration
14434 /// 'Dcl'.
14435 ///
14436 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14437 /// static data member of class X, names should be looked up in the scope of
14438 /// class X. If the declaration had a scope specifier, a scope will have
14439 /// been created and passed in for this purpose. Otherwise, S will be null.
14440 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14441   // If there is no declaration, there was an error parsing it.
14442   if (!D || D->isInvalidDecl())
14443     return;
14444 
14445   // We will always have a nested name specifier here, but this declaration
14446   // might not be out of line if the specifier names the current namespace:
14447   //   extern int n;
14448   //   int ::n = 0;
14449   if (S && D->isOutOfLine())
14450     EnterDeclaratorContext(S, D->getDeclContext());
14451 
14452   // If we are parsing the initializer for a static data member, push a
14453   // new expression evaluation context that is associated with this static
14454   // data member.
14455   if (isNonlocalVariable(D))
14456     PushExpressionEvaluationContext(
14457         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14458 }
14459 
14460 /// Invoked after we are finished parsing an initializer for the declaration D.
14461 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14462   // If there is no declaration, there was an error parsing it.
14463   if (!D || D->isInvalidDecl())
14464     return;
14465 
14466   if (isNonlocalVariable(D))
14467     PopExpressionEvaluationContext();
14468 
14469   if (S && D->isOutOfLine())
14470     ExitDeclaratorContext(S);
14471 }
14472 
14473 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14474 /// C++ if/switch/while/for statement.
14475 /// e.g: "if (int x = f()) {...}"
14476 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14477   // C++ 6.4p2:
14478   // The declarator shall not specify a function or an array.
14479   // The type-specifier-seq shall not contain typedef and shall not declare a
14480   // new class or enumeration.
14481   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14482          "Parser allowed 'typedef' as storage class of condition decl.");
14483 
14484   Decl *Dcl = ActOnDeclarator(S, D);
14485   if (!Dcl)
14486     return true;
14487 
14488   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14489     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14490       << D.getSourceRange();
14491     return true;
14492   }
14493 
14494   return Dcl;
14495 }
14496 
14497 void Sema::LoadExternalVTableUses() {
14498   if (!ExternalSource)
14499     return;
14500 
14501   SmallVector<ExternalVTableUse, 4> VTables;
14502   ExternalSource->ReadUsedVTables(VTables);
14503   SmallVector<VTableUse, 4> NewUses;
14504   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14505     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14506       = VTablesUsed.find(VTables[I].Record);
14507     // Even if a definition wasn't required before, it may be required now.
14508     if (Pos != VTablesUsed.end()) {
14509       if (!Pos->second && VTables[I].DefinitionRequired)
14510         Pos->second = true;
14511       continue;
14512     }
14513 
14514     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14515     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14516   }
14517 
14518   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14519 }
14520 
14521 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14522                           bool DefinitionRequired) {
14523   // Ignore any vtable uses in unevaluated operands or for classes that do
14524   // not have a vtable.
14525   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14526       CurContext->isDependentContext() || isUnevaluatedContext())
14527     return;
14528 
14529   // Try to insert this class into the map.
14530   LoadExternalVTableUses();
14531   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14532   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14533     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14534   if (!Pos.second) {
14535     // If we already had an entry, check to see if we are promoting this vtable
14536     // to require a definition. If so, we need to reappend to the VTableUses
14537     // list, since we may have already processed the first entry.
14538     if (DefinitionRequired && !Pos.first->second) {
14539       Pos.first->second = true;
14540     } else {
14541       // Otherwise, we can early exit.
14542       return;
14543     }
14544   } else {
14545     // The Microsoft ABI requires that we perform the destructor body
14546     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14547     // the deleting destructor is emitted with the vtable, not with the
14548     // destructor definition as in the Itanium ABI.
14549     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14550       CXXDestructorDecl *DD = Class->getDestructor();
14551       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14552         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14553           // If this is an out-of-line declaration, marking it referenced will
14554           // not do anything. Manually call CheckDestructor to look up operator
14555           // delete().
14556           ContextRAII SavedContext(*this, DD);
14557           CheckDestructor(DD);
14558         } else {
14559           MarkFunctionReferenced(Loc, Class->getDestructor());
14560         }
14561       }
14562     }
14563   }
14564 
14565   // Local classes need to have their virtual members marked
14566   // immediately. For all other classes, we mark their virtual members
14567   // at the end of the translation unit.
14568   if (Class->isLocalClass())
14569     MarkVirtualMembersReferenced(Loc, Class);
14570   else
14571     VTableUses.push_back(std::make_pair(Class, Loc));
14572 }
14573 
14574 bool Sema::DefineUsedVTables() {
14575   LoadExternalVTableUses();
14576   if (VTableUses.empty())
14577     return false;
14578 
14579   // Note: The VTableUses vector could grow as a result of marking
14580   // the members of a class as "used", so we check the size each
14581   // time through the loop and prefer indices (which are stable) to
14582   // iterators (which are not).
14583   bool DefinedAnything = false;
14584   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14585     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14586     if (!Class)
14587       continue;
14588     TemplateSpecializationKind ClassTSK =
14589         Class->getTemplateSpecializationKind();
14590 
14591     SourceLocation Loc = VTableUses[I].second;
14592 
14593     bool DefineVTable = true;
14594 
14595     // If this class has a key function, but that key function is
14596     // defined in another translation unit, we don't need to emit the
14597     // vtable even though we're using it.
14598     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14599     if (KeyFunction && !KeyFunction->hasBody()) {
14600       // The key function is in another translation unit.
14601       DefineVTable = false;
14602       TemplateSpecializationKind TSK =
14603           KeyFunction->getTemplateSpecializationKind();
14604       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14605              TSK != TSK_ImplicitInstantiation &&
14606              "Instantiations don't have key functions");
14607       (void)TSK;
14608     } else if (!KeyFunction) {
14609       // If we have a class with no key function that is the subject
14610       // of an explicit instantiation declaration, suppress the
14611       // vtable; it will live with the explicit instantiation
14612       // definition.
14613       bool IsExplicitInstantiationDeclaration =
14614           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14615       for (auto R : Class->redecls()) {
14616         TemplateSpecializationKind TSK
14617           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14618         if (TSK == TSK_ExplicitInstantiationDeclaration)
14619           IsExplicitInstantiationDeclaration = true;
14620         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14621           IsExplicitInstantiationDeclaration = false;
14622           break;
14623         }
14624       }
14625 
14626       if (IsExplicitInstantiationDeclaration)
14627         DefineVTable = false;
14628     }
14629 
14630     // The exception specifications for all virtual members may be needed even
14631     // if we are not providing an authoritative form of the vtable in this TU.
14632     // We may choose to emit it available_externally anyway.
14633     if (!DefineVTable) {
14634       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14635       continue;
14636     }
14637 
14638     // Mark all of the virtual members of this class as referenced, so
14639     // that we can build a vtable. Then, tell the AST consumer that a
14640     // vtable for this class is required.
14641     DefinedAnything = true;
14642     MarkVirtualMembersReferenced(Loc, Class);
14643     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14644     if (VTablesUsed[Canonical])
14645       Consumer.HandleVTable(Class);
14646 
14647     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14648     // no key function or the key function is inlined. Don't warn in C++ ABIs
14649     // that lack key functions, since the user won't be able to make one.
14650     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14651         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14652       const FunctionDecl *KeyFunctionDef = nullptr;
14653       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14654                            KeyFunctionDef->isInlined())) {
14655         Diag(Class->getLocation(),
14656              ClassTSK == TSK_ExplicitInstantiationDefinition
14657                  ? diag::warn_weak_template_vtable
14658                  : diag::warn_weak_vtable)
14659             << Class;
14660       }
14661     }
14662   }
14663   VTableUses.clear();
14664 
14665   return DefinedAnything;
14666 }
14667 
14668 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14669                                                  const CXXRecordDecl *RD) {
14670   for (const auto *I : RD->methods())
14671     if (I->isVirtual() && !I->isPure())
14672       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14673 }
14674 
14675 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14676                                         const CXXRecordDecl *RD) {
14677   // Mark all functions which will appear in RD's vtable as used.
14678   CXXFinalOverriderMap FinalOverriders;
14679   RD->getFinalOverriders(FinalOverriders);
14680   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14681                                             E = FinalOverriders.end();
14682        I != E; ++I) {
14683     for (OverridingMethods::const_iterator OI = I->second.begin(),
14684                                            OE = I->second.end();
14685          OI != OE; ++OI) {
14686       assert(OI->second.size() > 0 && "no final overrider");
14687       CXXMethodDecl *Overrider = OI->second.front().Method;
14688 
14689       // C++ [basic.def.odr]p2:
14690       //   [...] A virtual member function is used if it is not pure. [...]
14691       if (!Overrider->isPure())
14692         MarkFunctionReferenced(Loc, Overrider);
14693     }
14694   }
14695 
14696   // Only classes that have virtual bases need a VTT.
14697   if (RD->getNumVBases() == 0)
14698     return;
14699 
14700   for (const auto &I : RD->bases()) {
14701     const CXXRecordDecl *Base =
14702         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14703     if (Base->getNumVBases() == 0)
14704       continue;
14705     MarkVirtualMembersReferenced(Loc, Base);
14706   }
14707 }
14708 
14709 /// SetIvarInitializers - This routine builds initialization ASTs for the
14710 /// Objective-C implementation whose ivars need be initialized.
14711 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14712   if (!getLangOpts().CPlusPlus)
14713     return;
14714   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14715     SmallVector<ObjCIvarDecl*, 8> ivars;
14716     CollectIvarsToConstructOrDestruct(OID, ivars);
14717     if (ivars.empty())
14718       return;
14719     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14720     for (unsigned i = 0; i < ivars.size(); i++) {
14721       FieldDecl *Field = ivars[i];
14722       if (Field->isInvalidDecl())
14723         continue;
14724 
14725       CXXCtorInitializer *Member;
14726       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14727       InitializationKind InitKind =
14728         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14729 
14730       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14731       ExprResult MemberInit =
14732         InitSeq.Perform(*this, InitEntity, InitKind, None);
14733       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14734       // Note, MemberInit could actually come back empty if no initialization
14735       // is required (e.g., because it would call a trivial default constructor)
14736       if (!MemberInit.get() || MemberInit.isInvalid())
14737         continue;
14738 
14739       Member =
14740         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14741                                          SourceLocation(),
14742                                          MemberInit.getAs<Expr>(),
14743                                          SourceLocation());
14744       AllToInit.push_back(Member);
14745 
14746       // Be sure that the destructor is accessible and is marked as referenced.
14747       if (const RecordType *RecordTy =
14748               Context.getBaseElementType(Field->getType())
14749                   ->getAs<RecordType>()) {
14750         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14751         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14752           MarkFunctionReferenced(Field->getLocation(), Destructor);
14753           CheckDestructorAccess(Field->getLocation(), Destructor,
14754                             PDiag(diag::err_access_dtor_ivar)
14755                               << Context.getBaseElementType(Field->getType()));
14756         }
14757       }
14758     }
14759     ObjCImplementation->setIvarInitializers(Context,
14760                                             AllToInit.data(), AllToInit.size());
14761   }
14762 }
14763 
14764 static
14765 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14766                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14767                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14768                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14769                            Sema &S) {
14770   if (Ctor->isInvalidDecl())
14771     return;
14772 
14773   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14774 
14775   // Target may not be determinable yet, for instance if this is a dependent
14776   // call in an uninstantiated template.
14777   if (Target) {
14778     const FunctionDecl *FNTarget = nullptr;
14779     (void)Target->hasBody(FNTarget);
14780     Target = const_cast<CXXConstructorDecl*>(
14781       cast_or_null<CXXConstructorDecl>(FNTarget));
14782   }
14783 
14784   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14785                      // Avoid dereferencing a null pointer here.
14786                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14787 
14788   if (!Current.insert(Canonical).second)
14789     return;
14790 
14791   // We know that beyond here, we aren't chaining into a cycle.
14792   if (!Target || !Target->isDelegatingConstructor() ||
14793       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14794     Valid.insert(Current.begin(), Current.end());
14795     Current.clear();
14796   // We've hit a cycle.
14797   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14798              Current.count(TCanonical)) {
14799     // If we haven't diagnosed this cycle yet, do so now.
14800     if (!Invalid.count(TCanonical)) {
14801       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14802              diag::warn_delegating_ctor_cycle)
14803         << Ctor;
14804 
14805       // Don't add a note for a function delegating directly to itself.
14806       if (TCanonical != Canonical)
14807         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14808 
14809       CXXConstructorDecl *C = Target;
14810       while (C->getCanonicalDecl() != Canonical) {
14811         const FunctionDecl *FNTarget = nullptr;
14812         (void)C->getTargetConstructor()->hasBody(FNTarget);
14813         assert(FNTarget && "Ctor cycle through bodiless function");
14814 
14815         C = const_cast<CXXConstructorDecl*>(
14816           cast<CXXConstructorDecl>(FNTarget));
14817         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14818       }
14819     }
14820 
14821     Invalid.insert(Current.begin(), Current.end());
14822     Current.clear();
14823   } else {
14824     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14825   }
14826 }
14827 
14828 
14829 void Sema::CheckDelegatingCtorCycles() {
14830   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14831 
14832   for (DelegatingCtorDeclsType::iterator
14833          I = DelegatingCtorDecls.begin(ExternalSource),
14834          E = DelegatingCtorDecls.end();
14835        I != E; ++I)
14836     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14837 
14838   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14839                                                          CE = Invalid.end();
14840        CI != CE; ++CI)
14841     (*CI)->setInvalidDecl();
14842 }
14843 
14844 namespace {
14845   /// \brief AST visitor that finds references to the 'this' expression.
14846   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14847     Sema &S;
14848 
14849   public:
14850     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14851 
14852     bool VisitCXXThisExpr(CXXThisExpr *E) {
14853       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14854         << E->isImplicit();
14855       return false;
14856     }
14857   };
14858 }
14859 
14860 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14861   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14862   if (!TSInfo)
14863     return false;
14864 
14865   TypeLoc TL = TSInfo->getTypeLoc();
14866   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14867   if (!ProtoTL)
14868     return false;
14869 
14870   // C++11 [expr.prim.general]p3:
14871   //   [The expression this] shall not appear before the optional
14872   //   cv-qualifier-seq and it shall not appear within the declaration of a
14873   //   static member function (although its type and value category are defined
14874   //   within a static member function as they are within a non-static member
14875   //   function). [ Note: this is because declaration matching does not occur
14876   //  until the complete declarator is known. - end note ]
14877   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14878   FindCXXThisExpr Finder(*this);
14879 
14880   // If the return type came after the cv-qualifier-seq, check it now.
14881   if (Proto->hasTrailingReturn() &&
14882       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14883     return true;
14884 
14885   // Check the exception specification.
14886   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14887     return true;
14888 
14889   return checkThisInStaticMemberFunctionAttributes(Method);
14890 }
14891 
14892 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14893   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14894   if (!TSInfo)
14895     return false;
14896 
14897   TypeLoc TL = TSInfo->getTypeLoc();
14898   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14899   if (!ProtoTL)
14900     return false;
14901 
14902   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14903   FindCXXThisExpr Finder(*this);
14904 
14905   switch (Proto->getExceptionSpecType()) {
14906   case EST_Unparsed:
14907   case EST_Uninstantiated:
14908   case EST_Unevaluated:
14909   case EST_BasicNoexcept:
14910   case EST_DynamicNone:
14911   case EST_MSAny:
14912   case EST_None:
14913     break;
14914 
14915   case EST_ComputedNoexcept:
14916     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14917       return true;
14918     LLVM_FALLTHROUGH;
14919 
14920   case EST_Dynamic:
14921     for (const auto &E : Proto->exceptions()) {
14922       if (!Finder.TraverseType(E))
14923         return true;
14924     }
14925     break;
14926   }
14927 
14928   return false;
14929 }
14930 
14931 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14932   FindCXXThisExpr Finder(*this);
14933 
14934   // Check attributes.
14935   for (const auto *A : Method->attrs()) {
14936     // FIXME: This should be emitted by tblgen.
14937     Expr *Arg = nullptr;
14938     ArrayRef<Expr *> Args;
14939     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14940       Arg = G->getArg();
14941     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14942       Arg = G->getArg();
14943     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14944       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14945     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14946       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14947     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14948       Arg = ETLF->getSuccessValue();
14949       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14950     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14951       Arg = STLF->getSuccessValue();
14952       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14953     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14954       Arg = LR->getArg();
14955     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14956       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14957     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14958       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14959     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14960       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14961     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14962       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14963     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14964       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14965 
14966     if (Arg && !Finder.TraverseStmt(Arg))
14967       return true;
14968 
14969     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14970       if (!Finder.TraverseStmt(Args[I]))
14971         return true;
14972     }
14973   }
14974 
14975   return false;
14976 }
14977 
14978 void Sema::checkExceptionSpecification(
14979     bool IsTopLevel, ExceptionSpecificationType EST,
14980     ArrayRef<ParsedType> DynamicExceptions,
14981     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14982     SmallVectorImpl<QualType> &Exceptions,
14983     FunctionProtoType::ExceptionSpecInfo &ESI) {
14984   Exceptions.clear();
14985   ESI.Type = EST;
14986   if (EST == EST_Dynamic) {
14987     Exceptions.reserve(DynamicExceptions.size());
14988     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14989       // FIXME: Preserve type source info.
14990       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14991 
14992       if (IsTopLevel) {
14993         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14994         collectUnexpandedParameterPacks(ET, Unexpanded);
14995         if (!Unexpanded.empty()) {
14996           DiagnoseUnexpandedParameterPacks(
14997               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14998               Unexpanded);
14999           continue;
15000         }
15001       }
15002 
15003       // Check that the type is valid for an exception spec, and
15004       // drop it if not.
15005       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15006         Exceptions.push_back(ET);
15007     }
15008     ESI.Exceptions = Exceptions;
15009     return;
15010   }
15011 
15012   if (EST == EST_ComputedNoexcept) {
15013     // If an error occurred, there's no expression here.
15014     if (NoexceptExpr) {
15015       assert((NoexceptExpr->isTypeDependent() ||
15016               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15017               Context.BoolTy) &&
15018              "Parser should have made sure that the expression is boolean");
15019       if (IsTopLevel && NoexceptExpr &&
15020           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15021         ESI.Type = EST_BasicNoexcept;
15022         return;
15023       }
15024 
15025       if (!NoexceptExpr->isValueDependent()) {
15026         ExprResult Result = VerifyIntegerConstantExpression(
15027             NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression,
15028             /*AllowFold*/ false);
15029         if (Result.isInvalid()) {
15030           ESI.Type = EST_BasicNoexcept;
15031           return;
15032         }
15033         NoexceptExpr = Result.get();
15034       }
15035       ESI.NoexceptExpr = NoexceptExpr;
15036     }
15037     return;
15038   }
15039 }
15040 
15041 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15042              ExceptionSpecificationType EST,
15043              SourceRange SpecificationRange,
15044              ArrayRef<ParsedType> DynamicExceptions,
15045              ArrayRef<SourceRange> DynamicExceptionRanges,
15046              Expr *NoexceptExpr) {
15047   if (!MethodD)
15048     return;
15049 
15050   // Dig out the method we're referring to.
15051   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15052     MethodD = FunTmpl->getTemplatedDecl();
15053 
15054   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15055   if (!Method)
15056     return;
15057 
15058   // Check the exception specification.
15059   llvm::SmallVector<QualType, 4> Exceptions;
15060   FunctionProtoType::ExceptionSpecInfo ESI;
15061   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15062                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15063                               ESI);
15064 
15065   // Update the exception specification on the function type.
15066   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15067 
15068   if (Method->isStatic())
15069     checkThisInStaticMemberFunctionExceptionSpec(Method);
15070 
15071   if (Method->isVirtual()) {
15072     // Check overrides, which we previously had to delay.
15073     for (const CXXMethodDecl *O : Method->overridden_methods())
15074       CheckOverridingFunctionExceptionSpec(Method, O);
15075   }
15076 }
15077 
15078 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15079 ///
15080 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15081                                        SourceLocation DeclStart,
15082                                        Declarator &D, Expr *BitWidth,
15083                                        InClassInitStyle InitStyle,
15084                                        AccessSpecifier AS,
15085                                        AttributeList *MSPropertyAttr) {
15086   IdentifierInfo *II = D.getIdentifier();
15087   if (!II) {
15088     Diag(DeclStart, diag::err_anonymous_property);
15089     return nullptr;
15090   }
15091   SourceLocation Loc = D.getIdentifierLoc();
15092 
15093   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15094   QualType T = TInfo->getType();
15095   if (getLangOpts().CPlusPlus) {
15096     CheckExtraCXXDefaultArguments(D);
15097 
15098     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15099                                         UPPC_DataMemberType)) {
15100       D.setInvalidType();
15101       T = Context.IntTy;
15102       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15103     }
15104   }
15105 
15106   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15107 
15108   if (D.getDeclSpec().isInlineSpecified())
15109     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15110         << getLangOpts().CPlusPlus17;
15111   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15112     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15113          diag::err_invalid_thread)
15114       << DeclSpec::getSpecifierName(TSCS);
15115 
15116   // Check to see if this name was declared as a member previously
15117   NamedDecl *PrevDecl = nullptr;
15118   LookupResult Previous(*this, II, Loc, LookupMemberName,
15119                         ForVisibleRedeclaration);
15120   LookupName(Previous, S);
15121   switch (Previous.getResultKind()) {
15122   case LookupResult::Found:
15123   case LookupResult::FoundUnresolvedValue:
15124     PrevDecl = Previous.getAsSingle<NamedDecl>();
15125     break;
15126 
15127   case LookupResult::FoundOverloaded:
15128     PrevDecl = Previous.getRepresentativeDecl();
15129     break;
15130 
15131   case LookupResult::NotFound:
15132   case LookupResult::NotFoundInCurrentInstantiation:
15133   case LookupResult::Ambiguous:
15134     break;
15135   }
15136 
15137   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15138     // Maybe we will complain about the shadowed template parameter.
15139     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15140     // Just pretend that we didn't see the previous declaration.
15141     PrevDecl = nullptr;
15142   }
15143 
15144   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15145     PrevDecl = nullptr;
15146 
15147   SourceLocation TSSL = D.getLocStart();
15148   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15149   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15150       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15151   ProcessDeclAttributes(TUScope, NewPD, D);
15152   NewPD->setAccess(AS);
15153 
15154   if (NewPD->isInvalidDecl())
15155     Record->setInvalidDecl();
15156 
15157   if (D.getDeclSpec().isModulePrivateSpecified())
15158     NewPD->setModulePrivate();
15159 
15160   if (NewPD->isInvalidDecl() && PrevDecl) {
15161     // Don't introduce NewFD into scope; there's already something
15162     // with the same name in the same scope.
15163   } else if (II) {
15164     PushOnScopeChains(NewPD, S);
15165   } else
15166     Record->addDecl(NewPD);
15167 
15168   return NewPD;
15169 }
15170