1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/ComparisonCategories.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <map>
45 #include <set>
46 
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // CheckDefaultArgumentVisitor
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55   /// the default argument of a parameter to determine whether it
56   /// contains any ill-formed subexpressions. For example, this will
57   /// diagnose the use of local variables or parameters within the
58   /// default argument expression.
59   class CheckDefaultArgumentVisitor
60     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61     Expr *DefaultArg;
62     Sema *S;
63 
64   public:
65     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66       : DefaultArg(defarg), S(s) {}
67 
68     bool VisitExpr(Expr *Node);
69     bool VisitDeclRefExpr(DeclRefExpr *DRE);
70     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71     bool VisitLambdaExpr(LambdaExpr *Lambda);
72     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73   };
74 
75   /// VisitExpr - Visit all of the children of this expression.
76   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77     bool IsInvalid = false;
78     for (Stmt *SubStmt : Node->children())
79       IsInvalid |= Visit(SubStmt);
80     return IsInvalid;
81   }
82 
83   /// VisitDeclRefExpr - Visit a reference to a declaration, to
84   /// determine whether this declaration can be used in the default
85   /// argument expression.
86   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87     NamedDecl *Decl = DRE->getDecl();
88     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89       // C++ [dcl.fct.default]p9
90       //   Default arguments are evaluated each time the function is
91       //   called. The order of evaluation of function arguments is
92       //   unspecified. Consequently, parameters of a function shall not
93       //   be used in default argument expressions, even if they are not
94       //   evaluated. Parameters of a function declared before a default
95       //   argument expression are in scope and can hide namespace and
96       //   class member names.
97       return S->Diag(DRE->getLocStart(),
98                      diag::err_param_default_argument_references_param)
99          << Param->getDeclName() << DefaultArg->getSourceRange();
100     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101       // C++ [dcl.fct.default]p7
102       //   Local variables shall not be used in default argument
103       //   expressions.
104       if (VDecl->isLocalVarDecl())
105         return S->Diag(DRE->getLocStart(),
106                        diag::err_param_default_argument_references_local)
107           << VDecl->getDeclName() << DefaultArg->getSourceRange();
108     }
109 
110     return false;
111   }
112 
113   /// VisitCXXThisExpr - Visit a C++ "this" expression.
114   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115     // C++ [dcl.fct.default]p8:
116     //   The keyword this shall not be used in a default argument of a
117     //   member function.
118     return S->Diag(ThisE->getLocStart(),
119                    diag::err_param_default_argument_references_this)
120                << ThisE->getSourceRange();
121   }
122 
123   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124     bool Invalid = false;
125     for (PseudoObjectExpr::semantics_iterator
126            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127       Expr *E = *i;
128 
129       // Look through bindings.
130       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131         E = OVE->getSourceExpr();
132         assert(E && "pseudo-object binding without source expression?");
133       }
134 
135       Invalid |= Visit(E);
136     }
137     return Invalid;
138   }
139 
140   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141     // C++11 [expr.lambda.prim]p13:
142     //   A lambda-expression appearing in a default argument shall not
143     //   implicitly or explicitly capture any entity.
144     if (Lambda->capture_begin() == Lambda->capture_end())
145       return false;
146 
147     return S->Diag(Lambda->getLocStart(),
148                    diag::err_lambda_capture_default_arg);
149   }
150 }
151 
152 void
153 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
154                                                  const CXXMethodDecl *Method) {
155   // If we have an MSAny spec already, don't bother.
156   if (!Method || ComputedEST == EST_MSAny)
157     return;
158 
159   const FunctionProtoType *Proto
160     = Method->getType()->getAs<FunctionProtoType>();
161   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
162   if (!Proto)
163     return;
164 
165   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
166 
167   // If we have a throw-all spec at this point, ignore the function.
168   if (ComputedEST == EST_None)
169     return;
170 
171   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
172     EST = EST_BasicNoexcept;
173 
174   switch (EST) {
175   case EST_Unparsed:
176   case EST_Uninstantiated:
177   case EST_Unevaluated:
178     llvm_unreachable("should not see unresolved exception specs here");
179 
180   // If this function can throw any exceptions, make a note of that.
181   case EST_MSAny:
182   case EST_None:
183     // FIXME: Whichever we see last of MSAny and None determines our result.
184     // We should make a consistent, order-independent choice here.
185     ClearExceptions();
186     ComputedEST = EST;
187     return;
188   case EST_NoexceptFalse:
189     ClearExceptions();
190     ComputedEST = EST_None;
191     return;
192   // FIXME: If the call to this decl is using any of its default arguments, we
193   // need to search them for potentially-throwing calls.
194   // If this function has a basic noexcept, it doesn't affect the outcome.
195   case EST_BasicNoexcept:
196   case EST_NoexceptTrue:
197     return;
198   // If we're still at noexcept(true) and there's a throw() callee,
199   // change to that specification.
200   case EST_DynamicNone:
201     if (ComputedEST == EST_BasicNoexcept)
202       ComputedEST = EST_DynamicNone;
203     return;
204   case EST_DependentNoexcept:
205     llvm_unreachable(
206         "should not generate implicit declarations for dependent cases");
207   case EST_Dynamic:
208     break;
209   }
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217       Exceptions.push_back(E);
218 }
219 
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223 
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244 
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248 
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257 
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.getAs<Expr>();
273 
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276 
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279 
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291 
292   return false;
293 }
294 
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303 
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306 
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314 
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320 
321   // C++11 [dcl.fct.default]p3
322   //   A default argument expression [...] shall not be specified for a
323   //   parameter pack.
324   if (Param->isParameterPack()) {
325     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326         << DefaultArg->getSourceRange();
327     return;
328   }
329 
330   // Check that the default argument is well-formed
331   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332   if (DefaultArgChecker.Visit(DefaultArg)) {
333     Param->setInvalidDecl();
334     return;
335   }
336 
337   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338 }
339 
340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
341 /// argument for a function parameter, but we can't parse it yet
342 /// because we're inside a class definition. Note that this default
343 /// argument will be parsed later.
344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345                                              SourceLocation EqualLoc,
346                                              SourceLocation ArgLoc) {
347   if (!param)
348     return;
349 
350   ParmVarDecl *Param = cast<ParmVarDecl>(param);
351   Param->setUnparsedDefaultArg();
352   UnparsedDefaultArgLocs[Param] = ArgLoc;
353 }
354 
355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356 /// the default argument for the parameter param failed.
357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
358                                           SourceLocation EqualLoc) {
359   if (!param)
360     return;
361 
362   ParmVarDecl *Param = cast<ParmVarDecl>(param);
363   Param->setInvalidDecl();
364   UnparsedDefaultArgLocs.erase(Param);
365   Param->setDefaultArg(new(Context)
366                        OpaqueValueExpr(EqualLoc,
367                                        Param->getType().getNonReferenceType(),
368                                        VK_RValue));
369 }
370 
371 /// CheckExtraCXXDefaultArguments - Check for any extra default
372 /// arguments in the declarator, which is not a function declaration
373 /// or definition and therefore is not permitted to have default
374 /// arguments. This routine should be invoked for every declarator
375 /// that is not a function declaration or definition.
376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377   // C++ [dcl.fct.default]p3
378   //   A default argument expression shall be specified only in the
379   //   parameter-declaration-clause of a function declaration or in a
380   //   template-parameter (14.1). It shall not be specified for a
381   //   parameter pack. If it is specified in a
382   //   parameter-declaration-clause, it shall not occur within a
383   //   declarator or abstract-declarator of a parameter-declaration.
384   bool MightBeFunction = D.isFunctionDeclarationContext();
385   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386     DeclaratorChunk &chunk = D.getTypeObject(i);
387     if (chunk.Kind == DeclaratorChunk::Function) {
388       if (MightBeFunction) {
389         // This is a function declaration. It can have default arguments, but
390         // keep looking in case its return type is a function type with default
391         // arguments.
392         MightBeFunction = false;
393         continue;
394       }
395       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396            ++argIdx) {
397         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398         if (Param->hasUnparsedDefaultArg()) {
399           std::unique_ptr<CachedTokens> Toks =
400               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401           SourceRange SR;
402           if (Toks->size() > 1)
403             SR = SourceRange((*Toks)[1].getLocation(),
404                              Toks->back().getLocation());
405           else
406             SR = UnparsedDefaultArgLocs[Param];
407           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
408             << SR;
409         } else if (Param->getDefaultArg()) {
410           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411             << Param->getDefaultArg()->getSourceRange();
412           Param->setDefaultArg(nullptr);
413         }
414       }
415     } else if (chunk.Kind != DeclaratorChunk::Paren) {
416       MightBeFunction = false;
417     }
418   }
419 }
420 
421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424     if (!PVD->hasDefaultArg())
425       return false;
426     if (!PVD->hasInheritedDefaultArg())
427       return true;
428   }
429   return false;
430 }
431 
432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
433 /// function, once we already know that they have the same
434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435 /// error, false otherwise.
436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437                                 Scope *S) {
438   bool Invalid = false;
439 
440   // The declaration context corresponding to the scope is the semantic
441   // parent, unless this is a local function declaration, in which case
442   // it is that surrounding function.
443   DeclContext *ScopeDC = New->isLocalExternDecl()
444                              ? New->getLexicalDeclContext()
445                              : New->getDeclContext();
446 
447   // Find the previous declaration for the purpose of default arguments.
448   FunctionDecl *PrevForDefaultArgs = Old;
449   for (/**/; PrevForDefaultArgs;
450        // Don't bother looking back past the latest decl if this is a local
451        // extern declaration; nothing else could work.
452        PrevForDefaultArgs = New->isLocalExternDecl()
453                                 ? nullptr
454                                 : PrevForDefaultArgs->getPreviousDecl()) {
455     // Ignore hidden declarations.
456     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457       continue;
458 
459     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460         !New->isCXXClassMember()) {
461       // Ignore default arguments of old decl if they are not in
462       // the same scope and this is not an out-of-line definition of
463       // a member function.
464       continue;
465     }
466 
467     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468       // If only one of these is a local function declaration, then they are
469       // declared in different scopes, even though isDeclInScope may think
470       // they're in the same scope. (If both are local, the scope check is
471       // sufficient, and if neither is local, then they are in the same scope.)
472       continue;
473     }
474 
475     // We found the right previous declaration.
476     break;
477   }
478 
479   // C++ [dcl.fct.default]p4:
480   //   For non-template functions, default arguments can be added in
481   //   later declarations of a function in the same
482   //   scope. Declarations in different scopes have completely
483   //   distinct sets of default arguments. That is, declarations in
484   //   inner scopes do not acquire default arguments from
485   //   declarations in outer scopes, and vice versa. In a given
486   //   function declaration, all parameters subsequent to a
487   //   parameter with a default argument shall have default
488   //   arguments supplied in this or previous declarations. A
489   //   default argument shall not be redefined by a later
490   //   declaration (not even to the same value).
491   //
492   // C++ [dcl.fct.default]p6:
493   //   Except for member functions of class templates, the default arguments
494   //   in a member function definition that appears outside of the class
495   //   definition are added to the set of default arguments provided by the
496   //   member function declaration in the class definition.
497   for (unsigned p = 0, NumParams = PrevForDefaultArgs
498                                        ? PrevForDefaultArgs->getNumParams()
499                                        : 0;
500        p < NumParams; ++p) {
501     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
502     ParmVarDecl *NewParam = New->getParamDecl(p);
503 
504     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
505     bool NewParamHasDfl = NewParam->hasDefaultArg();
506 
507     if (OldParamHasDfl && NewParamHasDfl) {
508       unsigned DiagDefaultParamID =
509         diag::err_param_default_argument_redefinition;
510 
511       // MSVC accepts that default parameters be redefined for member functions
512       // of template class. The new default parameter's value is ignored.
513       Invalid = true;
514       if (getLangOpts().MicrosoftExt) {
515         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
516         if (MD && MD->getParent()->getDescribedClassTemplate()) {
517           // Merge the old default argument into the new parameter.
518           NewParam->setHasInheritedDefaultArg();
519           if (OldParam->hasUninstantiatedDefaultArg())
520             NewParam->setUninstantiatedDefaultArg(
521                                       OldParam->getUninstantiatedDefaultArg());
522           else
523             NewParam->setDefaultArg(OldParam->getInit());
524           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
525           Invalid = false;
526         }
527       }
528 
529       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530       // hint here. Alternatively, we could walk the type-source information
531       // for NewParam to find the last source location in the type... but it
532       // isn't worth the effort right now. This is the kind of test case that
533       // is hard to get right:
534       //   int f(int);
535       //   void g(int (*fp)(int) = f);
536       //   void g(int (*fp)(int) = &f);
537       Diag(NewParam->getLocation(), DiagDefaultParamID)
538         << NewParam->getDefaultArgRange();
539 
540       // Look for the function declaration where the default argument was
541       // actually written, which may be a declaration prior to Old.
542       for (auto Older = PrevForDefaultArgs;
543            OldParam->hasInheritedDefaultArg(); /**/) {
544         Older = Older->getPreviousDecl();
545         OldParam = Older->getParamDecl(p);
546       }
547 
548       Diag(OldParam->getLocation(), diag::note_previous_definition)
549         << OldParam->getDefaultArgRange();
550     } else if (OldParamHasDfl) {
551       // Merge the old default argument into the new parameter unless the new
552       // function is a friend declaration in a template class. In the latter
553       // case the default arguments will be inherited when the friend
554       // declaration will be instantiated.
555       if (New->getFriendObjectKind() == Decl::FOK_None ||
556           !New->getLexicalDeclContext()->isDependentContext()) {
557         // It's important to use getInit() here;  getDefaultArg()
558         // strips off any top-level ExprWithCleanups.
559         NewParam->setHasInheritedDefaultArg();
560         if (OldParam->hasUnparsedDefaultArg())
561           NewParam->setUnparsedDefaultArg();
562         else if (OldParam->hasUninstantiatedDefaultArg())
563           NewParam->setUninstantiatedDefaultArg(
564                                        OldParam->getUninstantiatedDefaultArg());
565         else
566           NewParam->setDefaultArg(OldParam->getInit());
567       }
568     } else if (NewParamHasDfl) {
569       if (New->getDescribedFunctionTemplate()) {
570         // Paragraph 4, quoted above, only applies to non-template functions.
571         Diag(NewParam->getLocation(),
572              diag::err_param_default_argument_template_redecl)
573           << NewParam->getDefaultArgRange();
574         Diag(PrevForDefaultArgs->getLocation(),
575              diag::note_template_prev_declaration)
576             << false;
577       } else if (New->getTemplateSpecializationKind()
578                    != TSK_ImplicitInstantiation &&
579                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
580         // C++ [temp.expr.spec]p21:
581         //   Default function arguments shall not be specified in a declaration
582         //   or a definition for one of the following explicit specializations:
583         //     - the explicit specialization of a function template;
584         //     - the explicit specialization of a member function template;
585         //     - the explicit specialization of a member function of a class
586         //       template where the class template specialization to which the
587         //       member function specialization belongs is implicitly
588         //       instantiated.
589         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
590           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
591           << New->getDeclName()
592           << NewParam->getDefaultArgRange();
593       } else if (New->getDeclContext()->isDependentContext()) {
594         // C++ [dcl.fct.default]p6 (DR217):
595         //   Default arguments for a member function of a class template shall
596         //   be specified on the initial declaration of the member function
597         //   within the class template.
598         //
599         // Reading the tea leaves a bit in DR217 and its reference to DR205
600         // leads me to the conclusion that one cannot add default function
601         // arguments for an out-of-line definition of a member function of a
602         // dependent type.
603         int WhichKind = 2;
604         if (CXXRecordDecl *Record
605               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
606           if (Record->getDescribedClassTemplate())
607             WhichKind = 0;
608           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
609             WhichKind = 1;
610           else
611             WhichKind = 2;
612         }
613 
614         Diag(NewParam->getLocation(),
615              diag::err_param_default_argument_member_template_redecl)
616           << WhichKind
617           << NewParam->getDefaultArgRange();
618       }
619     }
620   }
621 
622   // DR1344: If a default argument is added outside a class definition and that
623   // default argument makes the function a special member function, the program
624   // is ill-formed. This can only happen for constructors.
625   if (isa<CXXConstructorDecl>(New) &&
626       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
627     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
628                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
629     if (NewSM != OldSM) {
630       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
631       assert(NewParam->hasDefaultArg());
632       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
633         << NewParam->getDefaultArgRange() << NewSM;
634       Diag(Old->getLocation(), diag::note_previous_declaration);
635     }
636   }
637 
638   const FunctionDecl *Def;
639   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
640   // template has a constexpr specifier then all its declarations shall
641   // contain the constexpr specifier.
642   if (New->isConstexpr() != Old->isConstexpr()) {
643     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
644       << New << New->isConstexpr();
645     Diag(Old->getLocation(), diag::note_previous_declaration);
646     Invalid = true;
647   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
648              Old->isDefined(Def) &&
649              // If a friend function is inlined but does not have 'inline'
650              // specifier, it is a definition. Do not report attribute conflict
651              // in this case, redefinition will be diagnosed later.
652              (New->isInlineSpecified() ||
653               New->getFriendObjectKind() == Decl::FOK_None)) {
654     // C++11 [dcl.fcn.spec]p4:
655     //   If the definition of a function appears in a translation unit before its
656     //   first declaration as inline, the program is ill-formed.
657     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
658     Diag(Def->getLocation(), diag::note_previous_definition);
659     Invalid = true;
660   }
661 
662   // FIXME: It's not clear what should happen if multiple declarations of a
663   // deduction guide have different explicitness. For now at least we simply
664   // reject any case where the explicitness changes.
665   auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
666   if (NewGuide && NewGuide->isExplicitSpecified() !=
667                       cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
668     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
669       << NewGuide->isExplicitSpecified();
670     Diag(Old->getLocation(), diag::note_previous_declaration);
671   }
672 
673   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
674   // argument expression, that declaration shall be a definition and shall be
675   // the only declaration of the function or function template in the
676   // translation unit.
677   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
678       functionDeclHasDefaultArgument(Old)) {
679     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
680     Diag(Old->getLocation(), diag::note_previous_declaration);
681     Invalid = true;
682   }
683 
684   return Invalid;
685 }
686 
687 NamedDecl *
688 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
689                                    MultiTemplateParamsArg TemplateParamLists) {
690   assert(D.isDecompositionDeclarator());
691   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
692 
693   // The syntax only allows a decomposition declarator as a simple-declaration,
694   // a for-range-declaration, or a condition in Clang, but we parse it in more
695   // cases than that.
696   if (!D.mayHaveDecompositionDeclarator()) {
697     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
698       << Decomp.getSourceRange();
699     return nullptr;
700   }
701 
702   if (!TemplateParamLists.empty()) {
703     // FIXME: There's no rule against this, but there are also no rules that
704     // would actually make it usable, so we reject it for now.
705     Diag(TemplateParamLists.front()->getTemplateLoc(),
706          diag::err_decomp_decl_template);
707     return nullptr;
708   }
709 
710   Diag(Decomp.getLSquareLoc(),
711        !getLangOpts().CPlusPlus17
712            ? diag::ext_decomp_decl
713            : D.getContext() == DeclaratorContext::ConditionContext
714                  ? diag::ext_decomp_decl_cond
715                  : diag::warn_cxx14_compat_decomp_decl)
716       << Decomp.getSourceRange();
717 
718   // The semantic context is always just the current context.
719   DeclContext *const DC = CurContext;
720 
721   // C++1z [dcl.dcl]/8:
722   //   The decl-specifier-seq shall contain only the type-specifier auto
723   //   and cv-qualifiers.
724   auto &DS = D.getDeclSpec();
725   {
726     SmallVector<StringRef, 8> BadSpecifiers;
727     SmallVector<SourceLocation, 8> BadSpecifierLocs;
728     if (auto SCS = DS.getStorageClassSpec()) {
729       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
730       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
731     }
732     if (auto TSCS = DS.getThreadStorageClassSpec()) {
733       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
734       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
735     }
736     if (DS.isConstexprSpecified()) {
737       BadSpecifiers.push_back("constexpr");
738       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
739     }
740     if (DS.isInlineSpecified()) {
741       BadSpecifiers.push_back("inline");
742       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
743     }
744     if (!BadSpecifiers.empty()) {
745       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
746       Err << (int)BadSpecifiers.size()
747           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
748       // Don't add FixItHints to remove the specifiers; we do still respect
749       // them when building the underlying variable.
750       for (auto Loc : BadSpecifierLocs)
751         Err << SourceRange(Loc, Loc);
752     }
753     // We can't recover from it being declared as a typedef.
754     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
755       return nullptr;
756   }
757 
758   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
759   QualType R = TInfo->getType();
760 
761   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
762                                       UPPC_DeclarationType))
763     D.setInvalidType();
764 
765   // The syntax only allows a single ref-qualifier prior to the decomposition
766   // declarator. No other declarator chunks are permitted. Also check the type
767   // specifier here.
768   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
769       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
770       (D.getNumTypeObjects() == 1 &&
771        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
772     Diag(Decomp.getLSquareLoc(),
773          (D.hasGroupingParens() ||
774           (D.getNumTypeObjects() &&
775            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
776              ? diag::err_decomp_decl_parens
777              : diag::err_decomp_decl_type)
778         << R;
779 
780     // In most cases, there's no actual problem with an explicitly-specified
781     // type, but a function type won't work here, and ActOnVariableDeclarator
782     // shouldn't be called for such a type.
783     if (R->isFunctionType())
784       D.setInvalidType();
785   }
786 
787   // Build the BindingDecls.
788   SmallVector<BindingDecl*, 8> Bindings;
789 
790   // Build the BindingDecls.
791   for (auto &B : D.getDecompositionDeclarator().bindings()) {
792     // Check for name conflicts.
793     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
794     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
795                           ForVisibleRedeclaration);
796     LookupName(Previous, S,
797                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
798 
799     // It's not permitted to shadow a template parameter name.
800     if (Previous.isSingleResult() &&
801         Previous.getFoundDecl()->isTemplateParameter()) {
802       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
803                                       Previous.getFoundDecl());
804       Previous.clear();
805     }
806 
807     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
808                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
809     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
810                          /*AllowInlineNamespace*/false);
811     if (!Previous.empty()) {
812       auto *Old = Previous.getRepresentativeDecl();
813       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
814       Diag(Old->getLocation(), diag::note_previous_definition);
815     }
816 
817     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
818     PushOnScopeChains(BD, S, true);
819     Bindings.push_back(BD);
820     ParsingInitForAutoVars.insert(BD);
821   }
822 
823   // There are no prior lookup results for the variable itself, because it
824   // is unnamed.
825   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
826                                Decomp.getLSquareLoc());
827   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
828                         ForVisibleRedeclaration);
829 
830   // Build the variable that holds the non-decomposed object.
831   bool AddToScope = true;
832   NamedDecl *New =
833       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
834                               MultiTemplateParamsArg(), AddToScope, Bindings);
835   if (AddToScope) {
836     S->AddDecl(New);
837     CurContext->addHiddenDecl(New);
838   }
839 
840   if (isInOpenMPDeclareTargetContext())
841     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
842 
843   return New;
844 }
845 
846 static bool checkSimpleDecomposition(
847     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
848     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
849     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
850   if ((int64_t)Bindings.size() != NumElems) {
851     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
852         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
853         << (NumElems < Bindings.size());
854     return true;
855   }
856 
857   unsigned I = 0;
858   for (auto *B : Bindings) {
859     SourceLocation Loc = B->getLocation();
860     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
861     if (E.isInvalid())
862       return true;
863     E = GetInit(Loc, E.get(), I++);
864     if (E.isInvalid())
865       return true;
866     B->setBinding(ElemType, E.get());
867   }
868 
869   return false;
870 }
871 
872 static bool checkArrayLikeDecomposition(Sema &S,
873                                         ArrayRef<BindingDecl *> Bindings,
874                                         ValueDecl *Src, QualType DecompType,
875                                         const llvm::APSInt &NumElems,
876                                         QualType ElemType) {
877   return checkSimpleDecomposition(
878       S, Bindings, Src, DecompType, NumElems, ElemType,
879       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
880         ExprResult E = S.ActOnIntegerConstant(Loc, I);
881         if (E.isInvalid())
882           return ExprError();
883         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
884       });
885 }
886 
887 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
888                                     ValueDecl *Src, QualType DecompType,
889                                     const ConstantArrayType *CAT) {
890   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
891                                      llvm::APSInt(CAT->getSize()),
892                                      CAT->getElementType());
893 }
894 
895 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
896                                      ValueDecl *Src, QualType DecompType,
897                                      const VectorType *VT) {
898   return checkArrayLikeDecomposition(
899       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
900       S.Context.getQualifiedType(VT->getElementType(),
901                                  DecompType.getQualifiers()));
902 }
903 
904 static bool checkComplexDecomposition(Sema &S,
905                                       ArrayRef<BindingDecl *> Bindings,
906                                       ValueDecl *Src, QualType DecompType,
907                                       const ComplexType *CT) {
908   return checkSimpleDecomposition(
909       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
910       S.Context.getQualifiedType(CT->getElementType(),
911                                  DecompType.getQualifiers()),
912       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
913         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
914       });
915 }
916 
917 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
918                                      TemplateArgumentListInfo &Args) {
919   SmallString<128> SS;
920   llvm::raw_svector_ostream OS(SS);
921   bool First = true;
922   for (auto &Arg : Args.arguments()) {
923     if (!First)
924       OS << ", ";
925     Arg.getArgument().print(PrintingPolicy, OS);
926     First = false;
927   }
928   return OS.str();
929 }
930 
931 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
932                                      SourceLocation Loc, StringRef Trait,
933                                      TemplateArgumentListInfo &Args,
934                                      unsigned DiagID) {
935   auto DiagnoseMissing = [&] {
936     if (DiagID)
937       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
938                                                Args);
939     return true;
940   };
941 
942   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
943   NamespaceDecl *Std = S.getStdNamespace();
944   if (!Std)
945     return DiagnoseMissing();
946 
947   // Look up the trait itself, within namespace std. We can diagnose various
948   // problems with this lookup even if we've been asked to not diagnose a
949   // missing specialization, because this can only fail if the user has been
950   // declaring their own names in namespace std or we don't support the
951   // standard library implementation in use.
952   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
953                       Loc, Sema::LookupOrdinaryName);
954   if (!S.LookupQualifiedName(Result, Std))
955     return DiagnoseMissing();
956   if (Result.isAmbiguous())
957     return true;
958 
959   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
960   if (!TraitTD) {
961     Result.suppressDiagnostics();
962     NamedDecl *Found = *Result.begin();
963     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
964     S.Diag(Found->getLocation(), diag::note_declared_at);
965     return true;
966   }
967 
968   // Build the template-id.
969   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
970   if (TraitTy.isNull())
971     return true;
972   if (!S.isCompleteType(Loc, TraitTy)) {
973     if (DiagID)
974       S.RequireCompleteType(
975           Loc, TraitTy, DiagID,
976           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
977     return true;
978   }
979 
980   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
981   assert(RD && "specialization of class template is not a class?");
982 
983   // Look up the member of the trait type.
984   S.LookupQualifiedName(TraitMemberLookup, RD);
985   return TraitMemberLookup.isAmbiguous();
986 }
987 
988 static TemplateArgumentLoc
989 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
990                                    uint64_t I) {
991   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
992   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
993 }
994 
995 static TemplateArgumentLoc
996 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
997   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
998 }
999 
1000 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1001 
1002 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1003                                llvm::APSInt &Size) {
1004   EnterExpressionEvaluationContext ContextRAII(
1005       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1006 
1007   DeclarationName Value = S.PP.getIdentifierInfo("value");
1008   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1009 
1010   // Form template argument list for tuple_size<T>.
1011   TemplateArgumentListInfo Args(Loc, Loc);
1012   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1013 
1014   // If there's no tuple_size specialization, it's not tuple-like.
1015   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1016     return IsTupleLike::NotTupleLike;
1017 
1018   // If we get this far, we've committed to the tuple interpretation, but
1019   // we can still fail if there actually isn't a usable ::value.
1020 
1021   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1022     LookupResult &R;
1023     TemplateArgumentListInfo &Args;
1024     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1025         : R(R), Args(Args) {}
1026     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1027       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1028           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1029     }
1030   } Diagnoser(R, Args);
1031 
1032   if (R.empty()) {
1033     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1034     return IsTupleLike::Error;
1035   }
1036 
1037   ExprResult E =
1038       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1039   if (E.isInvalid())
1040     return IsTupleLike::Error;
1041 
1042   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1043   if (E.isInvalid())
1044     return IsTupleLike::Error;
1045 
1046   return IsTupleLike::TupleLike;
1047 }
1048 
1049 /// \return std::tuple_element<I, T>::type.
1050 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1051                                         unsigned I, QualType T) {
1052   // Form template argument list for tuple_element<I, T>.
1053   TemplateArgumentListInfo Args(Loc, Loc);
1054   Args.addArgument(
1055       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1056   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1057 
1058   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1059   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1060   if (lookupStdTypeTraitMember(
1061           S, R, Loc, "tuple_element", Args,
1062           diag::err_decomp_decl_std_tuple_element_not_specialized))
1063     return QualType();
1064 
1065   auto *TD = R.getAsSingle<TypeDecl>();
1066   if (!TD) {
1067     R.suppressDiagnostics();
1068     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1069       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1070     if (!R.empty())
1071       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1072     return QualType();
1073   }
1074 
1075   return S.Context.getTypeDeclType(TD);
1076 }
1077 
1078 namespace {
1079 struct BindingDiagnosticTrap {
1080   Sema &S;
1081   DiagnosticErrorTrap Trap;
1082   BindingDecl *BD;
1083 
1084   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1085       : S(S), Trap(S.Diags), BD(BD) {}
1086   ~BindingDiagnosticTrap() {
1087     if (Trap.hasErrorOccurred())
1088       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1089   }
1090 };
1091 }
1092 
1093 static bool checkTupleLikeDecomposition(Sema &S,
1094                                         ArrayRef<BindingDecl *> Bindings,
1095                                         VarDecl *Src, QualType DecompType,
1096                                         const llvm::APSInt &TupleSize) {
1097   if ((int64_t)Bindings.size() != TupleSize) {
1098     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1099         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1100         << (TupleSize < Bindings.size());
1101     return true;
1102   }
1103 
1104   if (Bindings.empty())
1105     return false;
1106 
1107   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1108 
1109   // [dcl.decomp]p3:
1110   //   The unqualified-id get is looked up in the scope of E by class member
1111   //   access lookup
1112   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1113   bool UseMemberGet = false;
1114   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1115     if (auto *RD = DecompType->getAsCXXRecordDecl())
1116       S.LookupQualifiedName(MemberGet, RD);
1117     if (MemberGet.isAmbiguous())
1118       return true;
1119     UseMemberGet = !MemberGet.empty();
1120     S.FilterAcceptableTemplateNames(MemberGet);
1121   }
1122 
1123   unsigned I = 0;
1124   for (auto *B : Bindings) {
1125     BindingDiagnosticTrap Trap(S, B);
1126     SourceLocation Loc = B->getLocation();
1127 
1128     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1129     if (E.isInvalid())
1130       return true;
1131 
1132     //   e is an lvalue if the type of the entity is an lvalue reference and
1133     //   an xvalue otherwise
1134     if (!Src->getType()->isLValueReferenceType())
1135       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1136                                    E.get(), nullptr, VK_XValue);
1137 
1138     TemplateArgumentListInfo Args(Loc, Loc);
1139     Args.addArgument(
1140         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1141 
1142     if (UseMemberGet) {
1143       //   if [lookup of member get] finds at least one declaration, the
1144       //   initializer is e.get<i-1>().
1145       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1146                                      CXXScopeSpec(), SourceLocation(), nullptr,
1147                                      MemberGet, &Args, nullptr);
1148       if (E.isInvalid())
1149         return true;
1150 
1151       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1152     } else {
1153       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1154       //   in the associated namespaces.
1155       Expr *Get = UnresolvedLookupExpr::Create(
1156           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1157           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1158           UnresolvedSetIterator(), UnresolvedSetIterator());
1159 
1160       Expr *Arg = E.get();
1161       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1162     }
1163     if (E.isInvalid())
1164       return true;
1165     Expr *Init = E.get();
1166 
1167     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1168     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1169     if (T.isNull())
1170       return true;
1171 
1172     //   each vi is a variable of type "reference to T" initialized with the
1173     //   initializer, where the reference is an lvalue reference if the
1174     //   initializer is an lvalue and an rvalue reference otherwise
1175     QualType RefType =
1176         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1177     if (RefType.isNull())
1178       return true;
1179     auto *RefVD = VarDecl::Create(
1180         S.Context, Src->getDeclContext(), Loc, Loc,
1181         B->getDeclName().getAsIdentifierInfo(), RefType,
1182         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1183     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1184     RefVD->setTSCSpec(Src->getTSCSpec());
1185     RefVD->setImplicit();
1186     if (Src->isInlineSpecified())
1187       RefVD->setInlineSpecified();
1188     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1189 
1190     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1191     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1192     InitializationSequence Seq(S, Entity, Kind, Init);
1193     E = Seq.Perform(S, Entity, Kind, Init);
1194     if (E.isInvalid())
1195       return true;
1196     E = S.ActOnFinishFullExpr(E.get(), Loc);
1197     if (E.isInvalid())
1198       return true;
1199     RefVD->setInit(E.get());
1200     RefVD->checkInitIsICE();
1201 
1202     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1203                                    DeclarationNameInfo(B->getDeclName(), Loc),
1204                                    RefVD);
1205     if (E.isInvalid())
1206       return true;
1207 
1208     B->setBinding(T, E.get());
1209     I++;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 /// Find the base class to decompose in a built-in decomposition of a class type.
1216 /// This base class search is, unfortunately, not quite like any other that we
1217 /// perform anywhere else in C++.
1218 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1219                                                       SourceLocation Loc,
1220                                                       const CXXRecordDecl *RD,
1221                                                       CXXCastPath &BasePath) {
1222   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1223                           CXXBasePath &Path) {
1224     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1225   };
1226 
1227   const CXXRecordDecl *ClassWithFields = nullptr;
1228   if (RD->hasDirectFields())
1229     // [dcl.decomp]p4:
1230     //   Otherwise, all of E's non-static data members shall be public direct
1231     //   members of E ...
1232     ClassWithFields = RD;
1233   else {
1234     //   ... or of ...
1235     CXXBasePaths Paths;
1236     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1237     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1238       // If no classes have fields, just decompose RD itself. (This will work
1239       // if and only if zero bindings were provided.)
1240       return RD;
1241     }
1242 
1243     CXXBasePath *BestPath = nullptr;
1244     for (auto &P : Paths) {
1245       if (!BestPath)
1246         BestPath = &P;
1247       else if (!S.Context.hasSameType(P.back().Base->getType(),
1248                                       BestPath->back().Base->getType())) {
1249         //   ... the same ...
1250         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1251           << false << RD << BestPath->back().Base->getType()
1252           << P.back().Base->getType();
1253         return nullptr;
1254       } else if (P.Access < BestPath->Access) {
1255         BestPath = &P;
1256       }
1257     }
1258 
1259     //   ... unambiguous ...
1260     QualType BaseType = BestPath->back().Base->getType();
1261     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1262       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1263         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1264       return nullptr;
1265     }
1266 
1267     //   ... public base class of E.
1268     if (BestPath->Access != AS_public) {
1269       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1270         << RD << BaseType;
1271       for (auto &BS : *BestPath) {
1272         if (BS.Base->getAccessSpecifier() != AS_public) {
1273           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1274             << (BS.Base->getAccessSpecifier() == AS_protected)
1275             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1276           break;
1277         }
1278       }
1279       return nullptr;
1280     }
1281 
1282     ClassWithFields = BaseType->getAsCXXRecordDecl();
1283     S.BuildBasePathArray(Paths, BasePath);
1284   }
1285 
1286   // The above search did not check whether the selected class itself has base
1287   // classes with fields, so check that now.
1288   CXXBasePaths Paths;
1289   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1290     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1291       << (ClassWithFields == RD) << RD << ClassWithFields
1292       << Paths.front().back().Base->getType();
1293     return nullptr;
1294   }
1295 
1296   return ClassWithFields;
1297 }
1298 
1299 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1300                                      ValueDecl *Src, QualType DecompType,
1301                                      const CXXRecordDecl *RD) {
1302   CXXCastPath BasePath;
1303   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1304   if (!RD)
1305     return true;
1306   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1307                                                  DecompType.getQualifiers());
1308 
1309   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1310     unsigned NumFields =
1311         std::count_if(RD->field_begin(), RD->field_end(),
1312                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1313     assert(Bindings.size() != NumFields);
1314     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1315         << DecompType << (unsigned)Bindings.size() << NumFields
1316         << (NumFields < Bindings.size());
1317     return true;
1318   };
1319 
1320   //   all of E's non-static data members shall be public [...] members,
1321   //   E shall not have an anonymous union member, ...
1322   unsigned I = 0;
1323   for (auto *FD : RD->fields()) {
1324     if (FD->isUnnamedBitfield())
1325       continue;
1326 
1327     if (FD->isAnonymousStructOrUnion()) {
1328       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1329         << DecompType << FD->getType()->isUnionType();
1330       S.Diag(FD->getLocation(), diag::note_declared_at);
1331       return true;
1332     }
1333 
1334     // We have a real field to bind.
1335     if (I >= Bindings.size())
1336       return DiagnoseBadNumberOfBindings();
1337     auto *B = Bindings[I++];
1338 
1339     SourceLocation Loc = B->getLocation();
1340     if (FD->getAccess() != AS_public) {
1341       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1342 
1343       // Determine whether the access specifier was explicit.
1344       bool Implicit = true;
1345       for (const auto *D : RD->decls()) {
1346         if (declaresSameEntity(D, FD))
1347           break;
1348         if (isa<AccessSpecDecl>(D)) {
1349           Implicit = false;
1350           break;
1351         }
1352       }
1353 
1354       S.Diag(FD->getLocation(), diag::note_access_natural)
1355         << (FD->getAccess() == AS_protected) << Implicit;
1356       return true;
1357     }
1358 
1359     // Initialize the binding to Src.FD.
1360     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1361     if (E.isInvalid())
1362       return true;
1363     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1364                             VK_LValue, &BasePath);
1365     if (E.isInvalid())
1366       return true;
1367     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1368                                   CXXScopeSpec(), FD,
1369                                   DeclAccessPair::make(FD, FD->getAccess()),
1370                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1371     if (E.isInvalid())
1372       return true;
1373 
1374     // If the type of the member is T, the referenced type is cv T, where cv is
1375     // the cv-qualification of the decomposition expression.
1376     //
1377     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1378     // 'const' to the type of the field.
1379     Qualifiers Q = DecompType.getQualifiers();
1380     if (FD->isMutable())
1381       Q.removeConst();
1382     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1383   }
1384 
1385   if (I != Bindings.size())
1386     return DiagnoseBadNumberOfBindings();
1387 
1388   return false;
1389 }
1390 
1391 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1392   QualType DecompType = DD->getType();
1393 
1394   // If the type of the decomposition is dependent, then so is the type of
1395   // each binding.
1396   if (DecompType->isDependentType()) {
1397     for (auto *B : DD->bindings())
1398       B->setType(Context.DependentTy);
1399     return;
1400   }
1401 
1402   DecompType = DecompType.getNonReferenceType();
1403   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1404 
1405   // C++1z [dcl.decomp]/2:
1406   //   If E is an array type [...]
1407   // As an extension, we also support decomposition of built-in complex and
1408   // vector types.
1409   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1410     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1411       DD->setInvalidDecl();
1412     return;
1413   }
1414   if (auto *VT = DecompType->getAs<VectorType>()) {
1415     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1416       DD->setInvalidDecl();
1417     return;
1418   }
1419   if (auto *CT = DecompType->getAs<ComplexType>()) {
1420     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1421       DD->setInvalidDecl();
1422     return;
1423   }
1424 
1425   // C++1z [dcl.decomp]/3:
1426   //   if the expression std::tuple_size<E>::value is a well-formed integral
1427   //   constant expression, [...]
1428   llvm::APSInt TupleSize(32);
1429   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1430   case IsTupleLike::Error:
1431     DD->setInvalidDecl();
1432     return;
1433 
1434   case IsTupleLike::TupleLike:
1435     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1436       DD->setInvalidDecl();
1437     return;
1438 
1439   case IsTupleLike::NotTupleLike:
1440     break;
1441   }
1442 
1443   // C++1z [dcl.dcl]/8:
1444   //   [E shall be of array or non-union class type]
1445   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1446   if (!RD || RD->isUnion()) {
1447     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1448         << DD << !RD << DecompType;
1449     DD->setInvalidDecl();
1450     return;
1451   }
1452 
1453   // C++1z [dcl.decomp]/4:
1454   //   all of E's non-static data members shall be [...] direct members of
1455   //   E or of the same unambiguous public base class of E, ...
1456   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1457     DD->setInvalidDecl();
1458 }
1459 
1460 /// Merge the exception specifications of two variable declarations.
1461 ///
1462 /// This is called when there's a redeclaration of a VarDecl. The function
1463 /// checks if the redeclaration might have an exception specification and
1464 /// validates compatibility and merges the specs if necessary.
1465 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1466   // Shortcut if exceptions are disabled.
1467   if (!getLangOpts().CXXExceptions)
1468     return;
1469 
1470   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1471          "Should only be called if types are otherwise the same.");
1472 
1473   QualType NewType = New->getType();
1474   QualType OldType = Old->getType();
1475 
1476   // We're only interested in pointers and references to functions, as well
1477   // as pointers to member functions.
1478   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1479     NewType = R->getPointeeType();
1480     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1481   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1482     NewType = P->getPointeeType();
1483     OldType = OldType->getAs<PointerType>()->getPointeeType();
1484   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1485     NewType = M->getPointeeType();
1486     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1487   }
1488 
1489   if (!NewType->isFunctionProtoType())
1490     return;
1491 
1492   // There's lots of special cases for functions. For function pointers, system
1493   // libraries are hopefully not as broken so that we don't need these
1494   // workarounds.
1495   if (CheckEquivalentExceptionSpec(
1496         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1497         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1498     New->setInvalidDecl();
1499   }
1500 }
1501 
1502 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1503 /// function declaration are well-formed according to C++
1504 /// [dcl.fct.default].
1505 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1506   unsigned NumParams = FD->getNumParams();
1507   unsigned p;
1508 
1509   // Find first parameter with a default argument
1510   for (p = 0; p < NumParams; ++p) {
1511     ParmVarDecl *Param = FD->getParamDecl(p);
1512     if (Param->hasDefaultArg())
1513       break;
1514   }
1515 
1516   // C++11 [dcl.fct.default]p4:
1517   //   In a given function declaration, each parameter subsequent to a parameter
1518   //   with a default argument shall have a default argument supplied in this or
1519   //   a previous declaration or shall be a function parameter pack. A default
1520   //   argument shall not be redefined by a later declaration (not even to the
1521   //   same value).
1522   unsigned LastMissingDefaultArg = 0;
1523   for (; p < NumParams; ++p) {
1524     ParmVarDecl *Param = FD->getParamDecl(p);
1525     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1526       if (Param->isInvalidDecl())
1527         /* We already complained about this parameter. */;
1528       else if (Param->getIdentifier())
1529         Diag(Param->getLocation(),
1530              diag::err_param_default_argument_missing_name)
1531           << Param->getIdentifier();
1532       else
1533         Diag(Param->getLocation(),
1534              diag::err_param_default_argument_missing);
1535 
1536       LastMissingDefaultArg = p;
1537     }
1538   }
1539 
1540   if (LastMissingDefaultArg > 0) {
1541     // Some default arguments were missing. Clear out all of the
1542     // default arguments up to (and including) the last missing
1543     // default argument, so that we leave the function parameters
1544     // in a semantically valid state.
1545     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1546       ParmVarDecl *Param = FD->getParamDecl(p);
1547       if (Param->hasDefaultArg()) {
1548         Param->setDefaultArg(nullptr);
1549       }
1550     }
1551   }
1552 }
1553 
1554 // CheckConstexprParameterTypes - Check whether a function's parameter types
1555 // are all literal types. If so, return true. If not, produce a suitable
1556 // diagnostic and return false.
1557 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1558                                          const FunctionDecl *FD) {
1559   unsigned ArgIndex = 0;
1560   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1561   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1562                                               e = FT->param_type_end();
1563        i != e; ++i, ++ArgIndex) {
1564     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1565     SourceLocation ParamLoc = PD->getLocation();
1566     if (!(*i)->isDependentType() &&
1567         SemaRef.RequireLiteralType(ParamLoc, *i,
1568                                    diag::err_constexpr_non_literal_param,
1569                                    ArgIndex+1, PD->getSourceRange(),
1570                                    isa<CXXConstructorDecl>(FD)))
1571       return false;
1572   }
1573   return true;
1574 }
1575 
1576 /// Get diagnostic %select index for tag kind for
1577 /// record diagnostic message.
1578 /// WARNING: Indexes apply to particular diagnostics only!
1579 ///
1580 /// \returns diagnostic %select index.
1581 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1582   switch (Tag) {
1583   case TTK_Struct: return 0;
1584   case TTK_Interface: return 1;
1585   case TTK_Class:  return 2;
1586   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1587   }
1588 }
1589 
1590 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1591 // the requirements of a constexpr function definition or a constexpr
1592 // constructor definition. If so, return true. If not, produce appropriate
1593 // diagnostics and return false.
1594 //
1595 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1596 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1597   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1598   if (MD && MD->isInstance()) {
1599     // C++11 [dcl.constexpr]p4:
1600     //  The definition of a constexpr constructor shall satisfy the following
1601     //  constraints:
1602     //  - the class shall not have any virtual base classes;
1603     const CXXRecordDecl *RD = MD->getParent();
1604     if (RD->getNumVBases()) {
1605       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1606         << isa<CXXConstructorDecl>(NewFD)
1607         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1608       for (const auto &I : RD->vbases())
1609         Diag(I.getLocStart(),
1610              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1611       return false;
1612     }
1613   }
1614 
1615   if (!isa<CXXConstructorDecl>(NewFD)) {
1616     // C++11 [dcl.constexpr]p3:
1617     //  The definition of a constexpr function shall satisfy the following
1618     //  constraints:
1619     // - it shall not be virtual;
1620     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1621     if (Method && Method->isVirtual()) {
1622       Method = Method->getCanonicalDecl();
1623       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1624 
1625       // If it's not obvious why this function is virtual, find an overridden
1626       // function which uses the 'virtual' keyword.
1627       const CXXMethodDecl *WrittenVirtual = Method;
1628       while (!WrittenVirtual->isVirtualAsWritten())
1629         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1630       if (WrittenVirtual != Method)
1631         Diag(WrittenVirtual->getLocation(),
1632              diag::note_overridden_virtual_function);
1633       return false;
1634     }
1635 
1636     // - its return type shall be a literal type;
1637     QualType RT = NewFD->getReturnType();
1638     if (!RT->isDependentType() &&
1639         RequireLiteralType(NewFD->getLocation(), RT,
1640                            diag::err_constexpr_non_literal_return))
1641       return false;
1642   }
1643 
1644   // - each of its parameter types shall be a literal type;
1645   if (!CheckConstexprParameterTypes(*this, NewFD))
1646     return false;
1647 
1648   return true;
1649 }
1650 
1651 /// Check the given declaration statement is legal within a constexpr function
1652 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1653 ///
1654 /// \return true if the body is OK (maybe only as an extension), false if we
1655 ///         have diagnosed a problem.
1656 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1657                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1658   // C++11 [dcl.constexpr]p3 and p4:
1659   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1660   //  contain only
1661   for (const auto *DclIt : DS->decls()) {
1662     switch (DclIt->getKind()) {
1663     case Decl::StaticAssert:
1664     case Decl::Using:
1665     case Decl::UsingShadow:
1666     case Decl::UsingDirective:
1667     case Decl::UnresolvedUsingTypename:
1668     case Decl::UnresolvedUsingValue:
1669       //   - static_assert-declarations
1670       //   - using-declarations,
1671       //   - using-directives,
1672       continue;
1673 
1674     case Decl::Typedef:
1675     case Decl::TypeAlias: {
1676       //   - typedef declarations and alias-declarations that do not define
1677       //     classes or enumerations,
1678       const auto *TN = cast<TypedefNameDecl>(DclIt);
1679       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1680         // Don't allow variably-modified types in constexpr functions.
1681         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1682         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1683           << TL.getSourceRange() << TL.getType()
1684           << isa<CXXConstructorDecl>(Dcl);
1685         return false;
1686       }
1687       continue;
1688     }
1689 
1690     case Decl::Enum:
1691     case Decl::CXXRecord:
1692       // C++1y allows types to be defined, not just declared.
1693       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1694         SemaRef.Diag(DS->getLocStart(),
1695                      SemaRef.getLangOpts().CPlusPlus14
1696                        ? diag::warn_cxx11_compat_constexpr_type_definition
1697                        : diag::ext_constexpr_type_definition)
1698           << isa<CXXConstructorDecl>(Dcl);
1699       continue;
1700 
1701     case Decl::EnumConstant:
1702     case Decl::IndirectField:
1703     case Decl::ParmVar:
1704       // These can only appear with other declarations which are banned in
1705       // C++11 and permitted in C++1y, so ignore them.
1706       continue;
1707 
1708     case Decl::Var:
1709     case Decl::Decomposition: {
1710       // C++1y [dcl.constexpr]p3 allows anything except:
1711       //   a definition of a variable of non-literal type or of static or
1712       //   thread storage duration or for which no initialization is performed.
1713       const auto *VD = cast<VarDecl>(DclIt);
1714       if (VD->isThisDeclarationADefinition()) {
1715         if (VD->isStaticLocal()) {
1716           SemaRef.Diag(VD->getLocation(),
1717                        diag::err_constexpr_local_var_static)
1718             << isa<CXXConstructorDecl>(Dcl)
1719             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1720           return false;
1721         }
1722         if (!VD->getType()->isDependentType() &&
1723             SemaRef.RequireLiteralType(
1724               VD->getLocation(), VD->getType(),
1725               diag::err_constexpr_local_var_non_literal_type,
1726               isa<CXXConstructorDecl>(Dcl)))
1727           return false;
1728         if (!VD->getType()->isDependentType() &&
1729             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1730           SemaRef.Diag(VD->getLocation(),
1731                        diag::err_constexpr_local_var_no_init)
1732             << isa<CXXConstructorDecl>(Dcl);
1733           return false;
1734         }
1735       }
1736       SemaRef.Diag(VD->getLocation(),
1737                    SemaRef.getLangOpts().CPlusPlus14
1738                     ? diag::warn_cxx11_compat_constexpr_local_var
1739                     : diag::ext_constexpr_local_var)
1740         << isa<CXXConstructorDecl>(Dcl);
1741       continue;
1742     }
1743 
1744     case Decl::NamespaceAlias:
1745     case Decl::Function:
1746       // These are disallowed in C++11 and permitted in C++1y. Allow them
1747       // everywhere as an extension.
1748       if (!Cxx1yLoc.isValid())
1749         Cxx1yLoc = DS->getLocStart();
1750       continue;
1751 
1752     default:
1753       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1754         << isa<CXXConstructorDecl>(Dcl);
1755       return false;
1756     }
1757   }
1758 
1759   return true;
1760 }
1761 
1762 /// Check that the given field is initialized within a constexpr constructor.
1763 ///
1764 /// \param Dcl The constexpr constructor being checked.
1765 /// \param Field The field being checked. This may be a member of an anonymous
1766 ///        struct or union nested within the class being checked.
1767 /// \param Inits All declarations, including anonymous struct/union members and
1768 ///        indirect members, for which any initialization was provided.
1769 /// \param Diagnosed Set to true if an error is produced.
1770 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1771                                           const FunctionDecl *Dcl,
1772                                           FieldDecl *Field,
1773                                           llvm::SmallSet<Decl*, 16> &Inits,
1774                                           bool &Diagnosed) {
1775   if (Field->isInvalidDecl())
1776     return;
1777 
1778   if (Field->isUnnamedBitfield())
1779     return;
1780 
1781   // Anonymous unions with no variant members and empty anonymous structs do not
1782   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1783   // indirect fields don't need initializing.
1784   if (Field->isAnonymousStructOrUnion() &&
1785       (Field->getType()->isUnionType()
1786            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1787            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1788     return;
1789 
1790   if (!Inits.count(Field)) {
1791     if (!Diagnosed) {
1792       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1793       Diagnosed = true;
1794     }
1795     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1796   } else if (Field->isAnonymousStructOrUnion()) {
1797     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1798     for (auto *I : RD->fields())
1799       // If an anonymous union contains an anonymous struct of which any member
1800       // is initialized, all members must be initialized.
1801       if (!RD->isUnion() || Inits.count(I))
1802         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1803   }
1804 }
1805 
1806 /// Check the provided statement is allowed in a constexpr function
1807 /// definition.
1808 static bool
1809 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1810                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1811                            SourceLocation &Cxx1yLoc) {
1812   // - its function-body shall be [...] a compound-statement that contains only
1813   switch (S->getStmtClass()) {
1814   case Stmt::NullStmtClass:
1815     //   - null statements,
1816     return true;
1817 
1818   case Stmt::DeclStmtClass:
1819     //   - static_assert-declarations
1820     //   - using-declarations,
1821     //   - using-directives,
1822     //   - typedef declarations and alias-declarations that do not define
1823     //     classes or enumerations,
1824     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1825       return false;
1826     return true;
1827 
1828   case Stmt::ReturnStmtClass:
1829     //   - and exactly one return statement;
1830     if (isa<CXXConstructorDecl>(Dcl)) {
1831       // C++1y allows return statements in constexpr constructors.
1832       if (!Cxx1yLoc.isValid())
1833         Cxx1yLoc = S->getLocStart();
1834       return true;
1835     }
1836 
1837     ReturnStmts.push_back(S->getLocStart());
1838     return true;
1839 
1840   case Stmt::CompoundStmtClass: {
1841     // C++1y allows compound-statements.
1842     if (!Cxx1yLoc.isValid())
1843       Cxx1yLoc = S->getLocStart();
1844 
1845     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1846     for (auto *BodyIt : CompStmt->body()) {
1847       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1848                                       Cxx1yLoc))
1849         return false;
1850     }
1851     return true;
1852   }
1853 
1854   case Stmt::AttributedStmtClass:
1855     if (!Cxx1yLoc.isValid())
1856       Cxx1yLoc = S->getLocStart();
1857     return true;
1858 
1859   case Stmt::IfStmtClass: {
1860     // C++1y allows if-statements.
1861     if (!Cxx1yLoc.isValid())
1862       Cxx1yLoc = S->getLocStart();
1863 
1864     IfStmt *If = cast<IfStmt>(S);
1865     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1866                                     Cxx1yLoc))
1867       return false;
1868     if (If->getElse() &&
1869         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1870                                     Cxx1yLoc))
1871       return false;
1872     return true;
1873   }
1874 
1875   case Stmt::WhileStmtClass:
1876   case Stmt::DoStmtClass:
1877   case Stmt::ForStmtClass:
1878   case Stmt::CXXForRangeStmtClass:
1879   case Stmt::ContinueStmtClass:
1880     // C++1y allows all of these. We don't allow them as extensions in C++11,
1881     // because they don't make sense without variable mutation.
1882     if (!SemaRef.getLangOpts().CPlusPlus14)
1883       break;
1884     if (!Cxx1yLoc.isValid())
1885       Cxx1yLoc = S->getLocStart();
1886     for (Stmt *SubStmt : S->children())
1887       if (SubStmt &&
1888           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1889                                       Cxx1yLoc))
1890         return false;
1891     return true;
1892 
1893   case Stmt::SwitchStmtClass:
1894   case Stmt::CaseStmtClass:
1895   case Stmt::DefaultStmtClass:
1896   case Stmt::BreakStmtClass:
1897     // C++1y allows switch-statements, and since they don't need variable
1898     // mutation, we can reasonably allow them in C++11 as an extension.
1899     if (!Cxx1yLoc.isValid())
1900       Cxx1yLoc = S->getLocStart();
1901     for (Stmt *SubStmt : S->children())
1902       if (SubStmt &&
1903           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1904                                       Cxx1yLoc))
1905         return false;
1906     return true;
1907 
1908   default:
1909     if (!isa<Expr>(S))
1910       break;
1911 
1912     // C++1y allows expression-statements.
1913     if (!Cxx1yLoc.isValid())
1914       Cxx1yLoc = S->getLocStart();
1915     return true;
1916   }
1917 
1918   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1919     << isa<CXXConstructorDecl>(Dcl);
1920   return false;
1921 }
1922 
1923 /// Check the body for the given constexpr function declaration only contains
1924 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1925 ///
1926 /// \return true if the body is OK, false if we have diagnosed a problem.
1927 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1928   if (isa<CXXTryStmt>(Body)) {
1929     // C++11 [dcl.constexpr]p3:
1930     //  The definition of a constexpr function shall satisfy the following
1931     //  constraints: [...]
1932     // - its function-body shall be = delete, = default, or a
1933     //   compound-statement
1934     //
1935     // C++11 [dcl.constexpr]p4:
1936     //  In the definition of a constexpr constructor, [...]
1937     // - its function-body shall not be a function-try-block;
1938     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1939       << isa<CXXConstructorDecl>(Dcl);
1940     return false;
1941   }
1942 
1943   SmallVector<SourceLocation, 4> ReturnStmts;
1944 
1945   // - its function-body shall be [...] a compound-statement that contains only
1946   //   [... list of cases ...]
1947   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1948   SourceLocation Cxx1yLoc;
1949   for (auto *BodyIt : CompBody->body()) {
1950     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1951       return false;
1952   }
1953 
1954   if (Cxx1yLoc.isValid())
1955     Diag(Cxx1yLoc,
1956          getLangOpts().CPlusPlus14
1957            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1958            : diag::ext_constexpr_body_invalid_stmt)
1959       << isa<CXXConstructorDecl>(Dcl);
1960 
1961   if (const CXXConstructorDecl *Constructor
1962         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1963     const CXXRecordDecl *RD = Constructor->getParent();
1964     // DR1359:
1965     // - every non-variant non-static data member and base class sub-object
1966     //   shall be initialized;
1967     // DR1460:
1968     // - if the class is a union having variant members, exactly one of them
1969     //   shall be initialized;
1970     if (RD->isUnion()) {
1971       if (Constructor->getNumCtorInitializers() == 0 &&
1972           RD->hasVariantMembers()) {
1973         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1974         return false;
1975       }
1976     } else if (!Constructor->isDependentContext() &&
1977                !Constructor->isDelegatingConstructor()) {
1978       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1979 
1980       // Skip detailed checking if we have enough initializers, and we would
1981       // allow at most one initializer per member.
1982       bool AnyAnonStructUnionMembers = false;
1983       unsigned Fields = 0;
1984       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1985            E = RD->field_end(); I != E; ++I, ++Fields) {
1986         if (I->isAnonymousStructOrUnion()) {
1987           AnyAnonStructUnionMembers = true;
1988           break;
1989         }
1990       }
1991       // DR1460:
1992       // - if the class is a union-like class, but is not a union, for each of
1993       //   its anonymous union members having variant members, exactly one of
1994       //   them shall be initialized;
1995       if (AnyAnonStructUnionMembers ||
1996           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1997         // Check initialization of non-static data members. Base classes are
1998         // always initialized so do not need to be checked. Dependent bases
1999         // might not have initializers in the member initializer list.
2000         llvm::SmallSet<Decl*, 16> Inits;
2001         for (const auto *I: Constructor->inits()) {
2002           if (FieldDecl *FD = I->getMember())
2003             Inits.insert(FD);
2004           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2005             Inits.insert(ID->chain_begin(), ID->chain_end());
2006         }
2007 
2008         bool Diagnosed = false;
2009         for (auto *I : RD->fields())
2010           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2011         if (Diagnosed)
2012           return false;
2013       }
2014     }
2015   } else {
2016     if (ReturnStmts.empty()) {
2017       // C++1y doesn't require constexpr functions to contain a 'return'
2018       // statement. We still do, unless the return type might be void, because
2019       // otherwise if there's no return statement, the function cannot
2020       // be used in a core constant expression.
2021       bool OK = getLangOpts().CPlusPlus14 &&
2022                 (Dcl->getReturnType()->isVoidType() ||
2023                  Dcl->getReturnType()->isDependentType());
2024       Diag(Dcl->getLocation(),
2025            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2026               : diag::err_constexpr_body_no_return);
2027       if (!OK)
2028         return false;
2029     } else if (ReturnStmts.size() > 1) {
2030       Diag(ReturnStmts.back(),
2031            getLangOpts().CPlusPlus14
2032              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2033              : diag::ext_constexpr_body_multiple_return);
2034       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2035         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2036     }
2037   }
2038 
2039   // C++11 [dcl.constexpr]p5:
2040   //   if no function argument values exist such that the function invocation
2041   //   substitution would produce a constant expression, the program is
2042   //   ill-formed; no diagnostic required.
2043   // C++11 [dcl.constexpr]p3:
2044   //   - every constructor call and implicit conversion used in initializing the
2045   //     return value shall be one of those allowed in a constant expression.
2046   // C++11 [dcl.constexpr]p4:
2047   //   - every constructor involved in initializing non-static data members and
2048   //     base class sub-objects shall be a constexpr constructor.
2049   SmallVector<PartialDiagnosticAt, 8> Diags;
2050   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2051     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2052       << isa<CXXConstructorDecl>(Dcl);
2053     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2054       Diag(Diags[I].first, Diags[I].second);
2055     // Don't return false here: we allow this for compatibility in
2056     // system headers.
2057   }
2058 
2059   return true;
2060 }
2061 
2062 /// isCurrentClassName - Determine whether the identifier II is the
2063 /// name of the class type currently being defined. In the case of
2064 /// nested classes, this will only return true if II is the name of
2065 /// the innermost class.
2066 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2067                               const CXXScopeSpec *SS) {
2068   assert(getLangOpts().CPlusPlus && "No class names in C!");
2069 
2070   CXXRecordDecl *CurDecl;
2071   if (SS && SS->isSet() && !SS->isInvalid()) {
2072     DeclContext *DC = computeDeclContext(*SS, true);
2073     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2074   } else
2075     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2076 
2077   if (CurDecl && CurDecl->getIdentifier())
2078     return &II == CurDecl->getIdentifier();
2079   return false;
2080 }
2081 
2082 /// Determine whether the identifier II is a typo for the name of
2083 /// the class type currently being defined. If so, update it to the identifier
2084 /// that should have been used.
2085 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2086   assert(getLangOpts().CPlusPlus && "No class names in C!");
2087 
2088   if (!getLangOpts().SpellChecking)
2089     return false;
2090 
2091   CXXRecordDecl *CurDecl;
2092   if (SS && SS->isSet() && !SS->isInvalid()) {
2093     DeclContext *DC = computeDeclContext(*SS, true);
2094     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2095   } else
2096     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2097 
2098   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2099       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2100           < II->getLength()) {
2101     II = CurDecl->getIdentifier();
2102     return true;
2103   }
2104 
2105   return false;
2106 }
2107 
2108 /// Determine whether the given class is a base class of the given
2109 /// class, including looking at dependent bases.
2110 static bool findCircularInheritance(const CXXRecordDecl *Class,
2111                                     const CXXRecordDecl *Current) {
2112   SmallVector<const CXXRecordDecl*, 8> Queue;
2113 
2114   Class = Class->getCanonicalDecl();
2115   while (true) {
2116     for (const auto &I : Current->bases()) {
2117       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2118       if (!Base)
2119         continue;
2120 
2121       Base = Base->getDefinition();
2122       if (!Base)
2123         continue;
2124 
2125       if (Base->getCanonicalDecl() == Class)
2126         return true;
2127 
2128       Queue.push_back(Base);
2129     }
2130 
2131     if (Queue.empty())
2132       return false;
2133 
2134     Current = Queue.pop_back_val();
2135   }
2136 
2137   return false;
2138 }
2139 
2140 /// Check the validity of a C++ base class specifier.
2141 ///
2142 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2143 /// and returns NULL otherwise.
2144 CXXBaseSpecifier *
2145 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2146                          SourceRange SpecifierRange,
2147                          bool Virtual, AccessSpecifier Access,
2148                          TypeSourceInfo *TInfo,
2149                          SourceLocation EllipsisLoc) {
2150   QualType BaseType = TInfo->getType();
2151 
2152   // C++ [class.union]p1:
2153   //   A union shall not have base classes.
2154   if (Class->isUnion()) {
2155     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2156       << SpecifierRange;
2157     return nullptr;
2158   }
2159 
2160   if (EllipsisLoc.isValid() &&
2161       !TInfo->getType()->containsUnexpandedParameterPack()) {
2162     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2163       << TInfo->getTypeLoc().getSourceRange();
2164     EllipsisLoc = SourceLocation();
2165   }
2166 
2167   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2168 
2169   if (BaseType->isDependentType()) {
2170     // Make sure that we don't have circular inheritance among our dependent
2171     // bases. For non-dependent bases, the check for completeness below handles
2172     // this.
2173     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2174       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2175           ((BaseDecl = BaseDecl->getDefinition()) &&
2176            findCircularInheritance(Class, BaseDecl))) {
2177         Diag(BaseLoc, diag::err_circular_inheritance)
2178           << BaseType << Context.getTypeDeclType(Class);
2179 
2180         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2181           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2182             << BaseType;
2183 
2184         return nullptr;
2185       }
2186     }
2187 
2188     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2189                                           Class->getTagKind() == TTK_Class,
2190                                           Access, TInfo, EllipsisLoc);
2191   }
2192 
2193   // Base specifiers must be record types.
2194   if (!BaseType->isRecordType()) {
2195     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2196     return nullptr;
2197   }
2198 
2199   // C++ [class.union]p1:
2200   //   A union shall not be used as a base class.
2201   if (BaseType->isUnionType()) {
2202     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2203     return nullptr;
2204   }
2205 
2206   // For the MS ABI, propagate DLL attributes to base class templates.
2207   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2208     if (Attr *ClassAttr = getDLLAttr(Class)) {
2209       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2210               BaseType->getAsCXXRecordDecl())) {
2211         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2212                                             BaseLoc);
2213       }
2214     }
2215   }
2216 
2217   // C++ [class.derived]p2:
2218   //   The class-name in a base-specifier shall not be an incompletely
2219   //   defined class.
2220   if (RequireCompleteType(BaseLoc, BaseType,
2221                           diag::err_incomplete_base_class, SpecifierRange)) {
2222     Class->setInvalidDecl();
2223     return nullptr;
2224   }
2225 
2226   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2227   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2228   assert(BaseDecl && "Record type has no declaration");
2229   BaseDecl = BaseDecl->getDefinition();
2230   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2231   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2232   assert(CXXBaseDecl && "Base type is not a C++ type");
2233 
2234   // A class which contains a flexible array member is not suitable for use as a
2235   // base class:
2236   //   - If the layout determines that a base comes before another base,
2237   //     the flexible array member would index into the subsequent base.
2238   //   - If the layout determines that base comes before the derived class,
2239   //     the flexible array member would index into the derived class.
2240   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2241     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2242       << CXXBaseDecl->getDeclName();
2243     return nullptr;
2244   }
2245 
2246   // C++ [class]p3:
2247   //   If a class is marked final and it appears as a base-type-specifier in
2248   //   base-clause, the program is ill-formed.
2249   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2250     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2251       << CXXBaseDecl->getDeclName()
2252       << FA->isSpelledAsSealed();
2253     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2254         << CXXBaseDecl->getDeclName() << FA->getRange();
2255     return nullptr;
2256   }
2257 
2258   if (BaseDecl->isInvalidDecl())
2259     Class->setInvalidDecl();
2260 
2261   // Create the base specifier.
2262   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2263                                         Class->getTagKind() == TTK_Class,
2264                                         Access, TInfo, EllipsisLoc);
2265 }
2266 
2267 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2268 /// one entry in the base class list of a class specifier, for
2269 /// example:
2270 ///    class foo : public bar, virtual private baz {
2271 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2272 BaseResult
2273 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2274                          ParsedAttributes &Attributes,
2275                          bool Virtual, AccessSpecifier Access,
2276                          ParsedType basetype, SourceLocation BaseLoc,
2277                          SourceLocation EllipsisLoc) {
2278   if (!classdecl)
2279     return true;
2280 
2281   AdjustDeclIfTemplate(classdecl);
2282   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2283   if (!Class)
2284     return true;
2285 
2286   // We haven't yet attached the base specifiers.
2287   Class->setIsParsingBaseSpecifiers();
2288 
2289   // We do not support any C++11 attributes on base-specifiers yet.
2290   // Diagnose any attributes we see.
2291   if (!Attributes.empty()) {
2292     for (AttributeList *Attr = Attributes.getList(); Attr;
2293          Attr = Attr->getNext()) {
2294       if (Attr->isInvalid() ||
2295           Attr->getKind() == AttributeList::IgnoredAttribute)
2296         continue;
2297       Diag(Attr->getLoc(),
2298            Attr->getKind() == AttributeList::UnknownAttribute
2299              ? diag::warn_unknown_attribute_ignored
2300              : diag::err_base_specifier_attribute)
2301         << Attr->getName();
2302     }
2303   }
2304 
2305   TypeSourceInfo *TInfo = nullptr;
2306   GetTypeFromParser(basetype, &TInfo);
2307 
2308   if (EllipsisLoc.isInvalid() &&
2309       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2310                                       UPPC_BaseType))
2311     return true;
2312 
2313   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2314                                                       Virtual, Access, TInfo,
2315                                                       EllipsisLoc))
2316     return BaseSpec;
2317   else
2318     Class->setInvalidDecl();
2319 
2320   return true;
2321 }
2322 
2323 /// Use small set to collect indirect bases.  As this is only used
2324 /// locally, there's no need to abstract the small size parameter.
2325 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2326 
2327 /// Recursively add the bases of Type.  Don't add Type itself.
2328 static void
2329 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2330                   const QualType &Type)
2331 {
2332   // Even though the incoming type is a base, it might not be
2333   // a class -- it could be a template parm, for instance.
2334   if (auto Rec = Type->getAs<RecordType>()) {
2335     auto Decl = Rec->getAsCXXRecordDecl();
2336 
2337     // Iterate over its bases.
2338     for (const auto &BaseSpec : Decl->bases()) {
2339       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2340         .getUnqualifiedType();
2341       if (Set.insert(Base).second)
2342         // If we've not already seen it, recurse.
2343         NoteIndirectBases(Context, Set, Base);
2344     }
2345   }
2346 }
2347 
2348 /// Performs the actual work of attaching the given base class
2349 /// specifiers to a C++ class.
2350 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2351                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2352  if (Bases.empty())
2353     return false;
2354 
2355   // Used to keep track of which base types we have already seen, so
2356   // that we can properly diagnose redundant direct base types. Note
2357   // that the key is always the unqualified canonical type of the base
2358   // class.
2359   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2360 
2361   // Used to track indirect bases so we can see if a direct base is
2362   // ambiguous.
2363   IndirectBaseSet IndirectBaseTypes;
2364 
2365   // Copy non-redundant base specifiers into permanent storage.
2366   unsigned NumGoodBases = 0;
2367   bool Invalid = false;
2368   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2369     QualType NewBaseType
2370       = Context.getCanonicalType(Bases[idx]->getType());
2371     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2372 
2373     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2374     if (KnownBase) {
2375       // C++ [class.mi]p3:
2376       //   A class shall not be specified as a direct base class of a
2377       //   derived class more than once.
2378       Diag(Bases[idx]->getLocStart(),
2379            diag::err_duplicate_base_class)
2380         << KnownBase->getType()
2381         << Bases[idx]->getSourceRange();
2382 
2383       // Delete the duplicate base class specifier; we're going to
2384       // overwrite its pointer later.
2385       Context.Deallocate(Bases[idx]);
2386 
2387       Invalid = true;
2388     } else {
2389       // Okay, add this new base class.
2390       KnownBase = Bases[idx];
2391       Bases[NumGoodBases++] = Bases[idx];
2392 
2393       // Note this base's direct & indirect bases, if there could be ambiguity.
2394       if (Bases.size() > 1)
2395         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2396 
2397       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2398         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2399         if (Class->isInterface() &&
2400               (!RD->isInterfaceLike() ||
2401                KnownBase->getAccessSpecifier() != AS_public)) {
2402           // The Microsoft extension __interface does not permit bases that
2403           // are not themselves public interfaces.
2404           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2405             << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2406             << RD->getSourceRange();
2407           Invalid = true;
2408         }
2409         if (RD->hasAttr<WeakAttr>())
2410           Class->addAttr(WeakAttr::CreateImplicit(Context));
2411       }
2412     }
2413   }
2414 
2415   // Attach the remaining base class specifiers to the derived class.
2416   Class->setBases(Bases.data(), NumGoodBases);
2417 
2418   // Check that the only base classes that are duplicate are virtual.
2419   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2420     // Check whether this direct base is inaccessible due to ambiguity.
2421     QualType BaseType = Bases[idx]->getType();
2422 
2423     // Skip all dependent types in templates being used as base specifiers.
2424     // Checks below assume that the base specifier is a CXXRecord.
2425     if (BaseType->isDependentType())
2426       continue;
2427 
2428     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2429       .getUnqualifiedType();
2430 
2431     if (IndirectBaseTypes.count(CanonicalBase)) {
2432       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2433                          /*DetectVirtual=*/true);
2434       bool found
2435         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2436       assert(found);
2437       (void)found;
2438 
2439       if (Paths.isAmbiguous(CanonicalBase))
2440         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2441           << BaseType << getAmbiguousPathsDisplayString(Paths)
2442           << Bases[idx]->getSourceRange();
2443       else
2444         assert(Bases[idx]->isVirtual());
2445     }
2446 
2447     // Delete the base class specifier, since its data has been copied
2448     // into the CXXRecordDecl.
2449     Context.Deallocate(Bases[idx]);
2450   }
2451 
2452   return Invalid;
2453 }
2454 
2455 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2456 /// class, after checking whether there are any duplicate base
2457 /// classes.
2458 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2459                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2460   if (!ClassDecl || Bases.empty())
2461     return;
2462 
2463   AdjustDeclIfTemplate(ClassDecl);
2464   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2465 }
2466 
2467 /// Determine whether the type \p Derived is a C++ class that is
2468 /// derived from the type \p Base.
2469 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2470   if (!getLangOpts().CPlusPlus)
2471     return false;
2472 
2473   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2474   if (!DerivedRD)
2475     return false;
2476 
2477   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2478   if (!BaseRD)
2479     return false;
2480 
2481   // If either the base or the derived type is invalid, don't try to
2482   // check whether one is derived from the other.
2483   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2484     return false;
2485 
2486   // FIXME: In a modules build, do we need the entire path to be visible for us
2487   // to be able to use the inheritance relationship?
2488   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2489     return false;
2490 
2491   return DerivedRD->isDerivedFrom(BaseRD);
2492 }
2493 
2494 /// Determine whether the type \p Derived is a C++ class that is
2495 /// derived from the type \p Base.
2496 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2497                          CXXBasePaths &Paths) {
2498   if (!getLangOpts().CPlusPlus)
2499     return false;
2500 
2501   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2502   if (!DerivedRD)
2503     return false;
2504 
2505   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2506   if (!BaseRD)
2507     return false;
2508 
2509   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2510     return false;
2511 
2512   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2513 }
2514 
2515 static void BuildBasePathArray(const CXXBasePath &Path,
2516                                CXXCastPath &BasePathArray) {
2517   // We first go backward and check if we have a virtual base.
2518   // FIXME: It would be better if CXXBasePath had the base specifier for
2519   // the nearest virtual base.
2520   unsigned Start = 0;
2521   for (unsigned I = Path.size(); I != 0; --I) {
2522     if (Path[I - 1].Base->isVirtual()) {
2523       Start = I - 1;
2524       break;
2525     }
2526   }
2527 
2528   // Now add all bases.
2529   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2530     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2531 }
2532 
2533 
2534 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2535                               CXXCastPath &BasePathArray) {
2536   assert(BasePathArray.empty() && "Base path array must be empty!");
2537   assert(Paths.isRecordingPaths() && "Must record paths!");
2538   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2539 }
2540 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2541 /// conversion (where Derived and Base are class types) is
2542 /// well-formed, meaning that the conversion is unambiguous (and
2543 /// that all of the base classes are accessible). Returns true
2544 /// and emits a diagnostic if the code is ill-formed, returns false
2545 /// otherwise. Loc is the location where this routine should point to
2546 /// if there is an error, and Range is the source range to highlight
2547 /// if there is an error.
2548 ///
2549 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2550 /// diagnostic for the respective type of error will be suppressed, but the
2551 /// check for ill-formed code will still be performed.
2552 bool
2553 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2554                                    unsigned InaccessibleBaseID,
2555                                    unsigned AmbigiousBaseConvID,
2556                                    SourceLocation Loc, SourceRange Range,
2557                                    DeclarationName Name,
2558                                    CXXCastPath *BasePath,
2559                                    bool IgnoreAccess) {
2560   // First, determine whether the path from Derived to Base is
2561   // ambiguous. This is slightly more expensive than checking whether
2562   // the Derived to Base conversion exists, because here we need to
2563   // explore multiple paths to determine if there is an ambiguity.
2564   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2565                      /*DetectVirtual=*/false);
2566   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2567   if (!DerivationOkay)
2568     return true;
2569 
2570   const CXXBasePath *Path = nullptr;
2571   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2572     Path = &Paths.front();
2573 
2574   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2575   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2576   // user to access such bases.
2577   if (!Path && getLangOpts().MSVCCompat) {
2578     for (const CXXBasePath &PossiblePath : Paths) {
2579       if (PossiblePath.size() == 1) {
2580         Path = &PossiblePath;
2581         if (AmbigiousBaseConvID)
2582           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2583               << Base << Derived << Range;
2584         break;
2585       }
2586     }
2587   }
2588 
2589   if (Path) {
2590     if (!IgnoreAccess) {
2591       // Check that the base class can be accessed.
2592       switch (
2593           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2594       case AR_inaccessible:
2595         return true;
2596       case AR_accessible:
2597       case AR_dependent:
2598       case AR_delayed:
2599         break;
2600       }
2601     }
2602 
2603     // Build a base path if necessary.
2604     if (BasePath)
2605       ::BuildBasePathArray(*Path, *BasePath);
2606     return false;
2607   }
2608 
2609   if (AmbigiousBaseConvID) {
2610     // We know that the derived-to-base conversion is ambiguous, and
2611     // we're going to produce a diagnostic. Perform the derived-to-base
2612     // search just one more time to compute all of the possible paths so
2613     // that we can print them out. This is more expensive than any of
2614     // the previous derived-to-base checks we've done, but at this point
2615     // performance isn't as much of an issue.
2616     Paths.clear();
2617     Paths.setRecordingPaths(true);
2618     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2619     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2620     (void)StillOkay;
2621 
2622     // Build up a textual representation of the ambiguous paths, e.g.,
2623     // D -> B -> A, that will be used to illustrate the ambiguous
2624     // conversions in the diagnostic. We only print one of the paths
2625     // to each base class subobject.
2626     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2627 
2628     Diag(Loc, AmbigiousBaseConvID)
2629     << Derived << Base << PathDisplayStr << Range << Name;
2630   }
2631   return true;
2632 }
2633 
2634 bool
2635 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2636                                    SourceLocation Loc, SourceRange Range,
2637                                    CXXCastPath *BasePath,
2638                                    bool IgnoreAccess) {
2639   return CheckDerivedToBaseConversion(
2640       Derived, Base, diag::err_upcast_to_inaccessible_base,
2641       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2642       BasePath, IgnoreAccess);
2643 }
2644 
2645 
2646 /// Builds a string representing ambiguous paths from a
2647 /// specific derived class to different subobjects of the same base
2648 /// class.
2649 ///
2650 /// This function builds a string that can be used in error messages
2651 /// to show the different paths that one can take through the
2652 /// inheritance hierarchy to go from the derived class to different
2653 /// subobjects of a base class. The result looks something like this:
2654 /// @code
2655 /// struct D -> struct B -> struct A
2656 /// struct D -> struct C -> struct A
2657 /// @endcode
2658 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2659   std::string PathDisplayStr;
2660   std::set<unsigned> DisplayedPaths;
2661   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2662        Path != Paths.end(); ++Path) {
2663     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2664       // We haven't displayed a path to this particular base
2665       // class subobject yet.
2666       PathDisplayStr += "\n    ";
2667       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2668       for (CXXBasePath::const_iterator Element = Path->begin();
2669            Element != Path->end(); ++Element)
2670         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2671     }
2672   }
2673 
2674   return PathDisplayStr;
2675 }
2676 
2677 //===----------------------------------------------------------------------===//
2678 // C++ class member Handling
2679 //===----------------------------------------------------------------------===//
2680 
2681 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2682 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2683                                 SourceLocation ASLoc,
2684                                 SourceLocation ColonLoc,
2685                                 AttributeList *Attrs) {
2686   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2687   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2688                                                   ASLoc, ColonLoc);
2689   CurContext->addHiddenDecl(ASDecl);
2690   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2691 }
2692 
2693 /// CheckOverrideControl - Check C++11 override control semantics.
2694 void Sema::CheckOverrideControl(NamedDecl *D) {
2695   if (D->isInvalidDecl())
2696     return;
2697 
2698   // We only care about "override" and "final" declarations.
2699   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2700     return;
2701 
2702   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2703 
2704   // We can't check dependent instance methods.
2705   if (MD && MD->isInstance() &&
2706       (MD->getParent()->hasAnyDependentBases() ||
2707        MD->getType()->isDependentType()))
2708     return;
2709 
2710   if (MD && !MD->isVirtual()) {
2711     // If we have a non-virtual method, check if if hides a virtual method.
2712     // (In that case, it's most likely the method has the wrong type.)
2713     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2714     FindHiddenVirtualMethods(MD, OverloadedMethods);
2715 
2716     if (!OverloadedMethods.empty()) {
2717       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2718         Diag(OA->getLocation(),
2719              diag::override_keyword_hides_virtual_member_function)
2720           << "override" << (OverloadedMethods.size() > 1);
2721       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2722         Diag(FA->getLocation(),
2723              diag::override_keyword_hides_virtual_member_function)
2724           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2725           << (OverloadedMethods.size() > 1);
2726       }
2727       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2728       MD->setInvalidDecl();
2729       return;
2730     }
2731     // Fall through into the general case diagnostic.
2732     // FIXME: We might want to attempt typo correction here.
2733   }
2734 
2735   if (!MD || !MD->isVirtual()) {
2736     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2737       Diag(OA->getLocation(),
2738            diag::override_keyword_only_allowed_on_virtual_member_functions)
2739         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2740       D->dropAttr<OverrideAttr>();
2741     }
2742     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2743       Diag(FA->getLocation(),
2744            diag::override_keyword_only_allowed_on_virtual_member_functions)
2745         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2746         << FixItHint::CreateRemoval(FA->getLocation());
2747       D->dropAttr<FinalAttr>();
2748     }
2749     return;
2750   }
2751 
2752   // C++11 [class.virtual]p5:
2753   //   If a function is marked with the virt-specifier override and
2754   //   does not override a member function of a base class, the program is
2755   //   ill-formed.
2756   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2757   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2758     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2759       << MD->getDeclName();
2760 }
2761 
2762 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2763   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2764     return;
2765   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2766   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2767     return;
2768 
2769   SourceLocation Loc = MD->getLocation();
2770   SourceLocation SpellingLoc = Loc;
2771   if (getSourceManager().isMacroArgExpansion(Loc))
2772     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2773   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2774   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2775       return;
2776 
2777   if (MD->size_overridden_methods() > 0) {
2778     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2779                           ? diag::warn_destructor_marked_not_override_overriding
2780                           : diag::warn_function_marked_not_override_overriding;
2781     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2782     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2783     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2784   }
2785 }
2786 
2787 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2788 /// function overrides a virtual member function marked 'final', according to
2789 /// C++11 [class.virtual]p4.
2790 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2791                                                   const CXXMethodDecl *Old) {
2792   FinalAttr *FA = Old->getAttr<FinalAttr>();
2793   if (!FA)
2794     return false;
2795 
2796   Diag(New->getLocation(), diag::err_final_function_overridden)
2797     << New->getDeclName()
2798     << FA->isSpelledAsSealed();
2799   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2800   return true;
2801 }
2802 
2803 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2804   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2805   // FIXME: Destruction of ObjC lifetime types has side-effects.
2806   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2807     return !RD->isCompleteDefinition() ||
2808            !RD->hasTrivialDefaultConstructor() ||
2809            !RD->hasTrivialDestructor();
2810   return false;
2811 }
2812 
2813 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2814   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2815     if (it->isDeclspecPropertyAttribute())
2816       return it;
2817   return nullptr;
2818 }
2819 
2820 // Check if there is a field shadowing.
2821 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2822                                       DeclarationName FieldName,
2823                                       const CXXRecordDecl *RD) {
2824   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2825     return;
2826 
2827   // To record a shadowed field in a base
2828   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2829   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2830                            CXXBasePath &Path) {
2831     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2832     // Record an ambiguous path directly
2833     if (Bases.find(Base) != Bases.end())
2834       return true;
2835     for (const auto Field : Base->lookup(FieldName)) {
2836       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2837           Field->getAccess() != AS_private) {
2838         assert(Field->getAccess() != AS_none);
2839         assert(Bases.find(Base) == Bases.end());
2840         Bases[Base] = Field;
2841         return true;
2842       }
2843     }
2844     return false;
2845   };
2846 
2847   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2848                      /*DetectVirtual=*/true);
2849   if (!RD->lookupInBases(FieldShadowed, Paths))
2850     return;
2851 
2852   for (const auto &P : Paths) {
2853     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2854     auto It = Bases.find(Base);
2855     // Skip duplicated bases
2856     if (It == Bases.end())
2857       continue;
2858     auto BaseField = It->second;
2859     assert(BaseField->getAccess() != AS_private);
2860     if (AS_none !=
2861         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2862       Diag(Loc, diag::warn_shadow_field)
2863         << FieldName << RD << Base;
2864       Diag(BaseField->getLocation(), diag::note_shadow_field);
2865       Bases.erase(It);
2866     }
2867   }
2868 }
2869 
2870 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2871 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2872 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2873 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2874 /// present (but parsing it has been deferred).
2875 NamedDecl *
2876 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2877                                MultiTemplateParamsArg TemplateParameterLists,
2878                                Expr *BW, const VirtSpecifiers &VS,
2879                                InClassInitStyle InitStyle) {
2880   const DeclSpec &DS = D.getDeclSpec();
2881   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2882   DeclarationName Name = NameInfo.getName();
2883   SourceLocation Loc = NameInfo.getLoc();
2884 
2885   // For anonymous bitfields, the location should point to the type.
2886   if (Loc.isInvalid())
2887     Loc = D.getLocStart();
2888 
2889   Expr *BitWidth = static_cast<Expr*>(BW);
2890 
2891   assert(isa<CXXRecordDecl>(CurContext));
2892   assert(!DS.isFriendSpecified());
2893 
2894   bool isFunc = D.isDeclarationOfFunction();
2895   AttributeList *MSPropertyAttr =
2896       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2897 
2898   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2899     // The Microsoft extension __interface only permits public member functions
2900     // and prohibits constructors, destructors, operators, non-public member
2901     // functions, static methods and data members.
2902     unsigned InvalidDecl;
2903     bool ShowDeclName = true;
2904     if (!isFunc &&
2905         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2906       InvalidDecl = 0;
2907     else if (!isFunc)
2908       InvalidDecl = 1;
2909     else if (AS != AS_public)
2910       InvalidDecl = 2;
2911     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2912       InvalidDecl = 3;
2913     else switch (Name.getNameKind()) {
2914       case DeclarationName::CXXConstructorName:
2915         InvalidDecl = 4;
2916         ShowDeclName = false;
2917         break;
2918 
2919       case DeclarationName::CXXDestructorName:
2920         InvalidDecl = 5;
2921         ShowDeclName = false;
2922         break;
2923 
2924       case DeclarationName::CXXOperatorName:
2925       case DeclarationName::CXXConversionFunctionName:
2926         InvalidDecl = 6;
2927         break;
2928 
2929       default:
2930         InvalidDecl = 0;
2931         break;
2932     }
2933 
2934     if (InvalidDecl) {
2935       if (ShowDeclName)
2936         Diag(Loc, diag::err_invalid_member_in_interface)
2937           << (InvalidDecl-1) << Name;
2938       else
2939         Diag(Loc, diag::err_invalid_member_in_interface)
2940           << (InvalidDecl-1) << "";
2941       return nullptr;
2942     }
2943   }
2944 
2945   // C++ 9.2p6: A member shall not be declared to have automatic storage
2946   // duration (auto, register) or with the extern storage-class-specifier.
2947   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2948   // data members and cannot be applied to names declared const or static,
2949   // and cannot be applied to reference members.
2950   switch (DS.getStorageClassSpec()) {
2951   case DeclSpec::SCS_unspecified:
2952   case DeclSpec::SCS_typedef:
2953   case DeclSpec::SCS_static:
2954     break;
2955   case DeclSpec::SCS_mutable:
2956     if (isFunc) {
2957       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2958 
2959       // FIXME: It would be nicer if the keyword was ignored only for this
2960       // declarator. Otherwise we could get follow-up errors.
2961       D.getMutableDeclSpec().ClearStorageClassSpecs();
2962     }
2963     break;
2964   default:
2965     Diag(DS.getStorageClassSpecLoc(),
2966          diag::err_storageclass_invalid_for_member);
2967     D.getMutableDeclSpec().ClearStorageClassSpecs();
2968     break;
2969   }
2970 
2971   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2972                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2973                       !isFunc);
2974 
2975   if (DS.isConstexprSpecified() && isInstField) {
2976     SemaDiagnosticBuilder B =
2977         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2978     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2979     if (InitStyle == ICIS_NoInit) {
2980       B << 0 << 0;
2981       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2982         B << FixItHint::CreateRemoval(ConstexprLoc);
2983       else {
2984         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2985         D.getMutableDeclSpec().ClearConstexprSpec();
2986         const char *PrevSpec;
2987         unsigned DiagID;
2988         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2989             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2990         (void)Failed;
2991         assert(!Failed && "Making a constexpr member const shouldn't fail");
2992       }
2993     } else {
2994       B << 1;
2995       const char *PrevSpec;
2996       unsigned DiagID;
2997       if (D.getMutableDeclSpec().SetStorageClassSpec(
2998           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2999           Context.getPrintingPolicy())) {
3000         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3001                "This is the only DeclSpec that should fail to be applied");
3002         B << 1;
3003       } else {
3004         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3005         isInstField = false;
3006       }
3007     }
3008   }
3009 
3010   NamedDecl *Member;
3011   if (isInstField) {
3012     CXXScopeSpec &SS = D.getCXXScopeSpec();
3013 
3014     // Data members must have identifiers for names.
3015     if (!Name.isIdentifier()) {
3016       Diag(Loc, diag::err_bad_variable_name)
3017         << Name;
3018       return nullptr;
3019     }
3020 
3021     IdentifierInfo *II = Name.getAsIdentifierInfo();
3022 
3023     // Member field could not be with "template" keyword.
3024     // So TemplateParameterLists should be empty in this case.
3025     if (TemplateParameterLists.size()) {
3026       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3027       if (TemplateParams->size()) {
3028         // There is no such thing as a member field template.
3029         Diag(D.getIdentifierLoc(), diag::err_template_member)
3030             << II
3031             << SourceRange(TemplateParams->getTemplateLoc(),
3032                 TemplateParams->getRAngleLoc());
3033       } else {
3034         // There is an extraneous 'template<>' for this member.
3035         Diag(TemplateParams->getTemplateLoc(),
3036             diag::err_template_member_noparams)
3037             << II
3038             << SourceRange(TemplateParams->getTemplateLoc(),
3039                 TemplateParams->getRAngleLoc());
3040       }
3041       return nullptr;
3042     }
3043 
3044     if (SS.isSet() && !SS.isInvalid()) {
3045       // The user provided a superfluous scope specifier inside a class
3046       // definition:
3047       //
3048       // class X {
3049       //   int X::member;
3050       // };
3051       if (DeclContext *DC = computeDeclContext(SS, false))
3052         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3053                                      D.getName().getKind() ==
3054                                          UnqualifiedIdKind::IK_TemplateId);
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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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->isZeroLengthBitField(SemaRef.Context))
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   /// 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 /// 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 ReferenceDllExportedMembers(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     // Defined static variables that are members of an exported base
5495     // class must be marked export too.
5496     auto *VD = dyn_cast<VarDecl>(Member);
5497     if (VD && Member->getAttr<DLLExportAttr>() &&
5498         VD->getStorageClass() == SC_Static &&
5499         TSK == TSK_ImplicitInstantiation)
5500       S.MarkVariableReferenced(VD->getLocation(), VD);
5501 
5502     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5503     if (!MD)
5504       continue;
5505 
5506     if (Member->getAttr<DLLExportAttr>()) {
5507       if (MD->isUserProvided()) {
5508         // Instantiate non-default class member functions ...
5509 
5510         // .. except for certain kinds of template specializations.
5511         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5512           continue;
5513 
5514         S.MarkFunctionReferenced(Class->getLocation(), MD);
5515 
5516         // The function will be passed to the consumer when its definition is
5517         // encountered.
5518       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5519                  MD->isCopyAssignmentOperator() ||
5520                  MD->isMoveAssignmentOperator()) {
5521         // Synthesize and instantiate non-trivial implicit methods, explicitly
5522         // defaulted methods, and the copy and move assignment operators. The
5523         // latter are exported even if they are trivial, because the address of
5524         // an operator can be taken and should compare equal across libraries.
5525         DiagnosticErrorTrap Trap(S.Diags);
5526         S.MarkFunctionReferenced(Class->getLocation(), MD);
5527         if (Trap.hasErrorOccurred()) {
5528           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5529               << Class << !S.getLangOpts().CPlusPlus11;
5530           break;
5531         }
5532 
5533         // There is no later point when we will see the definition of this
5534         // function, so pass it to the consumer now.
5535         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5536       }
5537     }
5538   }
5539 }
5540 
5541 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5542                                                         CXXRecordDecl *Class) {
5543   // Only the MS ABI has default constructor closures, so we don't need to do
5544   // this semantic checking anywhere else.
5545   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5546     return;
5547 
5548   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5549   for (Decl *Member : Class->decls()) {
5550     // Look for exported default constructors.
5551     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5552     if (!CD || !CD->isDefaultConstructor())
5553       continue;
5554     auto *Attr = CD->getAttr<DLLExportAttr>();
5555     if (!Attr)
5556       continue;
5557 
5558     // If the class is non-dependent, mark the default arguments as ODR-used so
5559     // that we can properly codegen the constructor closure.
5560     if (!Class->isDependentContext()) {
5561       for (ParmVarDecl *PD : CD->parameters()) {
5562         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5563         S.DiscardCleanupsInEvaluationContext();
5564       }
5565     }
5566 
5567     if (LastExportedDefaultCtor) {
5568       S.Diag(LastExportedDefaultCtor->getLocation(),
5569              diag::err_attribute_dll_ambiguous_default_ctor)
5570           << Class;
5571       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5572           << CD->getDeclName();
5573       return;
5574     }
5575     LastExportedDefaultCtor = CD;
5576   }
5577 }
5578 
5579 /// Check class-level dllimport/dllexport attribute.
5580 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5581   Attr *ClassAttr = getDLLAttr(Class);
5582 
5583   // MSVC inherits DLL attributes to partial class template specializations.
5584   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5585     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5586       if (Attr *TemplateAttr =
5587               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5588         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5589         A->setInherited(true);
5590         ClassAttr = A;
5591       }
5592     }
5593   }
5594 
5595   if (!ClassAttr)
5596     return;
5597 
5598   if (!Class->isExternallyVisible()) {
5599     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5600         << Class << ClassAttr;
5601     return;
5602   }
5603 
5604   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5605       !ClassAttr->isInherited()) {
5606     // Diagnose dll attributes on members of class with dll attribute.
5607     for (Decl *Member : Class->decls()) {
5608       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5609         continue;
5610       InheritableAttr *MemberAttr = getDLLAttr(Member);
5611       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5612         continue;
5613 
5614       Diag(MemberAttr->getLocation(),
5615              diag::err_attribute_dll_member_of_dll_class)
5616           << MemberAttr << ClassAttr;
5617       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5618       Member->setInvalidDecl();
5619     }
5620   }
5621 
5622   if (Class->getDescribedClassTemplate())
5623     // Don't inherit dll attribute until the template is instantiated.
5624     return;
5625 
5626   // The class is either imported or exported.
5627   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5628 
5629   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5630 
5631   // Ignore explicit dllexport on explicit class template instantiation declarations.
5632   if (ClassExported && !ClassAttr->isInherited() &&
5633       TSK == TSK_ExplicitInstantiationDeclaration) {
5634     Class->dropAttr<DLLExportAttr>();
5635     return;
5636   }
5637 
5638   // Force declaration of implicit members so they can inherit the attribute.
5639   ForceDeclarationOfImplicitMembers(Class);
5640 
5641   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5642   // seem to be true in practice?
5643 
5644   for (Decl *Member : Class->decls()) {
5645     VarDecl *VD = dyn_cast<VarDecl>(Member);
5646     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5647 
5648     // Only methods and static fields inherit the attributes.
5649     if (!VD && !MD)
5650       continue;
5651 
5652     if (MD) {
5653       // Don't process deleted methods.
5654       if (MD->isDeleted())
5655         continue;
5656 
5657       if (MD->isInlined()) {
5658         // MinGW does not import or export inline methods.
5659         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5660             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5661           continue;
5662 
5663         // MSVC versions before 2015 don't export the move assignment operators
5664         // and move constructor, so don't attempt to import/export them if
5665         // we have a definition.
5666         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5667         if ((MD->isMoveAssignmentOperator() ||
5668              (Ctor && Ctor->isMoveConstructor())) &&
5669             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5670           continue;
5671 
5672         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5673         // operator is exported anyway.
5674         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5675             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5676           continue;
5677       }
5678     }
5679 
5680     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5681       continue;
5682 
5683     if (!getDLLAttr(Member)) {
5684       auto *NewAttr =
5685           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5686       NewAttr->setInherited(true);
5687       Member->addAttr(NewAttr);
5688 
5689       if (MD) {
5690         // Propagate DLLAttr to friend re-declarations of MD that have already
5691         // been constructed.
5692         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5693              FD = FD->getPreviousDecl()) {
5694           if (FD->getFriendObjectKind() == Decl::FOK_None)
5695             continue;
5696           assert(!getDLLAttr(FD) &&
5697                  "friend re-decl should not already have a DLLAttr");
5698           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5699           NewAttr->setInherited(true);
5700           FD->addAttr(NewAttr);
5701         }
5702       }
5703     }
5704   }
5705 
5706   if (ClassExported)
5707     DelayedDllExportClasses.push_back(Class);
5708 }
5709 
5710 /// Perform propagation of DLL attributes from a derived class to a
5711 /// templated base class for MS compatibility.
5712 void Sema::propagateDLLAttrToBaseClassTemplate(
5713     CXXRecordDecl *Class, Attr *ClassAttr,
5714     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5715   if (getDLLAttr(
5716           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5717     // If the base class template has a DLL attribute, don't try to change it.
5718     return;
5719   }
5720 
5721   auto TSK = BaseTemplateSpec->getSpecializationKind();
5722   if (!getDLLAttr(BaseTemplateSpec) &&
5723       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5724        TSK == TSK_ImplicitInstantiation)) {
5725     // The template hasn't been instantiated yet (or it has, but only as an
5726     // explicit instantiation declaration or implicit instantiation, which means
5727     // we haven't codegenned any members yet), so propagate the attribute.
5728     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5729     NewAttr->setInherited(true);
5730     BaseTemplateSpec->addAttr(NewAttr);
5731 
5732     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5733     // needs to be run again to work see the new attribute. Otherwise this will
5734     // get run whenever the template is instantiated.
5735     if (TSK != TSK_Undeclared)
5736       checkClassLevelDLLAttribute(BaseTemplateSpec);
5737 
5738     return;
5739   }
5740 
5741   if (getDLLAttr(BaseTemplateSpec)) {
5742     // The template has already been specialized or instantiated with an
5743     // attribute, explicitly or through propagation. We should not try to change
5744     // it.
5745     return;
5746   }
5747 
5748   // The template was previously instantiated or explicitly specialized without
5749   // a dll attribute, It's too late for us to add an attribute, so warn that
5750   // this is unsupported.
5751   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5752       << BaseTemplateSpec->isExplicitSpecialization();
5753   Diag(ClassAttr->getLocation(), diag::note_attribute);
5754   if (BaseTemplateSpec->isExplicitSpecialization()) {
5755     Diag(BaseTemplateSpec->getLocation(),
5756            diag::note_template_class_explicit_specialization_was_here)
5757         << BaseTemplateSpec;
5758   } else {
5759     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5760            diag::note_template_class_instantiation_was_here)
5761         << BaseTemplateSpec;
5762   }
5763 }
5764 
5765 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5766                                         SourceLocation DefaultLoc) {
5767   switch (S.getSpecialMember(MD)) {
5768   case Sema::CXXDefaultConstructor:
5769     S.DefineImplicitDefaultConstructor(DefaultLoc,
5770                                        cast<CXXConstructorDecl>(MD));
5771     break;
5772   case Sema::CXXCopyConstructor:
5773     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5774     break;
5775   case Sema::CXXCopyAssignment:
5776     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5777     break;
5778   case Sema::CXXDestructor:
5779     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5780     break;
5781   case Sema::CXXMoveConstructor:
5782     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5783     break;
5784   case Sema::CXXMoveAssignment:
5785     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5786     break;
5787   case Sema::CXXInvalid:
5788     llvm_unreachable("Invalid special member.");
5789   }
5790 }
5791 
5792 /// Determine whether a type would be destructed in the callee if it had a
5793 /// non-trivial destructor. The rules here are based on C++ [class.temporary]p3,
5794 /// which determines whether a struct can be passed to or returned from
5795 /// functions in registers.
5796 static bool paramCanBeDestroyedInCallee(Sema &S, CXXRecordDecl *D,
5797                                         TargetInfo::CallingConvKind CCK) {
5798   if (D->isDependentType() || D->isInvalidDecl())
5799     return false;
5800 
5801   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5802   // The PS4 platform ABI follows the behavior of Clang 3.2.
5803   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5804     return !D->hasNonTrivialDestructorForCall() &&
5805            !D->hasNonTrivialCopyConstructorForCall();
5806 
5807   // Per C++ [class.temporary]p3, the relevant condition is:
5808   //   each copy constructor, move constructor, and destructor of X is
5809   //   either trivial or deleted, and X has at least one non-deleted copy
5810   //   or move constructor
5811   bool HasNonDeletedCopyOrMove = false;
5812 
5813   if (D->needsImplicitCopyConstructor() &&
5814       !D->defaultedCopyConstructorIsDeleted()) {
5815     if (!D->hasTrivialCopyConstructorForCall())
5816       return false;
5817     HasNonDeletedCopyOrMove = true;
5818   }
5819 
5820   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5821       !D->defaultedMoveConstructorIsDeleted()) {
5822     if (!D->hasTrivialMoveConstructorForCall())
5823       return false;
5824     HasNonDeletedCopyOrMove = true;
5825   }
5826 
5827   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5828       !D->hasTrivialDestructorForCall())
5829     return false;
5830 
5831   for (const CXXMethodDecl *MD : D->methods()) {
5832     if (MD->isDeleted())
5833       continue;
5834 
5835     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5836     if (CD && CD->isCopyOrMoveConstructor())
5837       HasNonDeletedCopyOrMove = true;
5838     else if (!isa<CXXDestructorDecl>(MD))
5839       continue;
5840 
5841     if (!MD->isTrivialForCall())
5842       return false;
5843   }
5844 
5845   return HasNonDeletedCopyOrMove;
5846 }
5847 
5848 static RecordDecl::ArgPassingKind
5849 computeArgPassingRestrictions(bool DestroyedInCallee, const CXXRecordDecl *RD,
5850                               TargetInfo::CallingConvKind CCK, Sema &S) {
5851   if (RD->isDependentType() || RD->isInvalidDecl())
5852     return RecordDecl::APK_CanPassInRegs;
5853 
5854   // The param cannot be passed in registers if ArgPassingRestrictions is set to
5855   // APK_CanNeverPassInRegs.
5856   if (RD->getArgPassingRestrictions() == RecordDecl::APK_CanNeverPassInRegs)
5857     return RecordDecl::APK_CanNeverPassInRegs;
5858 
5859   if (CCK != TargetInfo::CCK_MicrosoftX86_64)
5860     return DestroyedInCallee ? RecordDecl::APK_CanPassInRegs
5861                              : RecordDecl::APK_CannotPassInRegs;
5862 
5863   bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5864   bool DtorIsTrivialForCall = false;
5865 
5866   // If a class has at least one non-deleted, trivial copy constructor, it
5867   // is passed according to the C ABI. Otherwise, it is passed indirectly.
5868   //
5869   // Note: This permits classes with non-trivial copy or move ctors to be
5870   // passed in registers, so long as they *also* have a trivial copy ctor,
5871   // which is non-conforming.
5872   if (RD->needsImplicitCopyConstructor()) {
5873     if (!RD->defaultedCopyConstructorIsDeleted()) {
5874       if (RD->hasTrivialCopyConstructor())
5875         CopyCtorIsTrivial = true;
5876       if (RD->hasTrivialCopyConstructorForCall())
5877         CopyCtorIsTrivialForCall = true;
5878     }
5879   } else {
5880     for (const CXXConstructorDecl *CD : RD->ctors()) {
5881       if (CD->isCopyConstructor() && !CD->isDeleted()) {
5882         if (CD->isTrivial())
5883           CopyCtorIsTrivial = true;
5884         if (CD->isTrivialForCall())
5885           CopyCtorIsTrivialForCall = true;
5886       }
5887     }
5888   }
5889 
5890   if (RD->needsImplicitDestructor()) {
5891     if (!RD->defaultedDestructorIsDeleted() &&
5892         RD->hasTrivialDestructorForCall())
5893       DtorIsTrivialForCall = true;
5894   } else if (const auto *D = RD->getDestructor()) {
5895     if (!D->isDeleted() && D->isTrivialForCall())
5896       DtorIsTrivialForCall = true;
5897   }
5898 
5899   // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5900   if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5901     return RecordDecl::APK_CanPassInRegs;
5902 
5903   // If a class has a destructor, we'd really like to pass it indirectly
5904   // because it allows us to elide copies.  Unfortunately, MSVC makes that
5905   // impossible for small types, which it will pass in a single register or
5906   // stack slot. Most objects with dtors are large-ish, so handle that early.
5907   // We can't call out all large objects as being indirect because there are
5908   // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5909   // how we pass large POD types.
5910 
5911   // Note: This permits small classes with nontrivial destructors to be
5912   // passed in registers, which is non-conforming.
5913   if (CopyCtorIsTrivial &&
5914       S.getASTContext().getTypeSize(RD->getTypeForDecl()) <= 64)
5915     return RecordDecl::APK_CanPassInRegs;
5916   return RecordDecl::APK_CannotPassInRegs;
5917 }
5918 
5919 /// Perform semantic checks on a class definition that has been
5920 /// completing, introducing implicitly-declared members, checking for
5921 /// abstract types, etc.
5922 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5923   if (!Record)
5924     return;
5925 
5926   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5927     AbstractUsageInfo Info(*this, Record);
5928     CheckAbstractClassUsage(Info, Record);
5929   }
5930 
5931   // If this is not an aggregate type and has no user-declared constructor,
5932   // complain about any non-static data members of reference or const scalar
5933   // type, since they will never get initializers.
5934   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5935       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5936       !Record->isLambda()) {
5937     bool Complained = false;
5938     for (const auto *F : Record->fields()) {
5939       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5940         continue;
5941 
5942       if (F->getType()->isReferenceType() ||
5943           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5944         if (!Complained) {
5945           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5946             << Record->getTagKind() << Record;
5947           Complained = true;
5948         }
5949 
5950         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5951           << F->getType()->isReferenceType()
5952           << F->getDeclName();
5953       }
5954     }
5955   }
5956 
5957   if (Record->getIdentifier()) {
5958     // C++ [class.mem]p13:
5959     //   If T is the name of a class, then each of the following shall have a
5960     //   name different from T:
5961     //     - every member of every anonymous union that is a member of class T.
5962     //
5963     // C++ [class.mem]p14:
5964     //   In addition, if class T has a user-declared constructor (12.1), every
5965     //   non-static data member of class T shall have a name different from T.
5966     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5967     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5968          ++I) {
5969       NamedDecl *D = *I;
5970       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5971           isa<IndirectFieldDecl>(D)) {
5972         Diag(D->getLocation(), diag::err_member_name_of_class)
5973           << D->getDeclName();
5974         break;
5975       }
5976     }
5977   }
5978 
5979   // Warn if the class has virtual methods but non-virtual public destructor.
5980   if (Record->isPolymorphic() && !Record->isDependentType()) {
5981     CXXDestructorDecl *dtor = Record->getDestructor();
5982     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5983         !Record->hasAttr<FinalAttr>())
5984       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5985            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5986   }
5987 
5988   if (Record->isAbstract()) {
5989     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5990       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5991         << FA->isSpelledAsSealed();
5992       DiagnoseAbstractType(Record);
5993     }
5994   }
5995 
5996   // Set HasTrivialSpecialMemberForCall if the record has attribute
5997   // "trivial_abi".
5998   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
5999 
6000   if (HasTrivialABI)
6001     Record->setHasTrivialSpecialMemberForCall();
6002 
6003   bool HasMethodWithOverrideControl = false,
6004        HasOverridingMethodWithoutOverrideControl = false;
6005   if (!Record->isDependentType()) {
6006     for (auto *M : Record->methods()) {
6007       // See if a method overloads virtual methods in a base
6008       // class without overriding any.
6009       if (!M->isStatic())
6010         DiagnoseHiddenVirtualMethods(M);
6011       if (M->hasAttr<OverrideAttr>())
6012         HasMethodWithOverrideControl = true;
6013       else if (M->size_overridden_methods() > 0)
6014         HasOverridingMethodWithoutOverrideControl = true;
6015       // Check whether the explicitly-defaulted special members are valid.
6016       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6017         CheckExplicitlyDefaultedSpecialMember(M);
6018 
6019       // For an explicitly defaulted or deleted special member, we defer
6020       // determining triviality until the class is complete. That time is now!
6021       CXXSpecialMember CSM = getSpecialMember(M);
6022       if (!M->isImplicit() && !M->isUserProvided()) {
6023         if (CSM != CXXInvalid) {
6024           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6025           // Inform the class that we've finished declaring this member.
6026           Record->finishedDefaultedOrDeletedMember(M);
6027           M->setTrivialForCall(
6028               HasTrivialABI ||
6029               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6030           Record->setTrivialForCallFlags(M);
6031         }
6032       }
6033 
6034       // Set triviality for the purpose of calls if this is a user-provided
6035       // copy/move constructor or destructor.
6036       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6037            CSM == CXXDestructor) && M->isUserProvided()) {
6038         M->setTrivialForCall(HasTrivialABI);
6039         Record->setTrivialForCallFlags(M);
6040       }
6041 
6042       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6043           M->hasAttr<DLLExportAttr>()) {
6044         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6045             M->isTrivial() &&
6046             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6047              CSM == CXXDestructor))
6048           M->dropAttr<DLLExportAttr>();
6049 
6050         if (M->hasAttr<DLLExportAttr>()) {
6051           DefineImplicitSpecialMember(*this, M, M->getLocation());
6052           ActOnFinishInlineFunctionDef(M);
6053         }
6054       }
6055     }
6056   }
6057 
6058   if (HasMethodWithOverrideControl &&
6059       HasOverridingMethodWithoutOverrideControl) {
6060     // At least one method has the 'override' control declared.
6061     // Diagnose all other overridden methods which do not have 'override' specified on them.
6062     for (auto *M : Record->methods())
6063       DiagnoseAbsenceOfOverrideControl(M);
6064   }
6065 
6066   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6067   // whether this class uses any C++ features that are implemented
6068   // completely differently in MSVC, and if so, emit a diagnostic.
6069   // That diagnostic defaults to an error, but we allow projects to
6070   // map it down to a warning (or ignore it).  It's a fairly common
6071   // practice among users of the ms_struct pragma to mass-annotate
6072   // headers, sweeping up a bunch of types that the project doesn't
6073   // really rely on MSVC-compatible layout for.  We must therefore
6074   // support "ms_struct except for C++ stuff" as a secondary ABI.
6075   if (Record->isMsStruct(Context) &&
6076       (Record->isPolymorphic() || Record->getNumBases())) {
6077     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6078   }
6079 
6080   checkClassLevelDLLAttribute(Record);
6081 
6082   bool ClangABICompat4 =
6083       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6084   TargetInfo::CallingConvKind CCK =
6085       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6086   bool DestroyedInCallee = paramCanBeDestroyedInCallee(*this, Record, CCK);
6087 
6088   if (Record->hasNonTrivialDestructor())
6089     Record->setParamDestroyedInCallee(DestroyedInCallee);
6090 
6091   Record->setArgPassingRestrictions(
6092       computeArgPassingRestrictions(DestroyedInCallee, Record, CCK, *this));
6093 }
6094 
6095 /// Look up the special member function that would be called by a special
6096 /// member function for a subobject of class type.
6097 ///
6098 /// \param Class The class type of the subobject.
6099 /// \param CSM The kind of special member function.
6100 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6101 /// \param ConstRHS True if this is a copy operation with a const object
6102 ///        on its RHS, that is, if the argument to the outer special member
6103 ///        function is 'const' and this is not a field marked 'mutable'.
6104 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6105     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6106     unsigned FieldQuals, bool ConstRHS) {
6107   unsigned LHSQuals = 0;
6108   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6109     LHSQuals = FieldQuals;
6110 
6111   unsigned RHSQuals = FieldQuals;
6112   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6113     RHSQuals = 0;
6114   else if (ConstRHS)
6115     RHSQuals |= Qualifiers::Const;
6116 
6117   return S.LookupSpecialMember(Class, CSM,
6118                                RHSQuals & Qualifiers::Const,
6119                                RHSQuals & Qualifiers::Volatile,
6120                                false,
6121                                LHSQuals & Qualifiers::Const,
6122                                LHSQuals & Qualifiers::Volatile);
6123 }
6124 
6125 class Sema::InheritedConstructorInfo {
6126   Sema &S;
6127   SourceLocation UseLoc;
6128 
6129   /// A mapping from the base classes through which the constructor was
6130   /// inherited to the using shadow declaration in that base class (or a null
6131   /// pointer if the constructor was declared in that base class).
6132   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6133       InheritedFromBases;
6134 
6135 public:
6136   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6137                            ConstructorUsingShadowDecl *Shadow)
6138       : S(S), UseLoc(UseLoc) {
6139     bool DiagnosedMultipleConstructedBases = false;
6140     CXXRecordDecl *ConstructedBase = nullptr;
6141     UsingDecl *ConstructedBaseUsing = nullptr;
6142 
6143     // Find the set of such base class subobjects and check that there's a
6144     // unique constructed subobject.
6145     for (auto *D : Shadow->redecls()) {
6146       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6147       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6148       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6149 
6150       InheritedFromBases.insert(
6151           std::make_pair(DNominatedBase->getCanonicalDecl(),
6152                          DShadow->getNominatedBaseClassShadowDecl()));
6153       if (DShadow->constructsVirtualBase())
6154         InheritedFromBases.insert(
6155             std::make_pair(DConstructedBase->getCanonicalDecl(),
6156                            DShadow->getConstructedBaseClassShadowDecl()));
6157       else
6158         assert(DNominatedBase == DConstructedBase);
6159 
6160       // [class.inhctor.init]p2:
6161       //   If the constructor was inherited from multiple base class subobjects
6162       //   of type B, the program is ill-formed.
6163       if (!ConstructedBase) {
6164         ConstructedBase = DConstructedBase;
6165         ConstructedBaseUsing = D->getUsingDecl();
6166       } else if (ConstructedBase != DConstructedBase &&
6167                  !Shadow->isInvalidDecl()) {
6168         if (!DiagnosedMultipleConstructedBases) {
6169           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6170               << Shadow->getTargetDecl();
6171           S.Diag(ConstructedBaseUsing->getLocation(),
6172                diag::note_ambiguous_inherited_constructor_using)
6173               << ConstructedBase;
6174           DiagnosedMultipleConstructedBases = true;
6175         }
6176         S.Diag(D->getUsingDecl()->getLocation(),
6177                diag::note_ambiguous_inherited_constructor_using)
6178             << DConstructedBase;
6179       }
6180     }
6181 
6182     if (DiagnosedMultipleConstructedBases)
6183       Shadow->setInvalidDecl();
6184   }
6185 
6186   /// Find the constructor to use for inherited construction of a base class,
6187   /// and whether that base class constructor inherits the constructor from a
6188   /// virtual base class (in which case it won't actually invoke it).
6189   std::pair<CXXConstructorDecl *, bool>
6190   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6191     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6192     if (It == InheritedFromBases.end())
6193       return std::make_pair(nullptr, false);
6194 
6195     // This is an intermediary class.
6196     if (It->second)
6197       return std::make_pair(
6198           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6199           It->second->constructsVirtualBase());
6200 
6201     // This is the base class from which the constructor was inherited.
6202     return std::make_pair(Ctor, false);
6203   }
6204 };
6205 
6206 /// Is the special member function which would be selected to perform the
6207 /// specified operation on the specified class type a constexpr constructor?
6208 static bool
6209 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6210                          Sema::CXXSpecialMember CSM, unsigned Quals,
6211                          bool ConstRHS,
6212                          CXXConstructorDecl *InheritedCtor = nullptr,
6213                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6214   // If we're inheriting a constructor, see if we need to call it for this base
6215   // class.
6216   if (InheritedCtor) {
6217     assert(CSM == Sema::CXXDefaultConstructor);
6218     auto BaseCtor =
6219         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6220     if (BaseCtor)
6221       return BaseCtor->isConstexpr();
6222   }
6223 
6224   if (CSM == Sema::CXXDefaultConstructor)
6225     return ClassDecl->hasConstexprDefaultConstructor();
6226 
6227   Sema::SpecialMemberOverloadResult SMOR =
6228       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6229   if (!SMOR.getMethod())
6230     // A constructor we wouldn't select can't be "involved in initializing"
6231     // anything.
6232     return true;
6233   return SMOR.getMethod()->isConstexpr();
6234 }
6235 
6236 /// Determine whether the specified special member function would be constexpr
6237 /// if it were implicitly defined.
6238 static bool defaultedSpecialMemberIsConstexpr(
6239     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6240     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6241     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6242   if (!S.getLangOpts().CPlusPlus11)
6243     return false;
6244 
6245   // C++11 [dcl.constexpr]p4:
6246   // In the definition of a constexpr constructor [...]
6247   bool Ctor = true;
6248   switch (CSM) {
6249   case Sema::CXXDefaultConstructor:
6250     if (Inherited)
6251       break;
6252     // Since default constructor lookup is essentially trivial (and cannot
6253     // involve, for instance, template instantiation), we compute whether a
6254     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6255     //
6256     // This is important for performance; we need to know whether the default
6257     // constructor is constexpr to determine whether the type is a literal type.
6258     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6259 
6260   case Sema::CXXCopyConstructor:
6261   case Sema::CXXMoveConstructor:
6262     // For copy or move constructors, we need to perform overload resolution.
6263     break;
6264 
6265   case Sema::CXXCopyAssignment:
6266   case Sema::CXXMoveAssignment:
6267     if (!S.getLangOpts().CPlusPlus14)
6268       return false;
6269     // In C++1y, we need to perform overload resolution.
6270     Ctor = false;
6271     break;
6272 
6273   case Sema::CXXDestructor:
6274   case Sema::CXXInvalid:
6275     return false;
6276   }
6277 
6278   //   -- if the class is a non-empty union, or for each non-empty anonymous
6279   //      union member of a non-union class, exactly one non-static data member
6280   //      shall be initialized; [DR1359]
6281   //
6282   // If we squint, this is guaranteed, since exactly one non-static data member
6283   // will be initialized (if the constructor isn't deleted), we just don't know
6284   // which one.
6285   if (Ctor && ClassDecl->isUnion())
6286     return CSM == Sema::CXXDefaultConstructor
6287                ? ClassDecl->hasInClassInitializer() ||
6288                      !ClassDecl->hasVariantMembers()
6289                : true;
6290 
6291   //   -- the class shall not have any virtual base classes;
6292   if (Ctor && ClassDecl->getNumVBases())
6293     return false;
6294 
6295   // C++1y [class.copy]p26:
6296   //   -- [the class] is a literal type, and
6297   if (!Ctor && !ClassDecl->isLiteral())
6298     return false;
6299 
6300   //   -- every constructor involved in initializing [...] base class
6301   //      sub-objects shall be a constexpr constructor;
6302   //   -- the assignment operator selected to copy/move each direct base
6303   //      class is a constexpr function, and
6304   for (const auto &B : ClassDecl->bases()) {
6305     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6306     if (!BaseType) continue;
6307 
6308     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6309     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6310                                   InheritedCtor, Inherited))
6311       return false;
6312   }
6313 
6314   //   -- every constructor involved in initializing non-static data members
6315   //      [...] shall be a constexpr constructor;
6316   //   -- every non-static data member and base class sub-object shall be
6317   //      initialized
6318   //   -- for each non-static data member of X that is of class type (or array
6319   //      thereof), the assignment operator selected to copy/move that member is
6320   //      a constexpr function
6321   for (const auto *F : ClassDecl->fields()) {
6322     if (F->isInvalidDecl())
6323       continue;
6324     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6325       continue;
6326     QualType BaseType = S.Context.getBaseElementType(F->getType());
6327     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6328       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6329       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6330                                     BaseType.getCVRQualifiers(),
6331                                     ConstArg && !F->isMutable()))
6332         return false;
6333     } else if (CSM == Sema::CXXDefaultConstructor) {
6334       return false;
6335     }
6336   }
6337 
6338   // All OK, it's constexpr!
6339   return true;
6340 }
6341 
6342 static Sema::ImplicitExceptionSpecification
6343 ComputeDefaultedSpecialMemberExceptionSpec(
6344     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6345     Sema::InheritedConstructorInfo *ICI);
6346 
6347 static Sema::ImplicitExceptionSpecification
6348 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6349   auto CSM = S.getSpecialMember(MD);
6350   if (CSM != Sema::CXXInvalid)
6351     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6352 
6353   auto *CD = cast<CXXConstructorDecl>(MD);
6354   assert(CD->getInheritedConstructor() &&
6355          "only special members have implicit exception specs");
6356   Sema::InheritedConstructorInfo ICI(
6357       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6358   return ComputeDefaultedSpecialMemberExceptionSpec(
6359       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6360 }
6361 
6362 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6363                                                             CXXMethodDecl *MD) {
6364   FunctionProtoType::ExtProtoInfo EPI;
6365 
6366   // Build an exception specification pointing back at this member.
6367   EPI.ExceptionSpec.Type = EST_Unevaluated;
6368   EPI.ExceptionSpec.SourceDecl = MD;
6369 
6370   // Set the calling convention to the default for C++ instance methods.
6371   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6372       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6373                                             /*IsCXXMethod=*/true));
6374   return EPI;
6375 }
6376 
6377 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6378   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6379   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6380     return;
6381 
6382   // Evaluate the exception specification.
6383   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6384   auto ESI = IES.getExceptionSpec();
6385 
6386   // Update the type of the special member to use it.
6387   UpdateExceptionSpec(MD, ESI);
6388 
6389   // A user-provided destructor can be defined outside the class. When that
6390   // happens, be sure to update the exception specification on both
6391   // declarations.
6392   const FunctionProtoType *CanonicalFPT =
6393     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6394   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6395     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6396 }
6397 
6398 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6399   CXXRecordDecl *RD = MD->getParent();
6400   CXXSpecialMember CSM = getSpecialMember(MD);
6401 
6402   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6403          "not an explicitly-defaulted special member");
6404 
6405   // Whether this was the first-declared instance of the constructor.
6406   // This affects whether we implicitly add an exception spec and constexpr.
6407   bool First = MD == MD->getCanonicalDecl();
6408 
6409   bool HadError = false;
6410 
6411   // C++11 [dcl.fct.def.default]p1:
6412   //   A function that is explicitly defaulted shall
6413   //     -- be a special member function (checked elsewhere),
6414   //     -- have the same type (except for ref-qualifiers, and except that a
6415   //        copy operation can take a non-const reference) as an implicit
6416   //        declaration, and
6417   //     -- not have default arguments.
6418   unsigned ExpectedParams = 1;
6419   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6420     ExpectedParams = 0;
6421   if (MD->getNumParams() != ExpectedParams) {
6422     // This also checks for default arguments: a copy or move constructor with a
6423     // default argument is classified as a default constructor, and assignment
6424     // operations and destructors can't have default arguments.
6425     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6426       << CSM << MD->getSourceRange();
6427     HadError = true;
6428   } else if (MD->isVariadic()) {
6429     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6430       << CSM << MD->getSourceRange();
6431     HadError = true;
6432   }
6433 
6434   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6435 
6436   bool CanHaveConstParam = false;
6437   if (CSM == CXXCopyConstructor)
6438     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6439   else if (CSM == CXXCopyAssignment)
6440     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6441 
6442   QualType ReturnType = Context.VoidTy;
6443   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6444     // Check for return type matching.
6445     ReturnType = Type->getReturnType();
6446     QualType ExpectedReturnType =
6447         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6448     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6449       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6450         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6451       HadError = true;
6452     }
6453 
6454     // A defaulted special member cannot have cv-qualifiers.
6455     if (Type->getTypeQuals()) {
6456       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6457         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6458       HadError = true;
6459     }
6460   }
6461 
6462   // Check for parameter type matching.
6463   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6464   bool HasConstParam = false;
6465   if (ExpectedParams && ArgType->isReferenceType()) {
6466     // Argument must be reference to possibly-const T.
6467     QualType ReferentType = ArgType->getPointeeType();
6468     HasConstParam = ReferentType.isConstQualified();
6469 
6470     if (ReferentType.isVolatileQualified()) {
6471       Diag(MD->getLocation(),
6472            diag::err_defaulted_special_member_volatile_param) << CSM;
6473       HadError = true;
6474     }
6475 
6476     if (HasConstParam && !CanHaveConstParam) {
6477       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6478         Diag(MD->getLocation(),
6479              diag::err_defaulted_special_member_copy_const_param)
6480           << (CSM == CXXCopyAssignment);
6481         // FIXME: Explain why this special member can't be const.
6482       } else {
6483         Diag(MD->getLocation(),
6484              diag::err_defaulted_special_member_move_const_param)
6485           << (CSM == CXXMoveAssignment);
6486       }
6487       HadError = true;
6488     }
6489   } else if (ExpectedParams) {
6490     // A copy assignment operator can take its argument by value, but a
6491     // defaulted one cannot.
6492     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6493     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6494     HadError = true;
6495   }
6496 
6497   // C++11 [dcl.fct.def.default]p2:
6498   //   An explicitly-defaulted function may be declared constexpr only if it
6499   //   would have been implicitly declared as constexpr,
6500   // Do not apply this rule to members of class templates, since core issue 1358
6501   // makes such functions always instantiate to constexpr functions. For
6502   // functions which cannot be constexpr (for non-constructors in C++11 and for
6503   // destructors in C++1y), this is checked elsewhere.
6504   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6505                                                      HasConstParam);
6506   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6507                                  : isa<CXXConstructorDecl>(MD)) &&
6508       MD->isConstexpr() && !Constexpr &&
6509       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6510     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6511     // FIXME: Explain why the special member can't be constexpr.
6512     HadError = true;
6513   }
6514 
6515   //   and may have an explicit exception-specification only if it is compatible
6516   //   with the exception-specification on the implicit declaration.
6517   if (Type->hasExceptionSpec()) {
6518     // Delay the check if this is the first declaration of the special member,
6519     // since we may not have parsed some necessary in-class initializers yet.
6520     if (First) {
6521       // If the exception specification needs to be instantiated, do so now,
6522       // before we clobber it with an EST_Unevaluated specification below.
6523       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6524         InstantiateExceptionSpec(MD->getLocStart(), MD);
6525         Type = MD->getType()->getAs<FunctionProtoType>();
6526       }
6527       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6528     } else
6529       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6530   }
6531 
6532   //   If a function is explicitly defaulted on its first declaration,
6533   if (First) {
6534     //  -- it is implicitly considered to be constexpr if the implicit
6535     //     definition would be,
6536     MD->setConstexpr(Constexpr);
6537 
6538     //  -- it is implicitly considered to have the same exception-specification
6539     //     as if it had been implicitly declared,
6540     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6541     EPI.ExceptionSpec.Type = EST_Unevaluated;
6542     EPI.ExceptionSpec.SourceDecl = MD;
6543     MD->setType(Context.getFunctionType(ReturnType,
6544                                         llvm::makeArrayRef(&ArgType,
6545                                                            ExpectedParams),
6546                                         EPI));
6547   }
6548 
6549   if (ShouldDeleteSpecialMember(MD, CSM)) {
6550     if (First) {
6551       SetDeclDeleted(MD, MD->getLocation());
6552     } else {
6553       // C++11 [dcl.fct.def.default]p4:
6554       //   [For a] user-provided explicitly-defaulted function [...] if such a
6555       //   function is implicitly defined as deleted, the program is ill-formed.
6556       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6557       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6558       HadError = true;
6559     }
6560   }
6561 
6562   if (HadError)
6563     MD->setInvalidDecl();
6564 }
6565 
6566 /// Check whether the exception specification provided for an
6567 /// explicitly-defaulted special member matches the exception specification
6568 /// that would have been generated for an implicit special member, per
6569 /// C++11 [dcl.fct.def.default]p2.
6570 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6571     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6572   // If the exception specification was explicitly specified but hadn't been
6573   // parsed when the method was defaulted, grab it now.
6574   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6575     SpecifiedType =
6576         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6577 
6578   // Compute the implicit exception specification.
6579   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6580                                                        /*IsCXXMethod=*/true);
6581   FunctionProtoType::ExtProtoInfo EPI(CC);
6582   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6583   EPI.ExceptionSpec = IES.getExceptionSpec();
6584   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6585     Context.getFunctionType(Context.VoidTy, None, EPI));
6586 
6587   // Ensure that it matches.
6588   CheckEquivalentExceptionSpec(
6589     PDiag(diag::err_incorrect_defaulted_exception_spec)
6590       << getSpecialMember(MD), PDiag(),
6591     ImplicitType, SourceLocation(),
6592     SpecifiedType, MD->getLocation());
6593 }
6594 
6595 void Sema::CheckDelayedMemberExceptionSpecs() {
6596   decltype(DelayedExceptionSpecChecks) Checks;
6597   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6598 
6599   std::swap(Checks, DelayedExceptionSpecChecks);
6600   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6601 
6602   // Perform any deferred checking of exception specifications for virtual
6603   // destructors.
6604   for (auto &Check : Checks)
6605     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6606 
6607   // Check that any explicitly-defaulted methods have exception specifications
6608   // compatible with their implicit exception specifications.
6609   for (auto &Spec : Specs)
6610     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6611 }
6612 
6613 namespace {
6614 /// CRTP base class for visiting operations performed by a special member
6615 /// function (or inherited constructor).
6616 template<typename Derived>
6617 struct SpecialMemberVisitor {
6618   Sema &S;
6619   CXXMethodDecl *MD;
6620   Sema::CXXSpecialMember CSM;
6621   Sema::InheritedConstructorInfo *ICI;
6622 
6623   // Properties of the special member, computed for convenience.
6624   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6625 
6626   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6627                        Sema::InheritedConstructorInfo *ICI)
6628       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6629     switch (CSM) {
6630     case Sema::CXXDefaultConstructor:
6631     case Sema::CXXCopyConstructor:
6632     case Sema::CXXMoveConstructor:
6633       IsConstructor = true;
6634       break;
6635     case Sema::CXXCopyAssignment:
6636     case Sema::CXXMoveAssignment:
6637       IsAssignment = true;
6638       break;
6639     case Sema::CXXDestructor:
6640       break;
6641     case Sema::CXXInvalid:
6642       llvm_unreachable("invalid special member kind");
6643     }
6644 
6645     if (MD->getNumParams()) {
6646       if (const ReferenceType *RT =
6647               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6648         ConstArg = RT->getPointeeType().isConstQualified();
6649     }
6650   }
6651 
6652   Derived &getDerived() { return static_cast<Derived&>(*this); }
6653 
6654   /// Is this a "move" special member?
6655   bool isMove() const {
6656     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6657   }
6658 
6659   /// Look up the corresponding special member in the given class.
6660   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6661                                              unsigned Quals, bool IsMutable) {
6662     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6663                                        ConstArg && !IsMutable);
6664   }
6665 
6666   /// Look up the constructor for the specified base class to see if it's
6667   /// overridden due to this being an inherited constructor.
6668   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6669     if (!ICI)
6670       return {};
6671     assert(CSM == Sema::CXXDefaultConstructor);
6672     auto *BaseCtor =
6673       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6674     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6675       return MD;
6676     return {};
6677   }
6678 
6679   /// A base or member subobject.
6680   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6681 
6682   /// Get the location to use for a subobject in diagnostics.
6683   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6684     // FIXME: For an indirect virtual base, the direct base leading to
6685     // the indirect virtual base would be a more useful choice.
6686     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6687       return B->getBaseTypeLoc();
6688     else
6689       return Subobj.get<FieldDecl*>()->getLocation();
6690   }
6691 
6692   enum BasesToVisit {
6693     /// Visit all non-virtual (direct) bases.
6694     VisitNonVirtualBases,
6695     /// Visit all direct bases, virtual or not.
6696     VisitDirectBases,
6697     /// Visit all non-virtual bases, and all virtual bases if the class
6698     /// is not abstract.
6699     VisitPotentiallyConstructedBases,
6700     /// Visit all direct or virtual bases.
6701     VisitAllBases
6702   };
6703 
6704   // Visit the bases and members of the class.
6705   bool visit(BasesToVisit Bases) {
6706     CXXRecordDecl *RD = MD->getParent();
6707 
6708     if (Bases == VisitPotentiallyConstructedBases)
6709       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6710 
6711     for (auto &B : RD->bases())
6712       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6713           getDerived().visitBase(&B))
6714         return true;
6715 
6716     if (Bases == VisitAllBases)
6717       for (auto &B : RD->vbases())
6718         if (getDerived().visitBase(&B))
6719           return true;
6720 
6721     for (auto *F : RD->fields())
6722       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6723           getDerived().visitField(F))
6724         return true;
6725 
6726     return false;
6727   }
6728 };
6729 }
6730 
6731 namespace {
6732 struct SpecialMemberDeletionInfo
6733     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6734   bool Diagnose;
6735 
6736   SourceLocation Loc;
6737 
6738   bool AllFieldsAreConst;
6739 
6740   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6741                             Sema::CXXSpecialMember CSM,
6742                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6743       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6744         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6745 
6746   bool inUnion() const { return MD->getParent()->isUnion(); }
6747 
6748   Sema::CXXSpecialMember getEffectiveCSM() {
6749     return ICI ? Sema::CXXInvalid : CSM;
6750   }
6751 
6752   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6753   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6754 
6755   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6756   bool shouldDeleteForField(FieldDecl *FD);
6757   bool shouldDeleteForAllConstMembers();
6758 
6759   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6760                                      unsigned Quals);
6761   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6762                                     Sema::SpecialMemberOverloadResult SMOR,
6763                                     bool IsDtorCallInCtor);
6764 
6765   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6766 };
6767 }
6768 
6769 /// Is the given special member inaccessible when used on the given
6770 /// sub-object.
6771 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6772                                              CXXMethodDecl *target) {
6773   /// If we're operating on a base class, the object type is the
6774   /// type of this special member.
6775   QualType objectTy;
6776   AccessSpecifier access = target->getAccess();
6777   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6778     objectTy = S.Context.getTypeDeclType(MD->getParent());
6779     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6780 
6781   // If we're operating on a field, the object type is the type of the field.
6782   } else {
6783     objectTy = S.Context.getTypeDeclType(target->getParent());
6784   }
6785 
6786   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6787 }
6788 
6789 /// Check whether we should delete a special member due to the implicit
6790 /// definition containing a call to a special member of a subobject.
6791 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6792     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6793     bool IsDtorCallInCtor) {
6794   CXXMethodDecl *Decl = SMOR.getMethod();
6795   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6796 
6797   int DiagKind = -1;
6798 
6799   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6800     DiagKind = !Decl ? 0 : 1;
6801   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6802     DiagKind = 2;
6803   else if (!isAccessible(Subobj, Decl))
6804     DiagKind = 3;
6805   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6806            !Decl->isTrivial()) {
6807     // A member of a union must have a trivial corresponding special member.
6808     // As a weird special case, a destructor call from a union's constructor
6809     // must be accessible and non-deleted, but need not be trivial. Such a
6810     // destructor is never actually called, but is semantically checked as
6811     // if it were.
6812     DiagKind = 4;
6813   }
6814 
6815   if (DiagKind == -1)
6816     return false;
6817 
6818   if (Diagnose) {
6819     if (Field) {
6820       S.Diag(Field->getLocation(),
6821              diag::note_deleted_special_member_class_subobject)
6822         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6823         << Field << DiagKind << IsDtorCallInCtor;
6824     } else {
6825       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6826       S.Diag(Base->getLocStart(),
6827              diag::note_deleted_special_member_class_subobject)
6828         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6829         << Base->getType() << DiagKind << IsDtorCallInCtor;
6830     }
6831 
6832     if (DiagKind == 1)
6833       S.NoteDeletedFunction(Decl);
6834     // FIXME: Explain inaccessibility if DiagKind == 3.
6835   }
6836 
6837   return true;
6838 }
6839 
6840 /// Check whether we should delete a special member function due to having a
6841 /// direct or virtual base class or non-static data member of class type M.
6842 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6843     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6844   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6845   bool IsMutable = Field && Field->isMutable();
6846 
6847   // C++11 [class.ctor]p5:
6848   // -- any direct or virtual base class, or non-static data member with no
6849   //    brace-or-equal-initializer, has class type M (or array thereof) and
6850   //    either M has no default constructor or overload resolution as applied
6851   //    to M's default constructor results in an ambiguity or in a function
6852   //    that is deleted or inaccessible
6853   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6854   // -- a direct or virtual base class B that cannot be copied/moved because
6855   //    overload resolution, as applied to B's corresponding special member,
6856   //    results in an ambiguity or a function that is deleted or inaccessible
6857   //    from the defaulted special member
6858   // C++11 [class.dtor]p5:
6859   // -- any direct or virtual base class [...] has a type with a destructor
6860   //    that is deleted or inaccessible
6861   if (!(CSM == Sema::CXXDefaultConstructor &&
6862         Field && Field->hasInClassInitializer()) &&
6863       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6864                                    false))
6865     return true;
6866 
6867   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6868   // -- any direct or virtual base class or non-static data member has a
6869   //    type with a destructor that is deleted or inaccessible
6870   if (IsConstructor) {
6871     Sema::SpecialMemberOverloadResult SMOR =
6872         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6873                               false, false, false, false, false);
6874     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6875       return true;
6876   }
6877 
6878   return false;
6879 }
6880 
6881 /// Check whether we should delete a special member function due to the class
6882 /// having a particular direct or virtual base class.
6883 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6884   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6885   // If program is correct, BaseClass cannot be null, but if it is, the error
6886   // must be reported elsewhere.
6887   if (!BaseClass)
6888     return false;
6889   // If we have an inheriting constructor, check whether we're calling an
6890   // inherited constructor instead of a default constructor.
6891   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6892   if (auto *BaseCtor = SMOR.getMethod()) {
6893     // Note that we do not check access along this path; other than that,
6894     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6895     // FIXME: Check that the base has a usable destructor! Sink this into
6896     // shouldDeleteForClassSubobject.
6897     if (BaseCtor->isDeleted() && Diagnose) {
6898       S.Diag(Base->getLocStart(),
6899              diag::note_deleted_special_member_class_subobject)
6900         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6901         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6902       S.NoteDeletedFunction(BaseCtor);
6903     }
6904     return BaseCtor->isDeleted();
6905   }
6906   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6907 }
6908 
6909 /// Check whether we should delete a special member function due to the class
6910 /// having a particular non-static data member.
6911 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6912   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6913   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6914 
6915   if (CSM == Sema::CXXDefaultConstructor) {
6916     // For a default constructor, all references must be initialized in-class
6917     // and, if a union, it must have a non-const member.
6918     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6919       if (Diagnose)
6920         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6921           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6922       return true;
6923     }
6924     // C++11 [class.ctor]p5: any non-variant non-static data member of
6925     // const-qualified type (or array thereof) with no
6926     // brace-or-equal-initializer does not have a user-provided default
6927     // constructor.
6928     if (!inUnion() && FieldType.isConstQualified() &&
6929         !FD->hasInClassInitializer() &&
6930         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6931       if (Diagnose)
6932         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6933           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6934       return true;
6935     }
6936 
6937     if (inUnion() && !FieldType.isConstQualified())
6938       AllFieldsAreConst = false;
6939   } else if (CSM == Sema::CXXCopyConstructor) {
6940     // For a copy constructor, data members must not be of rvalue reference
6941     // type.
6942     if (FieldType->isRValueReferenceType()) {
6943       if (Diagnose)
6944         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6945           << MD->getParent() << FD << FieldType;
6946       return true;
6947     }
6948   } else if (IsAssignment) {
6949     // For an assignment operator, data members must not be of reference type.
6950     if (FieldType->isReferenceType()) {
6951       if (Diagnose)
6952         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6953           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6954       return true;
6955     }
6956     if (!FieldRecord && FieldType.isConstQualified()) {
6957       // C++11 [class.copy]p23:
6958       // -- a non-static data member of const non-class type (or array thereof)
6959       if (Diagnose)
6960         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6961           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6962       return true;
6963     }
6964   }
6965 
6966   if (FieldRecord) {
6967     // Some additional restrictions exist on the variant members.
6968     if (!inUnion() && FieldRecord->isUnion() &&
6969         FieldRecord->isAnonymousStructOrUnion()) {
6970       bool AllVariantFieldsAreConst = true;
6971 
6972       // FIXME: Handle anonymous unions declared within anonymous unions.
6973       for (auto *UI : FieldRecord->fields()) {
6974         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6975 
6976         if (!UnionFieldType.isConstQualified())
6977           AllVariantFieldsAreConst = false;
6978 
6979         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6980         if (UnionFieldRecord &&
6981             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6982                                           UnionFieldType.getCVRQualifiers()))
6983           return true;
6984       }
6985 
6986       // At least one member in each anonymous union must be non-const
6987       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6988           !FieldRecord->field_empty()) {
6989         if (Diagnose)
6990           S.Diag(FieldRecord->getLocation(),
6991                  diag::note_deleted_default_ctor_all_const)
6992             << !!ICI << MD->getParent() << /*anonymous union*/1;
6993         return true;
6994       }
6995 
6996       // Don't check the implicit member of the anonymous union type.
6997       // This is technically non-conformant, but sanity demands it.
6998       return false;
6999     }
7000 
7001     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7002                                       FieldType.getCVRQualifiers()))
7003       return true;
7004   }
7005 
7006   return false;
7007 }
7008 
7009 /// C++11 [class.ctor] p5:
7010 ///   A defaulted default constructor for a class X is defined as deleted if
7011 /// X is a union and all of its variant members are of const-qualified type.
7012 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7013   // This is a silly definition, because it gives an empty union a deleted
7014   // default constructor. Don't do that.
7015   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7016     bool AnyFields = false;
7017     for (auto *F : MD->getParent()->fields())
7018       if ((AnyFields = !F->isUnnamedBitfield()))
7019         break;
7020     if (!AnyFields)
7021       return false;
7022     if (Diagnose)
7023       S.Diag(MD->getParent()->getLocation(),
7024              diag::note_deleted_default_ctor_all_const)
7025         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7026     return true;
7027   }
7028   return false;
7029 }
7030 
7031 /// Determine whether a defaulted special member function should be defined as
7032 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7033 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7034 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7035                                      InheritedConstructorInfo *ICI,
7036                                      bool Diagnose) {
7037   if (MD->isInvalidDecl())
7038     return false;
7039   CXXRecordDecl *RD = MD->getParent();
7040   assert(!RD->isDependentType() && "do deletion after instantiation");
7041   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7042     return false;
7043 
7044   // C++11 [expr.lambda.prim]p19:
7045   //   The closure type associated with a lambda-expression has a
7046   //   deleted (8.4.3) default constructor and a deleted copy
7047   //   assignment operator.
7048   if (RD->isLambda() &&
7049       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7050     if (Diagnose)
7051       Diag(RD->getLocation(), diag::note_lambda_decl);
7052     return true;
7053   }
7054 
7055   // For an anonymous struct or union, the copy and assignment special members
7056   // will never be used, so skip the check. For an anonymous union declared at
7057   // namespace scope, the constructor and destructor are used.
7058   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7059       RD->isAnonymousStructOrUnion())
7060     return false;
7061 
7062   // C++11 [class.copy]p7, p18:
7063   //   If the class definition declares a move constructor or move assignment
7064   //   operator, an implicitly declared copy constructor or copy assignment
7065   //   operator is defined as deleted.
7066   if (MD->isImplicit() &&
7067       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7068     CXXMethodDecl *UserDeclaredMove = nullptr;
7069 
7070     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7071     // deletion of the corresponding copy operation, not both copy operations.
7072     // MSVC 2015 has adopted the standards conforming behavior.
7073     bool DeletesOnlyMatchingCopy =
7074         getLangOpts().MSVCCompat &&
7075         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7076 
7077     if (RD->hasUserDeclaredMoveConstructor() &&
7078         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7079       if (!Diagnose) return true;
7080 
7081       // Find any user-declared move constructor.
7082       for (auto *I : RD->ctors()) {
7083         if (I->isMoveConstructor()) {
7084           UserDeclaredMove = I;
7085           break;
7086         }
7087       }
7088       assert(UserDeclaredMove);
7089     } else if (RD->hasUserDeclaredMoveAssignment() &&
7090                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7091       if (!Diagnose) return true;
7092 
7093       // Find any user-declared move assignment operator.
7094       for (auto *I : RD->methods()) {
7095         if (I->isMoveAssignmentOperator()) {
7096           UserDeclaredMove = I;
7097           break;
7098         }
7099       }
7100       assert(UserDeclaredMove);
7101     }
7102 
7103     if (UserDeclaredMove) {
7104       Diag(UserDeclaredMove->getLocation(),
7105            diag::note_deleted_copy_user_declared_move)
7106         << (CSM == CXXCopyAssignment) << RD
7107         << UserDeclaredMove->isMoveAssignmentOperator();
7108       return true;
7109     }
7110   }
7111 
7112   // Do access control from the special member function
7113   ContextRAII MethodContext(*this, MD);
7114 
7115   // C++11 [class.dtor]p5:
7116   // -- for a virtual destructor, lookup of the non-array deallocation function
7117   //    results in an ambiguity or in a function that is deleted or inaccessible
7118   if (CSM == CXXDestructor && MD->isVirtual()) {
7119     FunctionDecl *OperatorDelete = nullptr;
7120     DeclarationName Name =
7121       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7122     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7123                                  OperatorDelete, /*Diagnose*/false)) {
7124       if (Diagnose)
7125         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7126       return true;
7127     }
7128   }
7129 
7130   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7131 
7132   // Per DR1611, do not consider virtual bases of constructors of abstract
7133   // classes, since we are not going to construct them.
7134   // Per DR1658, do not consider virtual bases of destructors of abstract
7135   // classes either.
7136   // Per DR2180, for assignment operators we only assign (and thus only
7137   // consider) direct bases.
7138   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7139                                  : SMI.VisitPotentiallyConstructedBases))
7140     return true;
7141 
7142   if (SMI.shouldDeleteForAllConstMembers())
7143     return true;
7144 
7145   if (getLangOpts().CUDA) {
7146     // We should delete the special member in CUDA mode if target inference
7147     // failed.
7148     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7149                                                    Diagnose);
7150   }
7151 
7152   return false;
7153 }
7154 
7155 /// Perform lookup for a special member of the specified kind, and determine
7156 /// whether it is trivial. If the triviality can be determined without the
7157 /// lookup, skip it. This is intended for use when determining whether a
7158 /// special member of a containing object is trivial, and thus does not ever
7159 /// perform overload resolution for default constructors.
7160 ///
7161 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7162 /// member that was most likely to be intended to be trivial, if any.
7163 ///
7164 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7165 /// determine whether the special member is trivial.
7166 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7167                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7168                                      bool ConstRHS,
7169                                      Sema::TrivialABIHandling TAH,
7170                                      CXXMethodDecl **Selected) {
7171   if (Selected)
7172     *Selected = nullptr;
7173 
7174   switch (CSM) {
7175   case Sema::CXXInvalid:
7176     llvm_unreachable("not a special member");
7177 
7178   case Sema::CXXDefaultConstructor:
7179     // C++11 [class.ctor]p5:
7180     //   A default constructor is trivial if:
7181     //    - all the [direct subobjects] have trivial default constructors
7182     //
7183     // Note, no overload resolution is performed in this case.
7184     if (RD->hasTrivialDefaultConstructor())
7185       return true;
7186 
7187     if (Selected) {
7188       // If there's a default constructor which could have been trivial, dig it
7189       // out. Otherwise, if there's any user-provided default constructor, point
7190       // to that as an example of why there's not a trivial one.
7191       CXXConstructorDecl *DefCtor = nullptr;
7192       if (RD->needsImplicitDefaultConstructor())
7193         S.DeclareImplicitDefaultConstructor(RD);
7194       for (auto *CI : RD->ctors()) {
7195         if (!CI->isDefaultConstructor())
7196           continue;
7197         DefCtor = CI;
7198         if (!DefCtor->isUserProvided())
7199           break;
7200       }
7201 
7202       *Selected = DefCtor;
7203     }
7204 
7205     return false;
7206 
7207   case Sema::CXXDestructor:
7208     // C++11 [class.dtor]p5:
7209     //   A destructor is trivial if:
7210     //    - all the direct [subobjects] have trivial destructors
7211     if (RD->hasTrivialDestructor() ||
7212         (TAH == Sema::TAH_ConsiderTrivialABI &&
7213          RD->hasTrivialDestructorForCall()))
7214       return true;
7215 
7216     if (Selected) {
7217       if (RD->needsImplicitDestructor())
7218         S.DeclareImplicitDestructor(RD);
7219       *Selected = RD->getDestructor();
7220     }
7221 
7222     return false;
7223 
7224   case Sema::CXXCopyConstructor:
7225     // C++11 [class.copy]p12:
7226     //   A copy constructor is trivial if:
7227     //    - the constructor selected to copy each direct [subobject] is trivial
7228     if (RD->hasTrivialCopyConstructor() ||
7229         (TAH == Sema::TAH_ConsiderTrivialABI &&
7230          RD->hasTrivialCopyConstructorForCall())) {
7231       if (Quals == Qualifiers::Const)
7232         // We must either select the trivial copy constructor or reach an
7233         // ambiguity; no need to actually perform overload resolution.
7234         return true;
7235     } else if (!Selected) {
7236       return false;
7237     }
7238     // In C++98, we are not supposed to perform overload resolution here, but we
7239     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7240     // cases like B as having a non-trivial copy constructor:
7241     //   struct A { template<typename T> A(T&); };
7242     //   struct B { mutable A a; };
7243     goto NeedOverloadResolution;
7244 
7245   case Sema::CXXCopyAssignment:
7246     // C++11 [class.copy]p25:
7247     //   A copy assignment operator is trivial if:
7248     //    - the assignment operator selected to copy each direct [subobject] is
7249     //      trivial
7250     if (RD->hasTrivialCopyAssignment()) {
7251       if (Quals == Qualifiers::Const)
7252         return true;
7253     } else if (!Selected) {
7254       return false;
7255     }
7256     // In C++98, we are not supposed to perform overload resolution here, but we
7257     // treat that as a language defect.
7258     goto NeedOverloadResolution;
7259 
7260   case Sema::CXXMoveConstructor:
7261   case Sema::CXXMoveAssignment:
7262   NeedOverloadResolution:
7263     Sema::SpecialMemberOverloadResult SMOR =
7264         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7265 
7266     // The standard doesn't describe how to behave if the lookup is ambiguous.
7267     // We treat it as not making the member non-trivial, just like the standard
7268     // mandates for the default constructor. This should rarely matter, because
7269     // the member will also be deleted.
7270     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7271       return true;
7272 
7273     if (!SMOR.getMethod()) {
7274       assert(SMOR.getKind() ==
7275              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7276       return false;
7277     }
7278 
7279     // We deliberately don't check if we found a deleted special member. We're
7280     // not supposed to!
7281     if (Selected)
7282       *Selected = SMOR.getMethod();
7283 
7284     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7285         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7286       return SMOR.getMethod()->isTrivialForCall();
7287     return SMOR.getMethod()->isTrivial();
7288   }
7289 
7290   llvm_unreachable("unknown special method kind");
7291 }
7292 
7293 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7294   for (auto *CI : RD->ctors())
7295     if (!CI->isImplicit())
7296       return CI;
7297 
7298   // Look for constructor templates.
7299   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7300   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7301     if (CXXConstructorDecl *CD =
7302           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7303       return CD;
7304   }
7305 
7306   return nullptr;
7307 }
7308 
7309 /// The kind of subobject we are checking for triviality. The values of this
7310 /// enumeration are used in diagnostics.
7311 enum TrivialSubobjectKind {
7312   /// The subobject is a base class.
7313   TSK_BaseClass,
7314   /// The subobject is a non-static data member.
7315   TSK_Field,
7316   /// The object is actually the complete object.
7317   TSK_CompleteObject
7318 };
7319 
7320 /// Check whether the special member selected for a given type would be trivial.
7321 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7322                                       QualType SubType, bool ConstRHS,
7323                                       Sema::CXXSpecialMember CSM,
7324                                       TrivialSubobjectKind Kind,
7325                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7326   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7327   if (!SubRD)
7328     return true;
7329 
7330   CXXMethodDecl *Selected;
7331   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7332                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7333     return true;
7334 
7335   if (Diagnose) {
7336     if (ConstRHS)
7337       SubType.addConst();
7338 
7339     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7340       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7341         << Kind << SubType.getUnqualifiedType();
7342       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7343         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7344     } else if (!Selected)
7345       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7346         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7347     else if (Selected->isUserProvided()) {
7348       if (Kind == TSK_CompleteObject)
7349         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7350           << Kind << SubType.getUnqualifiedType() << CSM;
7351       else {
7352         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7353           << Kind << SubType.getUnqualifiedType() << CSM;
7354         S.Diag(Selected->getLocation(), diag::note_declared_at);
7355       }
7356     } else {
7357       if (Kind != TSK_CompleteObject)
7358         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7359           << Kind << SubType.getUnqualifiedType() << CSM;
7360 
7361       // Explain why the defaulted or deleted special member isn't trivial.
7362       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7363                                Diagnose);
7364     }
7365   }
7366 
7367   return false;
7368 }
7369 
7370 /// Check whether the members of a class type allow a special member to be
7371 /// trivial.
7372 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7373                                      Sema::CXXSpecialMember CSM,
7374                                      bool ConstArg,
7375                                      Sema::TrivialABIHandling TAH,
7376                                      bool Diagnose) {
7377   for (const auto *FI : RD->fields()) {
7378     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7379       continue;
7380 
7381     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7382 
7383     // Pretend anonymous struct or union members are members of this class.
7384     if (FI->isAnonymousStructOrUnion()) {
7385       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7386                                     CSM, ConstArg, TAH, Diagnose))
7387         return false;
7388       continue;
7389     }
7390 
7391     // C++11 [class.ctor]p5:
7392     //   A default constructor is trivial if [...]
7393     //    -- no non-static data member of its class has a
7394     //       brace-or-equal-initializer
7395     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7396       if (Diagnose)
7397         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7398       return false;
7399     }
7400 
7401     // Objective C ARC 4.3.5:
7402     //   [...] nontrivally ownership-qualified types are [...] not trivially
7403     //   default constructible, copy constructible, move constructible, copy
7404     //   assignable, move assignable, or destructible [...]
7405     if (FieldType.hasNonTrivialObjCLifetime()) {
7406       if (Diagnose)
7407         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7408           << RD << FieldType.getObjCLifetime();
7409       return false;
7410     }
7411 
7412     bool ConstRHS = ConstArg && !FI->isMutable();
7413     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7414                                    CSM, TSK_Field, TAH, Diagnose))
7415       return false;
7416   }
7417 
7418   return true;
7419 }
7420 
7421 /// Diagnose why the specified class does not have a trivial special member of
7422 /// the given kind.
7423 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7424   QualType Ty = Context.getRecordType(RD);
7425 
7426   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7427   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7428                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7429                             /*Diagnose*/true);
7430 }
7431 
7432 /// Determine whether a defaulted or deleted special member function is trivial,
7433 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7434 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7435 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7436                                   TrivialABIHandling TAH, bool Diagnose) {
7437   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7438 
7439   CXXRecordDecl *RD = MD->getParent();
7440 
7441   bool ConstArg = false;
7442 
7443   // C++11 [class.copy]p12, p25: [DR1593]
7444   //   A [special member] is trivial if [...] its parameter-type-list is
7445   //   equivalent to the parameter-type-list of an implicit declaration [...]
7446   switch (CSM) {
7447   case CXXDefaultConstructor:
7448   case CXXDestructor:
7449     // Trivial default constructors and destructors cannot have parameters.
7450     break;
7451 
7452   case CXXCopyConstructor:
7453   case CXXCopyAssignment: {
7454     // Trivial copy operations always have const, non-volatile parameter types.
7455     ConstArg = true;
7456     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7457     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7458     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7459       if (Diagnose)
7460         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7461           << Param0->getSourceRange() << Param0->getType()
7462           << Context.getLValueReferenceType(
7463                Context.getRecordType(RD).withConst());
7464       return false;
7465     }
7466     break;
7467   }
7468 
7469   case CXXMoveConstructor:
7470   case CXXMoveAssignment: {
7471     // Trivial move operations always have non-cv-qualified parameters.
7472     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7473     const RValueReferenceType *RT =
7474       Param0->getType()->getAs<RValueReferenceType>();
7475     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7476       if (Diagnose)
7477         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7478           << Param0->getSourceRange() << Param0->getType()
7479           << Context.getRValueReferenceType(Context.getRecordType(RD));
7480       return false;
7481     }
7482     break;
7483   }
7484 
7485   case CXXInvalid:
7486     llvm_unreachable("not a special member");
7487   }
7488 
7489   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7490     if (Diagnose)
7491       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7492            diag::note_nontrivial_default_arg)
7493         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7494     return false;
7495   }
7496   if (MD->isVariadic()) {
7497     if (Diagnose)
7498       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7499     return false;
7500   }
7501 
7502   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7503   //   A copy/move [constructor or assignment operator] is trivial if
7504   //    -- the [member] selected to copy/move each direct base class subobject
7505   //       is trivial
7506   //
7507   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7508   //   A [default constructor or destructor] is trivial if
7509   //    -- all the direct base classes have trivial [default constructors or
7510   //       destructors]
7511   for (const auto &BI : RD->bases())
7512     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7513                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7514       return false;
7515 
7516   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7517   //   A copy/move [constructor or assignment operator] for a class X is
7518   //   trivial if
7519   //    -- for each non-static data member of X that is of class type (or array
7520   //       thereof), the constructor selected to copy/move that member is
7521   //       trivial
7522   //
7523   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7524   //   A [default constructor or destructor] is trivial if
7525   //    -- for all of the non-static data members of its class that are of class
7526   //       type (or array thereof), each such class has a trivial [default
7527   //       constructor or destructor]
7528   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7529     return false;
7530 
7531   // C++11 [class.dtor]p5:
7532   //   A destructor is trivial if [...]
7533   //    -- the destructor is not virtual
7534   if (CSM == CXXDestructor && MD->isVirtual()) {
7535     if (Diagnose)
7536       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7537     return false;
7538   }
7539 
7540   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7541   //   A [special member] for class X is trivial if [...]
7542   //    -- class X has no virtual functions and no virtual base classes
7543   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7544     if (!Diagnose)
7545       return false;
7546 
7547     if (RD->getNumVBases()) {
7548       // Check for virtual bases. We already know that the corresponding
7549       // member in all bases is trivial, so vbases must all be direct.
7550       CXXBaseSpecifier &BS = *RD->vbases_begin();
7551       assert(BS.isVirtual());
7552       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7553       return false;
7554     }
7555 
7556     // Must have a virtual method.
7557     for (const auto *MI : RD->methods()) {
7558       if (MI->isVirtual()) {
7559         SourceLocation MLoc = MI->getLocStart();
7560         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7561         return false;
7562       }
7563     }
7564 
7565     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7566   }
7567 
7568   // Looks like it's trivial!
7569   return true;
7570 }
7571 
7572 namespace {
7573 struct FindHiddenVirtualMethod {
7574   Sema *S;
7575   CXXMethodDecl *Method;
7576   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7577   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7578 
7579 private:
7580   /// Check whether any most overriden method from MD in Methods
7581   static bool CheckMostOverridenMethods(
7582       const CXXMethodDecl *MD,
7583       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7584     if (MD->size_overridden_methods() == 0)
7585       return Methods.count(MD->getCanonicalDecl());
7586     for (const CXXMethodDecl *O : MD->overridden_methods())
7587       if (CheckMostOverridenMethods(O, Methods))
7588         return true;
7589     return false;
7590   }
7591 
7592 public:
7593   /// Member lookup function that determines whether a given C++
7594   /// method overloads virtual methods in a base class without overriding any,
7595   /// to be used with CXXRecordDecl::lookupInBases().
7596   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7597     RecordDecl *BaseRecord =
7598         Specifier->getType()->getAs<RecordType>()->getDecl();
7599 
7600     DeclarationName Name = Method->getDeclName();
7601     assert(Name.getNameKind() == DeclarationName::Identifier);
7602 
7603     bool foundSameNameMethod = false;
7604     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7605     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7606          Path.Decls = Path.Decls.slice(1)) {
7607       NamedDecl *D = Path.Decls.front();
7608       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7609         MD = MD->getCanonicalDecl();
7610         foundSameNameMethod = true;
7611         // Interested only in hidden virtual methods.
7612         if (!MD->isVirtual())
7613           continue;
7614         // If the method we are checking overrides a method from its base
7615         // don't warn about the other overloaded methods. Clang deviates from
7616         // GCC by only diagnosing overloads of inherited virtual functions that
7617         // do not override any other virtual functions in the base. GCC's
7618         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7619         // function from a base class. These cases may be better served by a
7620         // warning (not specific to virtual functions) on call sites when the
7621         // call would select a different function from the base class, were it
7622         // visible.
7623         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7624         if (!S->IsOverload(Method, MD, false))
7625           return true;
7626         // Collect the overload only if its hidden.
7627         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7628           overloadedMethods.push_back(MD);
7629       }
7630     }
7631 
7632     if (foundSameNameMethod)
7633       OverloadedMethods.append(overloadedMethods.begin(),
7634                                overloadedMethods.end());
7635     return foundSameNameMethod;
7636   }
7637 };
7638 } // end anonymous namespace
7639 
7640 /// Add the most overriden methods from MD to Methods
7641 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7642                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7643   if (MD->size_overridden_methods() == 0)
7644     Methods.insert(MD->getCanonicalDecl());
7645   else
7646     for (const CXXMethodDecl *O : MD->overridden_methods())
7647       AddMostOverridenMethods(O, Methods);
7648 }
7649 
7650 /// Check if a method overloads virtual methods in a base class without
7651 /// overriding any.
7652 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7653                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7654   if (!MD->getDeclName().isIdentifier())
7655     return;
7656 
7657   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7658                      /*bool RecordPaths=*/false,
7659                      /*bool DetectVirtual=*/false);
7660   FindHiddenVirtualMethod FHVM;
7661   FHVM.Method = MD;
7662   FHVM.S = this;
7663 
7664   // Keep the base methods that were overriden or introduced in the subclass
7665   // by 'using' in a set. A base method not in this set is hidden.
7666   CXXRecordDecl *DC = MD->getParent();
7667   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7668   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7669     NamedDecl *ND = *I;
7670     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7671       ND = shad->getTargetDecl();
7672     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7673       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7674   }
7675 
7676   if (DC->lookupInBases(FHVM, Paths))
7677     OverloadedMethods = FHVM.OverloadedMethods;
7678 }
7679 
7680 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7681                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7682   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7683     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7684     PartialDiagnostic PD = PDiag(
7685          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7686     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7687     Diag(overloadedMD->getLocation(), PD);
7688   }
7689 }
7690 
7691 /// Diagnose methods which overload virtual methods in a base class
7692 /// without overriding any.
7693 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7694   if (MD->isInvalidDecl())
7695     return;
7696 
7697   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7698     return;
7699 
7700   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7701   FindHiddenVirtualMethods(MD, OverloadedMethods);
7702   if (!OverloadedMethods.empty()) {
7703     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7704       << MD << (OverloadedMethods.size() > 1);
7705 
7706     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7707   }
7708 }
7709 
7710 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7711   auto PrintDiagAndRemoveAttr = [&]() {
7712     // No diagnostics if this is a template instantiation.
7713     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7714       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7715            diag::ext_cannot_use_trivial_abi) << &RD;
7716     RD.dropAttr<TrivialABIAttr>();
7717   };
7718 
7719   // Ill-formed if the struct has virtual functions.
7720   if (RD.isPolymorphic()) {
7721     PrintDiagAndRemoveAttr();
7722     return;
7723   }
7724 
7725   for (const auto &B : RD.bases()) {
7726     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7727     // virtual base.
7728     if ((!B.getType()->isDependentType() &&
7729          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7730         B.isVirtual()) {
7731       PrintDiagAndRemoveAttr();
7732       return;
7733     }
7734   }
7735 
7736   for (const auto *FD : RD.fields()) {
7737     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7738     // non-trivial for the purpose of calls.
7739     QualType FT = FD->getType();
7740     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7741       PrintDiagAndRemoveAttr();
7742       return;
7743     }
7744 
7745     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7746       if (!RT->isDependentType() &&
7747           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7748         PrintDiagAndRemoveAttr();
7749         return;
7750       }
7751   }
7752 }
7753 
7754 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7755                                              Decl *TagDecl,
7756                                              SourceLocation LBrac,
7757                                              SourceLocation RBrac,
7758                                              AttributeList *AttrList) {
7759   if (!TagDecl)
7760     return;
7761 
7762   AdjustDeclIfTemplate(TagDecl);
7763 
7764   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7765     if (l->getKind() != AttributeList::AT_Visibility)
7766       continue;
7767     l->setInvalid();
7768     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7769       l->getName();
7770   }
7771 
7772   // See if trivial_abi has to be dropped.
7773   auto *RD = dyn_cast<CXXRecordDecl>(TagDecl);
7774   if (RD && RD->hasAttr<TrivialABIAttr>())
7775     checkIllFormedTrivialABIStruct(*RD);
7776 
7777   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7778               // strict aliasing violation!
7779               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7780               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7781 
7782   CheckCompletedCXXClass(RD);
7783 }
7784 
7785 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7786 /// special functions, such as the default constructor, copy
7787 /// constructor, or destructor, to the given C++ class (C++
7788 /// [special]p1).  This routine can only be executed just before the
7789 /// definition of the class is complete.
7790 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7791   if (ClassDecl->needsImplicitDefaultConstructor()) {
7792     ++ASTContext::NumImplicitDefaultConstructors;
7793 
7794     if (ClassDecl->hasInheritedConstructor())
7795       DeclareImplicitDefaultConstructor(ClassDecl);
7796   }
7797 
7798   if (ClassDecl->needsImplicitCopyConstructor()) {
7799     ++ASTContext::NumImplicitCopyConstructors;
7800 
7801     // If the properties or semantics of the copy constructor couldn't be
7802     // determined while the class was being declared, force a declaration
7803     // of it now.
7804     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7805         ClassDecl->hasInheritedConstructor())
7806       DeclareImplicitCopyConstructor(ClassDecl);
7807     // For the MS ABI we need to know whether the copy ctor is deleted. A
7808     // prerequisite for deleting the implicit copy ctor is that the class has a
7809     // move ctor or move assignment that is either user-declared or whose
7810     // semantics are inherited from a subobject. FIXME: We should provide a more
7811     // direct way for CodeGen to ask whether the constructor was deleted.
7812     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7813              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7814               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7815               ClassDecl->hasUserDeclaredMoveAssignment() ||
7816               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7817       DeclareImplicitCopyConstructor(ClassDecl);
7818   }
7819 
7820   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7821     ++ASTContext::NumImplicitMoveConstructors;
7822 
7823     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7824         ClassDecl->hasInheritedConstructor())
7825       DeclareImplicitMoveConstructor(ClassDecl);
7826   }
7827 
7828   if (ClassDecl->needsImplicitCopyAssignment()) {
7829     ++ASTContext::NumImplicitCopyAssignmentOperators;
7830 
7831     // If we have a dynamic class, then the copy assignment operator may be
7832     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7833     // it shows up in the right place in the vtable and that we diagnose
7834     // problems with the implicit exception specification.
7835     if (ClassDecl->isDynamicClass() ||
7836         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7837         ClassDecl->hasInheritedAssignment())
7838       DeclareImplicitCopyAssignment(ClassDecl);
7839   }
7840 
7841   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7842     ++ASTContext::NumImplicitMoveAssignmentOperators;
7843 
7844     // Likewise for the move assignment operator.
7845     if (ClassDecl->isDynamicClass() ||
7846         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7847         ClassDecl->hasInheritedAssignment())
7848       DeclareImplicitMoveAssignment(ClassDecl);
7849   }
7850 
7851   if (ClassDecl->needsImplicitDestructor()) {
7852     ++ASTContext::NumImplicitDestructors;
7853 
7854     // If we have a dynamic class, then the destructor may be virtual, so we
7855     // have to declare the destructor immediately. This ensures that, e.g., it
7856     // shows up in the right place in the vtable and that we diagnose problems
7857     // with the implicit exception specification.
7858     if (ClassDecl->isDynamicClass() ||
7859         ClassDecl->needsOverloadResolutionForDestructor())
7860       DeclareImplicitDestructor(ClassDecl);
7861   }
7862 }
7863 
7864 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7865   if (!D)
7866     return 0;
7867 
7868   // The order of template parameters is not important here. All names
7869   // get added to the same scope.
7870   SmallVector<TemplateParameterList *, 4> ParameterLists;
7871 
7872   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7873     D = TD->getTemplatedDecl();
7874 
7875   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7876     ParameterLists.push_back(PSD->getTemplateParameters());
7877 
7878   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7879     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7880       ParameterLists.push_back(DD->getTemplateParameterList(i));
7881 
7882     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7883       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7884         ParameterLists.push_back(FTD->getTemplateParameters());
7885     }
7886   }
7887 
7888   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7889     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7890       ParameterLists.push_back(TD->getTemplateParameterList(i));
7891 
7892     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7893       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7894         ParameterLists.push_back(CTD->getTemplateParameters());
7895     }
7896   }
7897 
7898   unsigned Count = 0;
7899   for (TemplateParameterList *Params : ParameterLists) {
7900     if (Params->size() > 0)
7901       // Ignore explicit specializations; they don't contribute to the template
7902       // depth.
7903       ++Count;
7904     for (NamedDecl *Param : *Params) {
7905       if (Param->getDeclName()) {
7906         S->AddDecl(Param);
7907         IdResolver.AddDecl(Param);
7908       }
7909     }
7910   }
7911 
7912   return Count;
7913 }
7914 
7915 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7916   if (!RecordD) return;
7917   AdjustDeclIfTemplate(RecordD);
7918   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7919   PushDeclContext(S, Record);
7920 }
7921 
7922 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7923   if (!RecordD) return;
7924   PopDeclContext();
7925 }
7926 
7927 /// This is used to implement the constant expression evaluation part of the
7928 /// attribute enable_if extension. There is nothing in standard C++ which would
7929 /// require reentering parameters.
7930 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7931   if (!Param)
7932     return;
7933 
7934   S->AddDecl(Param);
7935   if (Param->getDeclName())
7936     IdResolver.AddDecl(Param);
7937 }
7938 
7939 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7940 /// parsing a top-level (non-nested) C++ class, and we are now
7941 /// parsing those parts of the given Method declaration that could
7942 /// not be parsed earlier (C++ [class.mem]p2), such as default
7943 /// arguments. This action should enter the scope of the given
7944 /// Method declaration as if we had just parsed the qualified method
7945 /// name. However, it should not bring the parameters into scope;
7946 /// that will be performed by ActOnDelayedCXXMethodParameter.
7947 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7948 }
7949 
7950 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7951 /// C++ method declaration. We're (re-)introducing the given
7952 /// function parameter into scope for use in parsing later parts of
7953 /// the method declaration. For example, we could see an
7954 /// ActOnParamDefaultArgument event for this parameter.
7955 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7956   if (!ParamD)
7957     return;
7958 
7959   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7960 
7961   // If this parameter has an unparsed default argument, clear it out
7962   // to make way for the parsed default argument.
7963   if (Param->hasUnparsedDefaultArg())
7964     Param->setDefaultArg(nullptr);
7965 
7966   S->AddDecl(Param);
7967   if (Param->getDeclName())
7968     IdResolver.AddDecl(Param);
7969 }
7970 
7971 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7972 /// processing the delayed method declaration for Method. The method
7973 /// declaration is now considered finished. There may be a separate
7974 /// ActOnStartOfFunctionDef action later (not necessarily
7975 /// immediately!) for this method, if it was also defined inside the
7976 /// class body.
7977 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7978   if (!MethodD)
7979     return;
7980 
7981   AdjustDeclIfTemplate(MethodD);
7982 
7983   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7984 
7985   // Now that we have our default arguments, check the constructor
7986   // again. It could produce additional diagnostics or affect whether
7987   // the class has implicitly-declared destructors, among other
7988   // things.
7989   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7990     CheckConstructor(Constructor);
7991 
7992   // Check the default arguments, which we may have added.
7993   if (!Method->isInvalidDecl())
7994     CheckCXXDefaultArguments(Method);
7995 }
7996 
7997 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7998 /// the well-formedness of the constructor declarator @p D with type @p
7999 /// R. If there are any errors in the declarator, this routine will
8000 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8001 /// will be updated to reflect a well-formed type for the constructor and
8002 /// returned.
8003 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8004                                           StorageClass &SC) {
8005   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8006 
8007   // C++ [class.ctor]p3:
8008   //   A constructor shall not be virtual (10.3) or static (9.4). A
8009   //   constructor can be invoked for a const, volatile or const
8010   //   volatile object. A constructor shall not be declared const,
8011   //   volatile, or const volatile (9.3.2).
8012   if (isVirtual) {
8013     if (!D.isInvalidType())
8014       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8015         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8016         << SourceRange(D.getIdentifierLoc());
8017     D.setInvalidType();
8018   }
8019   if (SC == SC_Static) {
8020     if (!D.isInvalidType())
8021       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8022         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8023         << SourceRange(D.getIdentifierLoc());
8024     D.setInvalidType();
8025     SC = SC_None;
8026   }
8027 
8028   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8029     diagnoseIgnoredQualifiers(
8030         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8031         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8032         D.getDeclSpec().getRestrictSpecLoc(),
8033         D.getDeclSpec().getAtomicSpecLoc());
8034     D.setInvalidType();
8035   }
8036 
8037   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8038   if (FTI.TypeQuals != 0) {
8039     if (FTI.TypeQuals & Qualifiers::Const)
8040       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8041         << "const" << SourceRange(D.getIdentifierLoc());
8042     if (FTI.TypeQuals & Qualifiers::Volatile)
8043       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8044         << "volatile" << SourceRange(D.getIdentifierLoc());
8045     if (FTI.TypeQuals & Qualifiers::Restrict)
8046       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8047         << "restrict" << SourceRange(D.getIdentifierLoc());
8048     D.setInvalidType();
8049   }
8050 
8051   // C++0x [class.ctor]p4:
8052   //   A constructor shall not be declared with a ref-qualifier.
8053   if (FTI.hasRefQualifier()) {
8054     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8055       << FTI.RefQualifierIsLValueRef
8056       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8057     D.setInvalidType();
8058   }
8059 
8060   // Rebuild the function type "R" without any type qualifiers (in
8061   // case any of the errors above fired) and with "void" as the
8062   // return type, since constructors don't have return types.
8063   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8064   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8065     return R;
8066 
8067   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8068   EPI.TypeQuals = 0;
8069   EPI.RefQualifier = RQ_None;
8070 
8071   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8072 }
8073 
8074 /// CheckConstructor - Checks a fully-formed constructor for
8075 /// well-formedness, issuing any diagnostics required. Returns true if
8076 /// the constructor declarator is invalid.
8077 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8078   CXXRecordDecl *ClassDecl
8079     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8080   if (!ClassDecl)
8081     return Constructor->setInvalidDecl();
8082 
8083   // C++ [class.copy]p3:
8084   //   A declaration of a constructor for a class X is ill-formed if
8085   //   its first parameter is of type (optionally cv-qualified) X and
8086   //   either there are no other parameters or else all other
8087   //   parameters have default arguments.
8088   if (!Constructor->isInvalidDecl() &&
8089       ((Constructor->getNumParams() == 1) ||
8090        (Constructor->getNumParams() > 1 &&
8091         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8092       Constructor->getTemplateSpecializationKind()
8093                                               != TSK_ImplicitInstantiation) {
8094     QualType ParamType = Constructor->getParamDecl(0)->getType();
8095     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8096     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8097       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8098       const char *ConstRef
8099         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8100                                                         : " const &";
8101       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8102         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8103 
8104       // FIXME: Rather that making the constructor invalid, we should endeavor
8105       // to fix the type.
8106       Constructor->setInvalidDecl();
8107     }
8108   }
8109 }
8110 
8111 /// CheckDestructor - Checks a fully-formed destructor definition for
8112 /// well-formedness, issuing any diagnostics required.  Returns true
8113 /// on error.
8114 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8115   CXXRecordDecl *RD = Destructor->getParent();
8116 
8117   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8118     SourceLocation Loc;
8119 
8120     if (!Destructor->isImplicit())
8121       Loc = Destructor->getLocation();
8122     else
8123       Loc = RD->getLocation();
8124 
8125     // If we have a virtual destructor, look up the deallocation function
8126     if (FunctionDecl *OperatorDelete =
8127             FindDeallocationFunctionForDestructor(Loc, RD)) {
8128       Expr *ThisArg = nullptr;
8129 
8130       // If the notional 'delete this' expression requires a non-trivial
8131       // conversion from 'this' to the type of a destroying operator delete's
8132       // first parameter, perform that conversion now.
8133       if (OperatorDelete->isDestroyingOperatorDelete()) {
8134         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8135         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8136           // C++ [class.dtor]p13:
8137           //   ... as if for the expression 'delete this' appearing in a
8138           //   non-virtual destructor of the destructor's class.
8139           ContextRAII SwitchContext(*this, Destructor);
8140           ExprResult This =
8141               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8142           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8143           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8144           if (This.isInvalid()) {
8145             // FIXME: Register this as a context note so that it comes out
8146             // in the right order.
8147             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8148             return true;
8149           }
8150           ThisArg = This.get();
8151         }
8152       }
8153 
8154       MarkFunctionReferenced(Loc, OperatorDelete);
8155       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8156     }
8157   }
8158 
8159   return false;
8160 }
8161 
8162 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8163 /// the well-formednes of the destructor declarator @p D with type @p
8164 /// R. If there are any errors in the declarator, this routine will
8165 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8166 /// will be updated to reflect a well-formed type for the destructor and
8167 /// returned.
8168 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8169                                          StorageClass& SC) {
8170   // C++ [class.dtor]p1:
8171   //   [...] A typedef-name that names a class is a class-name
8172   //   (7.1.3); however, a typedef-name that names a class shall not
8173   //   be used as the identifier in the declarator for a destructor
8174   //   declaration.
8175   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8176   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8177     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8178       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8179   else if (const TemplateSpecializationType *TST =
8180              DeclaratorType->getAs<TemplateSpecializationType>())
8181     if (TST->isTypeAlias())
8182       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8183         << DeclaratorType << 1;
8184 
8185   // C++ [class.dtor]p2:
8186   //   A destructor is used to destroy objects of its class type. A
8187   //   destructor takes no parameters, and no return type can be
8188   //   specified for it (not even void). The address of a destructor
8189   //   shall not be taken. A destructor shall not be static. A
8190   //   destructor can be invoked for a const, volatile or const
8191   //   volatile object. A destructor shall not be declared const,
8192   //   volatile or const volatile (9.3.2).
8193   if (SC == SC_Static) {
8194     if (!D.isInvalidType())
8195       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8196         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8197         << SourceRange(D.getIdentifierLoc())
8198         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8199 
8200     SC = SC_None;
8201   }
8202   if (!D.isInvalidType()) {
8203     // Destructors don't have return types, but the parser will
8204     // happily parse something like:
8205     //
8206     //   class X {
8207     //     float ~X();
8208     //   };
8209     //
8210     // The return type will be eliminated later.
8211     if (D.getDeclSpec().hasTypeSpecifier())
8212       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8213         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8214         << SourceRange(D.getIdentifierLoc());
8215     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8216       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8217                                 SourceLocation(),
8218                                 D.getDeclSpec().getConstSpecLoc(),
8219                                 D.getDeclSpec().getVolatileSpecLoc(),
8220                                 D.getDeclSpec().getRestrictSpecLoc(),
8221                                 D.getDeclSpec().getAtomicSpecLoc());
8222       D.setInvalidType();
8223     }
8224   }
8225 
8226   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8227   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8228     if (FTI.TypeQuals & Qualifiers::Const)
8229       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8230         << "const" << SourceRange(D.getIdentifierLoc());
8231     if (FTI.TypeQuals & Qualifiers::Volatile)
8232       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8233         << "volatile" << SourceRange(D.getIdentifierLoc());
8234     if (FTI.TypeQuals & Qualifiers::Restrict)
8235       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8236         << "restrict" << SourceRange(D.getIdentifierLoc());
8237     D.setInvalidType();
8238   }
8239 
8240   // C++0x [class.dtor]p2:
8241   //   A destructor shall not be declared with a ref-qualifier.
8242   if (FTI.hasRefQualifier()) {
8243     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8244       << FTI.RefQualifierIsLValueRef
8245       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8246     D.setInvalidType();
8247   }
8248 
8249   // Make sure we don't have any parameters.
8250   if (FTIHasNonVoidParameters(FTI)) {
8251     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8252 
8253     // Delete the parameters.
8254     FTI.freeParams();
8255     D.setInvalidType();
8256   }
8257 
8258   // Make sure the destructor isn't variadic.
8259   if (FTI.isVariadic) {
8260     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8261     D.setInvalidType();
8262   }
8263 
8264   // Rebuild the function type "R" without any type qualifiers or
8265   // parameters (in case any of the errors above fired) and with
8266   // "void" as the return type, since destructors don't have return
8267   // types.
8268   if (!D.isInvalidType())
8269     return R;
8270 
8271   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8272   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8273   EPI.Variadic = false;
8274   EPI.TypeQuals = 0;
8275   EPI.RefQualifier = RQ_None;
8276   return Context.getFunctionType(Context.VoidTy, None, EPI);
8277 }
8278 
8279 static void extendLeft(SourceRange &R, SourceRange Before) {
8280   if (Before.isInvalid())
8281     return;
8282   R.setBegin(Before.getBegin());
8283   if (R.getEnd().isInvalid())
8284     R.setEnd(Before.getEnd());
8285 }
8286 
8287 static void extendRight(SourceRange &R, SourceRange After) {
8288   if (After.isInvalid())
8289     return;
8290   if (R.getBegin().isInvalid())
8291     R.setBegin(After.getBegin());
8292   R.setEnd(After.getEnd());
8293 }
8294 
8295 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8296 /// well-formednes of the conversion function declarator @p D with
8297 /// type @p R. If there are any errors in the declarator, this routine
8298 /// will emit diagnostics and return true. Otherwise, it will return
8299 /// false. Either way, the type @p R will be updated to reflect a
8300 /// well-formed type for the conversion operator.
8301 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8302                                      StorageClass& SC) {
8303   // C++ [class.conv.fct]p1:
8304   //   Neither parameter types nor return type can be specified. The
8305   //   type of a conversion function (8.3.5) is "function taking no
8306   //   parameter returning conversion-type-id."
8307   if (SC == SC_Static) {
8308     if (!D.isInvalidType())
8309       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8310         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8311         << D.getName().getSourceRange();
8312     D.setInvalidType();
8313     SC = SC_None;
8314   }
8315 
8316   TypeSourceInfo *ConvTSI = nullptr;
8317   QualType ConvType =
8318       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8319 
8320   const DeclSpec &DS = D.getDeclSpec();
8321   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8322     // Conversion functions don't have return types, but the parser will
8323     // happily parse something like:
8324     //
8325     //   class X {
8326     //     float operator bool();
8327     //   };
8328     //
8329     // The return type will be changed later anyway.
8330     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8331       << SourceRange(DS.getTypeSpecTypeLoc())
8332       << SourceRange(D.getIdentifierLoc());
8333     D.setInvalidType();
8334   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8335     // It's also plausible that the user writes type qualifiers in the wrong
8336     // place, such as:
8337     //   struct S { const operator int(); };
8338     // FIXME: we could provide a fixit to move the qualifiers onto the
8339     // conversion type.
8340     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8341         << SourceRange(D.getIdentifierLoc()) << 0;
8342     D.setInvalidType();
8343   }
8344 
8345   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8346 
8347   // Make sure we don't have any parameters.
8348   if (Proto->getNumParams() > 0) {
8349     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8350 
8351     // Delete the parameters.
8352     D.getFunctionTypeInfo().freeParams();
8353     D.setInvalidType();
8354   } else if (Proto->isVariadic()) {
8355     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8356     D.setInvalidType();
8357   }
8358 
8359   // Diagnose "&operator bool()" and other such nonsense.  This
8360   // is actually a gcc extension which we don't support.
8361   if (Proto->getReturnType() != ConvType) {
8362     bool NeedsTypedef = false;
8363     SourceRange Before, After;
8364 
8365     // Walk the chunks and extract information on them for our diagnostic.
8366     bool PastFunctionChunk = false;
8367     for (auto &Chunk : D.type_objects()) {
8368       switch (Chunk.Kind) {
8369       case DeclaratorChunk::Function:
8370         if (!PastFunctionChunk) {
8371           if (Chunk.Fun.HasTrailingReturnType) {
8372             TypeSourceInfo *TRT = nullptr;
8373             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8374             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8375           }
8376           PastFunctionChunk = true;
8377           break;
8378         }
8379         LLVM_FALLTHROUGH;
8380       case DeclaratorChunk::Array:
8381         NeedsTypedef = true;
8382         extendRight(After, Chunk.getSourceRange());
8383         break;
8384 
8385       case DeclaratorChunk::Pointer:
8386       case DeclaratorChunk::BlockPointer:
8387       case DeclaratorChunk::Reference:
8388       case DeclaratorChunk::MemberPointer:
8389       case DeclaratorChunk::Pipe:
8390         extendLeft(Before, Chunk.getSourceRange());
8391         break;
8392 
8393       case DeclaratorChunk::Paren:
8394         extendLeft(Before, Chunk.Loc);
8395         extendRight(After, Chunk.EndLoc);
8396         break;
8397       }
8398     }
8399 
8400     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8401                          After.isValid()  ? After.getBegin() :
8402                                             D.getIdentifierLoc();
8403     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8404     DB << Before << After;
8405 
8406     if (!NeedsTypedef) {
8407       DB << /*don't need a typedef*/0;
8408 
8409       // If we can provide a correct fix-it hint, do so.
8410       if (After.isInvalid() && ConvTSI) {
8411         SourceLocation InsertLoc =
8412             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8413         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8414            << FixItHint::CreateInsertionFromRange(
8415                   InsertLoc, CharSourceRange::getTokenRange(Before))
8416            << FixItHint::CreateRemoval(Before);
8417       }
8418     } else if (!Proto->getReturnType()->isDependentType()) {
8419       DB << /*typedef*/1 << Proto->getReturnType();
8420     } else if (getLangOpts().CPlusPlus11) {
8421       DB << /*alias template*/2 << Proto->getReturnType();
8422     } else {
8423       DB << /*might not be fixable*/3;
8424     }
8425 
8426     // Recover by incorporating the other type chunks into the result type.
8427     // Note, this does *not* change the name of the function. This is compatible
8428     // with the GCC extension:
8429     //   struct S { &operator int(); } s;
8430     //   int &r = s.operator int(); // ok in GCC
8431     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8432     ConvType = Proto->getReturnType();
8433   }
8434 
8435   // C++ [class.conv.fct]p4:
8436   //   The conversion-type-id shall not represent a function type nor
8437   //   an array type.
8438   if (ConvType->isArrayType()) {
8439     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8440     ConvType = Context.getPointerType(ConvType);
8441     D.setInvalidType();
8442   } else if (ConvType->isFunctionType()) {
8443     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8444     ConvType = Context.getPointerType(ConvType);
8445     D.setInvalidType();
8446   }
8447 
8448   // Rebuild the function type "R" without any parameters (in case any
8449   // of the errors above fired) and with the conversion type as the
8450   // return type.
8451   if (D.isInvalidType())
8452     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8453 
8454   // C++0x explicit conversion operators.
8455   if (DS.isExplicitSpecified())
8456     Diag(DS.getExplicitSpecLoc(),
8457          getLangOpts().CPlusPlus11
8458              ? diag::warn_cxx98_compat_explicit_conversion_functions
8459              : diag::ext_explicit_conversion_functions)
8460         << SourceRange(DS.getExplicitSpecLoc());
8461 }
8462 
8463 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8464 /// the declaration of the given C++ conversion function. This routine
8465 /// is responsible for recording the conversion function in the C++
8466 /// class, if possible.
8467 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8468   assert(Conversion && "Expected to receive a conversion function declaration");
8469 
8470   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8471 
8472   // Make sure we aren't redeclaring the conversion function.
8473   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8474 
8475   // C++ [class.conv.fct]p1:
8476   //   [...] A conversion function is never used to convert a
8477   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8478   //   same object type (or a reference to it), to a (possibly
8479   //   cv-qualified) base class of that type (or a reference to it),
8480   //   or to (possibly cv-qualified) void.
8481   // FIXME: Suppress this warning if the conversion function ends up being a
8482   // virtual function that overrides a virtual function in a base class.
8483   QualType ClassType
8484     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8485   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8486     ConvType = ConvTypeRef->getPointeeType();
8487   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8488       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8489     /* Suppress diagnostics for instantiations. */;
8490   else if (ConvType->isRecordType()) {
8491     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8492     if (ConvType == ClassType)
8493       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8494         << ClassType;
8495     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8496       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8497         <<  ClassType << ConvType;
8498   } else if (ConvType->isVoidType()) {
8499     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8500       << ClassType << ConvType;
8501   }
8502 
8503   if (FunctionTemplateDecl *ConversionTemplate
8504                                 = Conversion->getDescribedFunctionTemplate())
8505     return ConversionTemplate;
8506 
8507   return Conversion;
8508 }
8509 
8510 namespace {
8511 /// Utility class to accumulate and print a diagnostic listing the invalid
8512 /// specifier(s) on a declaration.
8513 struct BadSpecifierDiagnoser {
8514   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8515       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8516   ~BadSpecifierDiagnoser() {
8517     Diagnostic << Specifiers;
8518   }
8519 
8520   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8521     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8522   }
8523   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8524     return check(SpecLoc,
8525                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8526   }
8527   void check(SourceLocation SpecLoc, const char *Spec) {
8528     if (SpecLoc.isInvalid()) return;
8529     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8530     if (!Specifiers.empty()) Specifiers += " ";
8531     Specifiers += Spec;
8532   }
8533 
8534   Sema &S;
8535   Sema::SemaDiagnosticBuilder Diagnostic;
8536   std::string Specifiers;
8537 };
8538 }
8539 
8540 /// Check the validity of a declarator that we parsed for a deduction-guide.
8541 /// These aren't actually declarators in the grammar, so we need to check that
8542 /// the user didn't specify any pieces that are not part of the deduction-guide
8543 /// grammar.
8544 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8545                                          StorageClass &SC) {
8546   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8547   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8548   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8549 
8550   // C++ [temp.deduct.guide]p3:
8551   //   A deduction-gide shall be declared in the same scope as the
8552   //   corresponding class template.
8553   if (!CurContext->getRedeclContext()->Equals(
8554           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8555     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8556       << GuidedTemplateDecl;
8557     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8558   }
8559 
8560   auto &DS = D.getMutableDeclSpec();
8561   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8562   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8563       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8564       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8565     BadSpecifierDiagnoser Diagnoser(
8566         *this, D.getIdentifierLoc(),
8567         diag::err_deduction_guide_invalid_specifier);
8568 
8569     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8570     DS.ClearStorageClassSpecs();
8571     SC = SC_None;
8572 
8573     // 'explicit' is permitted.
8574     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8575     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8576     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8577     DS.ClearConstexprSpec();
8578 
8579     Diagnoser.check(DS.getConstSpecLoc(), "const");
8580     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8581     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8582     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8583     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8584     DS.ClearTypeQualifiers();
8585 
8586     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8587     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8588     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8589     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8590     DS.ClearTypeSpecType();
8591   }
8592 
8593   if (D.isInvalidType())
8594     return;
8595 
8596   // Check the declarator is simple enough.
8597   bool FoundFunction = false;
8598   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8599     if (Chunk.Kind == DeclaratorChunk::Paren)
8600       continue;
8601     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8602       Diag(D.getDeclSpec().getLocStart(),
8603           diag::err_deduction_guide_with_complex_decl)
8604         << D.getSourceRange();
8605       break;
8606     }
8607     if (!Chunk.Fun.hasTrailingReturnType()) {
8608       Diag(D.getName().getLocStart(),
8609            diag::err_deduction_guide_no_trailing_return_type);
8610       break;
8611     }
8612 
8613     // Check that the return type is written as a specialization of
8614     // the template specified as the deduction-guide's name.
8615     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8616     TypeSourceInfo *TSI = nullptr;
8617     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8618     assert(TSI && "deduction guide has valid type but invalid return type?");
8619     bool AcceptableReturnType = false;
8620     bool MightInstantiateToSpecialization = false;
8621     if (auto RetTST =
8622             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8623       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8624       bool TemplateMatches =
8625           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8626       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8627         AcceptableReturnType = true;
8628       else {
8629         // This could still instantiate to the right type, unless we know it
8630         // names the wrong class template.
8631         auto *TD = SpecifiedName.getAsTemplateDecl();
8632         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8633                                              !TemplateMatches);
8634       }
8635     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8636       MightInstantiateToSpecialization = true;
8637     }
8638 
8639     if (!AcceptableReturnType) {
8640       Diag(TSI->getTypeLoc().getLocStart(),
8641            diag::err_deduction_guide_bad_trailing_return_type)
8642         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8643         << TSI->getTypeLoc().getSourceRange();
8644     }
8645 
8646     // Keep going to check that we don't have any inner declarator pieces (we
8647     // could still have a function returning a pointer to a function).
8648     FoundFunction = true;
8649   }
8650 
8651   if (D.isFunctionDefinition())
8652     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8653 }
8654 
8655 //===----------------------------------------------------------------------===//
8656 // Namespace Handling
8657 //===----------------------------------------------------------------------===//
8658 
8659 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8660 /// reopened.
8661 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8662                                             SourceLocation Loc,
8663                                             IdentifierInfo *II, bool *IsInline,
8664                                             NamespaceDecl *PrevNS) {
8665   assert(*IsInline != PrevNS->isInline());
8666 
8667   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8668   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8669   // inline namespaces, with the intention of bringing names into namespace std.
8670   //
8671   // We support this just well enough to get that case working; this is not
8672   // sufficient to support reopening namespaces as inline in general.
8673   if (*IsInline && II && II->getName().startswith("__atomic") &&
8674       S.getSourceManager().isInSystemHeader(Loc)) {
8675     // Mark all prior declarations of the namespace as inline.
8676     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8677          NS = NS->getPreviousDecl())
8678       NS->setInline(*IsInline);
8679     // Patch up the lookup table for the containing namespace. This isn't really
8680     // correct, but it's good enough for this particular case.
8681     for (auto *I : PrevNS->decls())
8682       if (auto *ND = dyn_cast<NamedDecl>(I))
8683         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8684     return;
8685   }
8686 
8687   if (PrevNS->isInline())
8688     // The user probably just forgot the 'inline', so suggest that it
8689     // be added back.
8690     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8691       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8692   else
8693     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8694 
8695   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8696   *IsInline = PrevNS->isInline();
8697 }
8698 
8699 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8700 /// definition.
8701 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8702                                    SourceLocation InlineLoc,
8703                                    SourceLocation NamespaceLoc,
8704                                    SourceLocation IdentLoc,
8705                                    IdentifierInfo *II,
8706                                    SourceLocation LBrace,
8707                                    AttributeList *AttrList,
8708                                    UsingDirectiveDecl *&UD) {
8709   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8710   // For anonymous namespace, take the location of the left brace.
8711   SourceLocation Loc = II ? IdentLoc : LBrace;
8712   bool IsInline = InlineLoc.isValid();
8713   bool IsInvalid = false;
8714   bool IsStd = false;
8715   bool AddToKnown = false;
8716   Scope *DeclRegionScope = NamespcScope->getParent();
8717 
8718   NamespaceDecl *PrevNS = nullptr;
8719   if (II) {
8720     // C++ [namespace.def]p2:
8721     //   The identifier in an original-namespace-definition shall not
8722     //   have been previously defined in the declarative region in
8723     //   which the original-namespace-definition appears. The
8724     //   identifier in an original-namespace-definition is the name of
8725     //   the namespace. Subsequently in that declarative region, it is
8726     //   treated as an original-namespace-name.
8727     //
8728     // Since namespace names are unique in their scope, and we don't
8729     // look through using directives, just look for any ordinary names
8730     // as if by qualified name lookup.
8731     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8732                    ForExternalRedeclaration);
8733     LookupQualifiedName(R, CurContext->getRedeclContext());
8734     NamedDecl *PrevDecl =
8735         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8736     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8737 
8738     if (PrevNS) {
8739       // This is an extended namespace definition.
8740       if (IsInline != PrevNS->isInline())
8741         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8742                                         &IsInline, PrevNS);
8743     } else if (PrevDecl) {
8744       // This is an invalid name redefinition.
8745       Diag(Loc, diag::err_redefinition_different_kind)
8746         << II;
8747       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8748       IsInvalid = true;
8749       // Continue on to push Namespc as current DeclContext and return it.
8750     } else if (II->isStr("std") &&
8751                CurContext->getRedeclContext()->isTranslationUnit()) {
8752       // This is the first "real" definition of the namespace "std", so update
8753       // our cache of the "std" namespace to point at this definition.
8754       PrevNS = getStdNamespace();
8755       IsStd = true;
8756       AddToKnown = !IsInline;
8757     } else {
8758       // We've seen this namespace for the first time.
8759       AddToKnown = !IsInline;
8760     }
8761   } else {
8762     // Anonymous namespaces.
8763 
8764     // Determine whether the parent already has an anonymous namespace.
8765     DeclContext *Parent = CurContext->getRedeclContext();
8766     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8767       PrevNS = TU->getAnonymousNamespace();
8768     } else {
8769       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8770       PrevNS = ND->getAnonymousNamespace();
8771     }
8772 
8773     if (PrevNS && IsInline != PrevNS->isInline())
8774       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8775                                       &IsInline, PrevNS);
8776   }
8777 
8778   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8779                                                  StartLoc, Loc, II, PrevNS);
8780   if (IsInvalid)
8781     Namespc->setInvalidDecl();
8782 
8783   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8784   AddPragmaAttributes(DeclRegionScope, Namespc);
8785 
8786   // FIXME: Should we be merging attributes?
8787   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8788     PushNamespaceVisibilityAttr(Attr, Loc);
8789 
8790   if (IsStd)
8791     StdNamespace = Namespc;
8792   if (AddToKnown)
8793     KnownNamespaces[Namespc] = false;
8794 
8795   if (II) {
8796     PushOnScopeChains(Namespc, DeclRegionScope);
8797   } else {
8798     // Link the anonymous namespace into its parent.
8799     DeclContext *Parent = CurContext->getRedeclContext();
8800     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8801       TU->setAnonymousNamespace(Namespc);
8802     } else {
8803       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8804     }
8805 
8806     CurContext->addDecl(Namespc);
8807 
8808     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8809     //   behaves as if it were replaced by
8810     //     namespace unique { /* empty body */ }
8811     //     using namespace unique;
8812     //     namespace unique { namespace-body }
8813     //   where all occurrences of 'unique' in a translation unit are
8814     //   replaced by the same identifier and this identifier differs
8815     //   from all other identifiers in the entire program.
8816 
8817     // We just create the namespace with an empty name and then add an
8818     // implicit using declaration, just like the standard suggests.
8819     //
8820     // CodeGen enforces the "universally unique" aspect by giving all
8821     // declarations semantically contained within an anonymous
8822     // namespace internal linkage.
8823 
8824     if (!PrevNS) {
8825       UD = UsingDirectiveDecl::Create(Context, Parent,
8826                                       /* 'using' */ LBrace,
8827                                       /* 'namespace' */ SourceLocation(),
8828                                       /* qualifier */ NestedNameSpecifierLoc(),
8829                                       /* identifier */ SourceLocation(),
8830                                       Namespc,
8831                                       /* Ancestor */ Parent);
8832       UD->setImplicit();
8833       Parent->addDecl(UD);
8834     }
8835   }
8836 
8837   ActOnDocumentableDecl(Namespc);
8838 
8839   // Although we could have an invalid decl (i.e. the namespace name is a
8840   // redefinition), push it as current DeclContext and try to continue parsing.
8841   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8842   // for the namespace has the declarations that showed up in that particular
8843   // namespace definition.
8844   PushDeclContext(NamespcScope, Namespc);
8845   return Namespc;
8846 }
8847 
8848 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8849 /// is a namespace alias, returns the namespace it points to.
8850 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8851   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8852     return AD->getNamespace();
8853   return dyn_cast_or_null<NamespaceDecl>(D);
8854 }
8855 
8856 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8857 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8858 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8859   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8860   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8861   Namespc->setRBraceLoc(RBrace);
8862   PopDeclContext();
8863   if (Namespc->hasAttr<VisibilityAttr>())
8864     PopPragmaVisibility(true, RBrace);
8865 }
8866 
8867 CXXRecordDecl *Sema::getStdBadAlloc() const {
8868   return cast_or_null<CXXRecordDecl>(
8869                                   StdBadAlloc.get(Context.getExternalSource()));
8870 }
8871 
8872 EnumDecl *Sema::getStdAlignValT() const {
8873   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8874 }
8875 
8876 NamespaceDecl *Sema::getStdNamespace() const {
8877   return cast_or_null<NamespaceDecl>(
8878                                  StdNamespace.get(Context.getExternalSource()));
8879 }
8880 
8881 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8882   if (!StdExperimentalNamespaceCache) {
8883     if (auto Std = getStdNamespace()) {
8884       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8885                           SourceLocation(), LookupNamespaceName);
8886       if (!LookupQualifiedName(Result, Std) ||
8887           !(StdExperimentalNamespaceCache =
8888                 Result.getAsSingle<NamespaceDecl>()))
8889         Result.suppressDiagnostics();
8890     }
8891   }
8892   return StdExperimentalNamespaceCache;
8893 }
8894 
8895 namespace {
8896 
8897 enum UnsupportedSTLSelect {
8898   USS_InvalidMember,
8899   USS_MissingMember,
8900   USS_NonTrivial,
8901   USS_Other
8902 };
8903 
8904 struct InvalidSTLDiagnoser {
8905   Sema &S;
8906   SourceLocation Loc;
8907   QualType TyForDiags;
8908 
8909   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
8910                       const VarDecl *VD = nullptr) {
8911     {
8912       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
8913                << TyForDiags << ((int)Sel);
8914       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
8915         assert(!Name.empty());
8916         D << Name;
8917       }
8918     }
8919     if (Sel == USS_InvalidMember) {
8920       S.Diag(VD->getLocation(), diag::note_var_declared_here)
8921           << VD << VD->getSourceRange();
8922     }
8923     return QualType();
8924   }
8925 };
8926 } // namespace
8927 
8928 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
8929                                            SourceLocation Loc) {
8930   assert(getLangOpts().CPlusPlus &&
8931          "Looking for comparison category type outside of C++.");
8932 
8933   // Check if we've already successfully checked the comparison category type
8934   // before. If so, skip checking it again.
8935   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
8936   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
8937     return Info->getType();
8938 
8939   // If lookup failed
8940   if (!Info) {
8941     std::string NameForDiags = "std::";
8942     NameForDiags += ComparisonCategories::getCategoryString(Kind);
8943     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
8944         << NameForDiags;
8945     return QualType();
8946   }
8947 
8948   assert(Info->Kind == Kind);
8949   assert(Info->Record);
8950 
8951   // Update the Record decl in case we encountered a forward declaration on our
8952   // first pass. FIXME: This is a bit of a hack.
8953   if (Info->Record->hasDefinition())
8954     Info->Record = Info->Record->getDefinition();
8955 
8956   // Use an elaborated type for diagnostics which has a name containing the
8957   // prepended 'std' namespace but not any inline namespace names.
8958   QualType TyForDiags = [&]() {
8959     auto *NNS =
8960         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
8961     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
8962   }();
8963 
8964   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
8965     return QualType();
8966 
8967   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
8968 
8969   if (!Info->Record->isTriviallyCopyable())
8970     return UnsupportedSTLError(USS_NonTrivial);
8971 
8972   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
8973     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
8974     // Tolerate empty base classes.
8975     if (Base->isEmpty())
8976       continue;
8977     // Reject STL implementations which have at least one non-empty base.
8978     return UnsupportedSTLError();
8979   }
8980 
8981   // Check that the STL has implemented the types using a single integer field.
8982   // This expectation allows better codegen for builtin operators. We require:
8983   //   (1) The class has exactly one field.
8984   //   (2) The field is an integral or enumeration type.
8985   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
8986   if (std::distance(FIt, FEnd) != 1 ||
8987       !FIt->getType()->isIntegralOrEnumerationType()) {
8988     return UnsupportedSTLError();
8989   }
8990 
8991   // Build each of the require values and store them in Info.
8992   for (ComparisonCategoryResult CCR :
8993        ComparisonCategories::getPossibleResultsForType(Kind)) {
8994     StringRef MemName = ComparisonCategories::getResultString(CCR);
8995     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
8996 
8997     if (!ValInfo)
8998       return UnsupportedSTLError(USS_MissingMember, MemName);
8999 
9000     VarDecl *VD = ValInfo->VD;
9001     assert(VD && "should not be null!");
9002 
9003     // Attempt to diagnose reasons why the STL definition of this type
9004     // might be foobar, including it failing to be a constant expression.
9005     // TODO Handle more ways the lookup or result can be invalid.
9006     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9007         !VD->checkInitIsICE())
9008       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9009 
9010     // Attempt to evaluate the var decl as a constant expression and extract
9011     // the value of its first field as a ICE. If this fails, the STL
9012     // implementation is not supported.
9013     if (!ValInfo->hasValidIntValue())
9014       return UnsupportedSTLError();
9015 
9016     MarkVariableReferenced(Loc, VD);
9017   }
9018 
9019   // We've successfully built the required types and expressions. Update
9020   // the cache and return the newly cached value.
9021   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9022   return Info->getType();
9023 }
9024 
9025 /// Retrieve the special "std" namespace, which may require us to
9026 /// implicitly define the namespace.
9027 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9028   if (!StdNamespace) {
9029     // The "std" namespace has not yet been defined, so build one implicitly.
9030     StdNamespace = NamespaceDecl::Create(Context,
9031                                          Context.getTranslationUnitDecl(),
9032                                          /*Inline=*/false,
9033                                          SourceLocation(), SourceLocation(),
9034                                          &PP.getIdentifierTable().get("std"),
9035                                          /*PrevDecl=*/nullptr);
9036     getStdNamespace()->setImplicit(true);
9037   }
9038 
9039   return getStdNamespace();
9040 }
9041 
9042 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9043   assert(getLangOpts().CPlusPlus &&
9044          "Looking for std::initializer_list outside of C++.");
9045 
9046   // We're looking for implicit instantiations of
9047   // template <typename E> class std::initializer_list.
9048 
9049   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9050     return false;
9051 
9052   ClassTemplateDecl *Template = nullptr;
9053   const TemplateArgument *Arguments = nullptr;
9054 
9055   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9056 
9057     ClassTemplateSpecializationDecl *Specialization =
9058         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9059     if (!Specialization)
9060       return false;
9061 
9062     Template = Specialization->getSpecializedTemplate();
9063     Arguments = Specialization->getTemplateArgs().data();
9064   } else if (const TemplateSpecializationType *TST =
9065                  Ty->getAs<TemplateSpecializationType>()) {
9066     Template = dyn_cast_or_null<ClassTemplateDecl>(
9067         TST->getTemplateName().getAsTemplateDecl());
9068     Arguments = TST->getArgs();
9069   }
9070   if (!Template)
9071     return false;
9072 
9073   if (!StdInitializerList) {
9074     // Haven't recognized std::initializer_list yet, maybe this is it.
9075     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9076     if (TemplateClass->getIdentifier() !=
9077             &PP.getIdentifierTable().get("initializer_list") ||
9078         !getStdNamespace()->InEnclosingNamespaceSetOf(
9079             TemplateClass->getDeclContext()))
9080       return false;
9081     // This is a template called std::initializer_list, but is it the right
9082     // template?
9083     TemplateParameterList *Params = Template->getTemplateParameters();
9084     if (Params->getMinRequiredArguments() != 1)
9085       return false;
9086     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9087       return false;
9088 
9089     // It's the right template.
9090     StdInitializerList = Template;
9091   }
9092 
9093   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9094     return false;
9095 
9096   // This is an instance of std::initializer_list. Find the argument type.
9097   if (Element)
9098     *Element = Arguments[0].getAsType();
9099   return true;
9100 }
9101 
9102 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9103   NamespaceDecl *Std = S.getStdNamespace();
9104   if (!Std) {
9105     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9106     return nullptr;
9107   }
9108 
9109   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9110                       Loc, Sema::LookupOrdinaryName);
9111   if (!S.LookupQualifiedName(Result, Std)) {
9112     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9113     return nullptr;
9114   }
9115   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9116   if (!Template) {
9117     Result.suppressDiagnostics();
9118     // We found something weird. Complain about the first thing we found.
9119     NamedDecl *Found = *Result.begin();
9120     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9121     return nullptr;
9122   }
9123 
9124   // We found some template called std::initializer_list. Now verify that it's
9125   // correct.
9126   TemplateParameterList *Params = Template->getTemplateParameters();
9127   if (Params->getMinRequiredArguments() != 1 ||
9128       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9129     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9130     return nullptr;
9131   }
9132 
9133   return Template;
9134 }
9135 
9136 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9137   if (!StdInitializerList) {
9138     StdInitializerList = LookupStdInitializerList(*this, Loc);
9139     if (!StdInitializerList)
9140       return QualType();
9141   }
9142 
9143   TemplateArgumentListInfo Args(Loc, Loc);
9144   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9145                                        Context.getTrivialTypeSourceInfo(Element,
9146                                                                         Loc)));
9147   return Context.getCanonicalType(
9148       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9149 }
9150 
9151 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9152   // C++ [dcl.init.list]p2:
9153   //   A constructor is an initializer-list constructor if its first parameter
9154   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9155   //   std::initializer_list<E> for some type E, and either there are no other
9156   //   parameters or else all other parameters have default arguments.
9157   if (Ctor->getNumParams() < 1 ||
9158       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9159     return false;
9160 
9161   QualType ArgType = Ctor->getParamDecl(0)->getType();
9162   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9163     ArgType = RT->getPointeeType().getUnqualifiedType();
9164 
9165   return isStdInitializerList(ArgType, nullptr);
9166 }
9167 
9168 /// Determine whether a using statement is in a context where it will be
9169 /// apply in all contexts.
9170 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9171   switch (CurContext->getDeclKind()) {
9172     case Decl::TranslationUnit:
9173       return true;
9174     case Decl::LinkageSpec:
9175       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9176     default:
9177       return false;
9178   }
9179 }
9180 
9181 namespace {
9182 
9183 // Callback to only accept typo corrections that are namespaces.
9184 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9185 public:
9186   bool ValidateCandidate(const TypoCorrection &candidate) override {
9187     if (NamedDecl *ND = candidate.getCorrectionDecl())
9188       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9189     return false;
9190   }
9191 };
9192 
9193 }
9194 
9195 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9196                                        CXXScopeSpec &SS,
9197                                        SourceLocation IdentLoc,
9198                                        IdentifierInfo *Ident) {
9199   R.clear();
9200   if (TypoCorrection Corrected =
9201           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9202                         llvm::make_unique<NamespaceValidatorCCC>(),
9203                         Sema::CTK_ErrorRecovery)) {
9204     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9205       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9206       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9207                               Ident->getName().equals(CorrectedStr);
9208       S.diagnoseTypo(Corrected,
9209                      S.PDiag(diag::err_using_directive_member_suggest)
9210                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9211                      S.PDiag(diag::note_namespace_defined_here));
9212     } else {
9213       S.diagnoseTypo(Corrected,
9214                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9215                      S.PDiag(diag::note_namespace_defined_here));
9216     }
9217     R.addDecl(Corrected.getFoundDecl());
9218     return true;
9219   }
9220   return false;
9221 }
9222 
9223 Decl *Sema::ActOnUsingDirective(Scope *S,
9224                                           SourceLocation UsingLoc,
9225                                           SourceLocation NamespcLoc,
9226                                           CXXScopeSpec &SS,
9227                                           SourceLocation IdentLoc,
9228                                           IdentifierInfo *NamespcName,
9229                                           AttributeList *AttrList) {
9230   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9231   assert(NamespcName && "Invalid NamespcName.");
9232   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9233 
9234   // This can only happen along a recovery path.
9235   while (S->isTemplateParamScope())
9236     S = S->getParent();
9237   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9238 
9239   UsingDirectiveDecl *UDir = nullptr;
9240   NestedNameSpecifier *Qualifier = nullptr;
9241   if (SS.isSet())
9242     Qualifier = SS.getScopeRep();
9243 
9244   // Lookup namespace name.
9245   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9246   LookupParsedName(R, S, &SS);
9247   if (R.isAmbiguous())
9248     return nullptr;
9249 
9250   if (R.empty()) {
9251     R.clear();
9252     // Allow "using namespace std;" or "using namespace ::std;" even if
9253     // "std" hasn't been defined yet, for GCC compatibility.
9254     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9255         NamespcName->isStr("std")) {
9256       Diag(IdentLoc, diag::ext_using_undefined_std);
9257       R.addDecl(getOrCreateStdNamespace());
9258       R.resolveKind();
9259     }
9260     // Otherwise, attempt typo correction.
9261     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9262   }
9263 
9264   if (!R.empty()) {
9265     NamedDecl *Named = R.getRepresentativeDecl();
9266     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9267     assert(NS && "expected namespace decl");
9268 
9269     // The use of a nested name specifier may trigger deprecation warnings.
9270     DiagnoseUseOfDecl(Named, IdentLoc);
9271 
9272     // C++ [namespace.udir]p1:
9273     //   A using-directive specifies that the names in the nominated
9274     //   namespace can be used in the scope in which the
9275     //   using-directive appears after the using-directive. During
9276     //   unqualified name lookup (3.4.1), the names appear as if they
9277     //   were declared in the nearest enclosing namespace which
9278     //   contains both the using-directive and the nominated
9279     //   namespace. [Note: in this context, "contains" means "contains
9280     //   directly or indirectly". ]
9281 
9282     // Find enclosing context containing both using-directive and
9283     // nominated namespace.
9284     DeclContext *CommonAncestor = NS;
9285     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9286       CommonAncestor = CommonAncestor->getParent();
9287 
9288     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9289                                       SS.getWithLocInContext(Context),
9290                                       IdentLoc, Named, CommonAncestor);
9291 
9292     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9293         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9294       Diag(IdentLoc, diag::warn_using_directive_in_header);
9295     }
9296 
9297     PushUsingDirective(S, UDir);
9298   } else {
9299     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9300   }
9301 
9302   if (UDir)
9303     ProcessDeclAttributeList(S, UDir, AttrList);
9304 
9305   return UDir;
9306 }
9307 
9308 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9309   // If the scope has an associated entity and the using directive is at
9310   // namespace or translation unit scope, add the UsingDirectiveDecl into
9311   // its lookup structure so qualified name lookup can find it.
9312   DeclContext *Ctx = S->getEntity();
9313   if (Ctx && !Ctx->isFunctionOrMethod())
9314     Ctx->addDecl(UDir);
9315   else
9316     // Otherwise, it is at block scope. The using-directives will affect lookup
9317     // only to the end of the scope.
9318     S->PushUsingDirective(UDir);
9319 }
9320 
9321 
9322 Decl *Sema::ActOnUsingDeclaration(Scope *S,
9323                                   AccessSpecifier AS,
9324                                   SourceLocation UsingLoc,
9325                                   SourceLocation TypenameLoc,
9326                                   CXXScopeSpec &SS,
9327                                   UnqualifiedId &Name,
9328                                   SourceLocation EllipsisLoc,
9329                                   AttributeList *AttrList) {
9330   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9331 
9332   if (SS.isEmpty()) {
9333     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
9334     return nullptr;
9335   }
9336 
9337   switch (Name.getKind()) {
9338   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9339   case UnqualifiedIdKind::IK_Identifier:
9340   case UnqualifiedIdKind::IK_OperatorFunctionId:
9341   case UnqualifiedIdKind::IK_LiteralOperatorId:
9342   case UnqualifiedIdKind::IK_ConversionFunctionId:
9343     break;
9344 
9345   case UnqualifiedIdKind::IK_ConstructorName:
9346   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9347     // C++11 inheriting constructors.
9348     Diag(Name.getLocStart(),
9349          getLangOpts().CPlusPlus11 ?
9350            diag::warn_cxx98_compat_using_decl_constructor :
9351            diag::err_using_decl_constructor)
9352       << SS.getRange();
9353 
9354     if (getLangOpts().CPlusPlus11) break;
9355 
9356     return nullptr;
9357 
9358   case UnqualifiedIdKind::IK_DestructorName:
9359     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9360       << SS.getRange();
9361     return nullptr;
9362 
9363   case UnqualifiedIdKind::IK_TemplateId:
9364     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9365       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9366     return nullptr;
9367 
9368   case UnqualifiedIdKind::IK_DeductionGuideName:
9369     llvm_unreachable("cannot parse qualified deduction guide name");
9370   }
9371 
9372   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9373   DeclarationName TargetName = TargetNameInfo.getName();
9374   if (!TargetName)
9375     return nullptr;
9376 
9377   // Warn about access declarations.
9378   if (UsingLoc.isInvalid()) {
9379     Diag(Name.getLocStart(),
9380          getLangOpts().CPlusPlus11 ? diag::err_access_decl
9381                                    : diag::warn_access_decl_deprecated)
9382       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9383   }
9384 
9385   if (EllipsisLoc.isInvalid()) {
9386     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9387         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9388       return nullptr;
9389   } else {
9390     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9391         !TargetNameInfo.containsUnexpandedParameterPack()) {
9392       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9393         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9394       EllipsisLoc = SourceLocation();
9395     }
9396   }
9397 
9398   NamedDecl *UD =
9399       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9400                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9401                             /*IsInstantiation*/false);
9402   if (UD)
9403     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9404 
9405   return UD;
9406 }
9407 
9408 /// Determine whether a using declaration considers the given
9409 /// declarations as "equivalent", e.g., if they are redeclarations of
9410 /// the same entity or are both typedefs of the same type.
9411 static bool
9412 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9413   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9414     return true;
9415 
9416   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9417     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9418       return Context.hasSameType(TD1->getUnderlyingType(),
9419                                  TD2->getUnderlyingType());
9420 
9421   return false;
9422 }
9423 
9424 
9425 /// Determines whether to create a using shadow decl for a particular
9426 /// decl, given the set of decls existing prior to this using lookup.
9427 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9428                                 const LookupResult &Previous,
9429                                 UsingShadowDecl *&PrevShadow) {
9430   // Diagnose finding a decl which is not from a base class of the
9431   // current class.  We do this now because there are cases where this
9432   // function will silently decide not to build a shadow decl, which
9433   // will pre-empt further diagnostics.
9434   //
9435   // We don't need to do this in C++11 because we do the check once on
9436   // the qualifier.
9437   //
9438   // FIXME: diagnose the following if we care enough:
9439   //   struct A { int foo; };
9440   //   struct B : A { using A::foo; };
9441   //   template <class T> struct C : A {};
9442   //   template <class T> struct D : C<T> { using B::foo; } // <---
9443   // This is invalid (during instantiation) in C++03 because B::foo
9444   // resolves to the using decl in B, which is not a base class of D<T>.
9445   // We can't diagnose it immediately because C<T> is an unknown
9446   // specialization.  The UsingShadowDecl in D<T> then points directly
9447   // to A::foo, which will look well-formed when we instantiate.
9448   // The right solution is to not collapse the shadow-decl chain.
9449   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9450     DeclContext *OrigDC = Orig->getDeclContext();
9451 
9452     // Handle enums and anonymous structs.
9453     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9454     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9455     while (OrigRec->isAnonymousStructOrUnion())
9456       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9457 
9458     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9459       if (OrigDC == CurContext) {
9460         Diag(Using->getLocation(),
9461              diag::err_using_decl_nested_name_specifier_is_current_class)
9462           << Using->getQualifierLoc().getSourceRange();
9463         Diag(Orig->getLocation(), diag::note_using_decl_target);
9464         Using->setInvalidDecl();
9465         return true;
9466       }
9467 
9468       Diag(Using->getQualifierLoc().getBeginLoc(),
9469            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9470         << Using->getQualifier()
9471         << cast<CXXRecordDecl>(CurContext)
9472         << Using->getQualifierLoc().getSourceRange();
9473       Diag(Orig->getLocation(), diag::note_using_decl_target);
9474       Using->setInvalidDecl();
9475       return true;
9476     }
9477   }
9478 
9479   if (Previous.empty()) return false;
9480 
9481   NamedDecl *Target = Orig;
9482   if (isa<UsingShadowDecl>(Target))
9483     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9484 
9485   // If the target happens to be one of the previous declarations, we
9486   // don't have a conflict.
9487   //
9488   // FIXME: but we might be increasing its access, in which case we
9489   // should redeclare it.
9490   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9491   bool FoundEquivalentDecl = false;
9492   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9493          I != E; ++I) {
9494     NamedDecl *D = (*I)->getUnderlyingDecl();
9495     // We can have UsingDecls in our Previous results because we use the same
9496     // LookupResult for checking whether the UsingDecl itself is a valid
9497     // redeclaration.
9498     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9499       continue;
9500 
9501     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9502       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9503         PrevShadow = Shadow;
9504       FoundEquivalentDecl = true;
9505     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9506       // We don't conflict with an existing using shadow decl of an equivalent
9507       // declaration, but we're not a redeclaration of it.
9508       FoundEquivalentDecl = true;
9509     }
9510 
9511     if (isVisible(D))
9512       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9513   }
9514 
9515   if (FoundEquivalentDecl)
9516     return false;
9517 
9518   if (FunctionDecl *FD = Target->getAsFunction()) {
9519     NamedDecl *OldDecl = nullptr;
9520     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9521                           /*IsForUsingDecl*/ true)) {
9522     case Ovl_Overload:
9523       return false;
9524 
9525     case Ovl_NonFunction:
9526       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9527       break;
9528 
9529     // We found a decl with the exact signature.
9530     case Ovl_Match:
9531       // If we're in a record, we want to hide the target, so we
9532       // return true (without a diagnostic) to tell the caller not to
9533       // build a shadow decl.
9534       if (CurContext->isRecord())
9535         return true;
9536 
9537       // If we're not in a record, this is an error.
9538       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9539       break;
9540     }
9541 
9542     Diag(Target->getLocation(), diag::note_using_decl_target);
9543     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9544     Using->setInvalidDecl();
9545     return true;
9546   }
9547 
9548   // Target is not a function.
9549 
9550   if (isa<TagDecl>(Target)) {
9551     // No conflict between a tag and a non-tag.
9552     if (!Tag) return false;
9553 
9554     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9555     Diag(Target->getLocation(), diag::note_using_decl_target);
9556     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9557     Using->setInvalidDecl();
9558     return true;
9559   }
9560 
9561   // No conflict between a tag and a non-tag.
9562   if (!NonTag) return false;
9563 
9564   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9565   Diag(Target->getLocation(), diag::note_using_decl_target);
9566   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9567   Using->setInvalidDecl();
9568   return true;
9569 }
9570 
9571 /// Determine whether a direct base class is a virtual base class.
9572 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9573   if (!Derived->getNumVBases())
9574     return false;
9575   for (auto &B : Derived->bases())
9576     if (B.getType()->getAsCXXRecordDecl() == Base)
9577       return B.isVirtual();
9578   llvm_unreachable("not a direct base class");
9579 }
9580 
9581 /// Builds a shadow declaration corresponding to a 'using' declaration.
9582 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9583                                             UsingDecl *UD,
9584                                             NamedDecl *Orig,
9585                                             UsingShadowDecl *PrevDecl) {
9586   // If we resolved to another shadow declaration, just coalesce them.
9587   NamedDecl *Target = Orig;
9588   if (isa<UsingShadowDecl>(Target)) {
9589     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9590     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9591   }
9592 
9593   NamedDecl *NonTemplateTarget = Target;
9594   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9595     NonTemplateTarget = TargetTD->getTemplatedDecl();
9596 
9597   UsingShadowDecl *Shadow;
9598   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9599     bool IsVirtualBase =
9600         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9601                             UD->getQualifier()->getAsRecordDecl());
9602     Shadow = ConstructorUsingShadowDecl::Create(
9603         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9604   } else {
9605     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9606                                      Target);
9607   }
9608   UD->addShadowDecl(Shadow);
9609 
9610   Shadow->setAccess(UD->getAccess());
9611   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9612     Shadow->setInvalidDecl();
9613 
9614   Shadow->setPreviousDecl(PrevDecl);
9615 
9616   if (S)
9617     PushOnScopeChains(Shadow, S);
9618   else
9619     CurContext->addDecl(Shadow);
9620 
9621 
9622   return Shadow;
9623 }
9624 
9625 /// Hides a using shadow declaration.  This is required by the current
9626 /// using-decl implementation when a resolvable using declaration in a
9627 /// class is followed by a declaration which would hide or override
9628 /// one or more of the using decl's targets; for example:
9629 ///
9630 ///   struct Base { void foo(int); };
9631 ///   struct Derived : Base {
9632 ///     using Base::foo;
9633 ///     void foo(int);
9634 ///   };
9635 ///
9636 /// The governing language is C++03 [namespace.udecl]p12:
9637 ///
9638 ///   When a using-declaration brings names from a base class into a
9639 ///   derived class scope, member functions in the derived class
9640 ///   override and/or hide member functions with the same name and
9641 ///   parameter types in a base class (rather than conflicting).
9642 ///
9643 /// There are two ways to implement this:
9644 ///   (1) optimistically create shadow decls when they're not hidden
9645 ///       by existing declarations, or
9646 ///   (2) don't create any shadow decls (or at least don't make them
9647 ///       visible) until we've fully parsed/instantiated the class.
9648 /// The problem with (1) is that we might have to retroactively remove
9649 /// a shadow decl, which requires several O(n) operations because the
9650 /// decl structures are (very reasonably) not designed for removal.
9651 /// (2) avoids this but is very fiddly and phase-dependent.
9652 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9653   if (Shadow->getDeclName().getNameKind() ==
9654         DeclarationName::CXXConversionFunctionName)
9655     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9656 
9657   // Remove it from the DeclContext...
9658   Shadow->getDeclContext()->removeDecl(Shadow);
9659 
9660   // ...and the scope, if applicable...
9661   if (S) {
9662     S->RemoveDecl(Shadow);
9663     IdResolver.RemoveDecl(Shadow);
9664   }
9665 
9666   // ...and the using decl.
9667   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9668 
9669   // TODO: complain somehow if Shadow was used.  It shouldn't
9670   // be possible for this to happen, because...?
9671 }
9672 
9673 /// Find the base specifier for a base class with the given type.
9674 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9675                                                 QualType DesiredBase,
9676                                                 bool &AnyDependentBases) {
9677   // Check whether the named type is a direct base class.
9678   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9679   for (auto &Base : Derived->bases()) {
9680     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9681     if (CanonicalDesiredBase == BaseType)
9682       return &Base;
9683     if (BaseType->isDependentType())
9684       AnyDependentBases = true;
9685   }
9686   return nullptr;
9687 }
9688 
9689 namespace {
9690 class UsingValidatorCCC : public CorrectionCandidateCallback {
9691 public:
9692   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9693                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9694       : HasTypenameKeyword(HasTypenameKeyword),
9695         IsInstantiation(IsInstantiation), OldNNS(NNS),
9696         RequireMemberOf(RequireMemberOf) {}
9697 
9698   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9699     NamedDecl *ND = Candidate.getCorrectionDecl();
9700 
9701     // Keywords are not valid here.
9702     if (!ND || isa<NamespaceDecl>(ND))
9703       return false;
9704 
9705     // Completely unqualified names are invalid for a 'using' declaration.
9706     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9707       return false;
9708 
9709     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9710     // reject.
9711 
9712     if (RequireMemberOf) {
9713       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9714       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9715         // No-one ever wants a using-declaration to name an injected-class-name
9716         // of a base class, unless they're declaring an inheriting constructor.
9717         ASTContext &Ctx = ND->getASTContext();
9718         if (!Ctx.getLangOpts().CPlusPlus11)
9719           return false;
9720         QualType FoundType = Ctx.getRecordType(FoundRecord);
9721 
9722         // Check that the injected-class-name is named as a member of its own
9723         // type; we don't want to suggest 'using Derived::Base;', since that
9724         // means something else.
9725         NestedNameSpecifier *Specifier =
9726             Candidate.WillReplaceSpecifier()
9727                 ? Candidate.getCorrectionSpecifier()
9728                 : OldNNS;
9729         if (!Specifier->getAsType() ||
9730             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9731           return false;
9732 
9733         // Check that this inheriting constructor declaration actually names a
9734         // direct base class of the current class.
9735         bool AnyDependentBases = false;
9736         if (!findDirectBaseWithType(RequireMemberOf,
9737                                     Ctx.getRecordType(FoundRecord),
9738                                     AnyDependentBases) &&
9739             !AnyDependentBases)
9740           return false;
9741       } else {
9742         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9743         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9744           return false;
9745 
9746         // FIXME: Check that the base class member is accessible?
9747       }
9748     } else {
9749       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9750       if (FoundRecord && FoundRecord->isInjectedClassName())
9751         return false;
9752     }
9753 
9754     if (isa<TypeDecl>(ND))
9755       return HasTypenameKeyword || !IsInstantiation;
9756 
9757     return !HasTypenameKeyword;
9758   }
9759 
9760 private:
9761   bool HasTypenameKeyword;
9762   bool IsInstantiation;
9763   NestedNameSpecifier *OldNNS;
9764   CXXRecordDecl *RequireMemberOf;
9765 };
9766 } // end anonymous namespace
9767 
9768 /// Builds a using declaration.
9769 ///
9770 /// \param IsInstantiation - Whether this call arises from an
9771 ///   instantiation of an unresolved using declaration.  We treat
9772 ///   the lookup differently for these declarations.
9773 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9774                                        SourceLocation UsingLoc,
9775                                        bool HasTypenameKeyword,
9776                                        SourceLocation TypenameLoc,
9777                                        CXXScopeSpec &SS,
9778                                        DeclarationNameInfo NameInfo,
9779                                        SourceLocation EllipsisLoc,
9780                                        AttributeList *AttrList,
9781                                        bool IsInstantiation) {
9782   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9783   SourceLocation IdentLoc = NameInfo.getLoc();
9784   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9785 
9786   // FIXME: We ignore attributes for now.
9787 
9788   // For an inheriting constructor declaration, the name of the using
9789   // declaration is the name of a constructor in this class, not in the
9790   // base class.
9791   DeclarationNameInfo UsingName = NameInfo;
9792   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9793     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9794       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9795           Context.getCanonicalType(Context.getRecordType(RD))));
9796 
9797   // Do the redeclaration lookup in the current scope.
9798   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9799                         ForVisibleRedeclaration);
9800   Previous.setHideTags(false);
9801   if (S) {
9802     LookupName(Previous, S);
9803 
9804     // It is really dumb that we have to do this.
9805     LookupResult::Filter F = Previous.makeFilter();
9806     while (F.hasNext()) {
9807       NamedDecl *D = F.next();
9808       if (!isDeclInScope(D, CurContext, S))
9809         F.erase();
9810       // If we found a local extern declaration that's not ordinarily visible,
9811       // and this declaration is being added to a non-block scope, ignore it.
9812       // We're only checking for scope conflicts here, not also for violations
9813       // of the linkage rules.
9814       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9815                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9816         F.erase();
9817     }
9818     F.done();
9819   } else {
9820     assert(IsInstantiation && "no scope in non-instantiation");
9821     if (CurContext->isRecord())
9822       LookupQualifiedName(Previous, CurContext);
9823     else {
9824       // No redeclaration check is needed here; in non-member contexts we
9825       // diagnosed all possible conflicts with other using-declarations when
9826       // building the template:
9827       //
9828       // For a dependent non-type using declaration, the only valid case is
9829       // if we instantiate to a single enumerator. We check for conflicts
9830       // between shadow declarations we introduce, and we check in the template
9831       // definition for conflicts between a non-type using declaration and any
9832       // other declaration, which together covers all cases.
9833       //
9834       // A dependent typename using declaration will never successfully
9835       // instantiate, since it will always name a class member, so we reject
9836       // that in the template definition.
9837     }
9838   }
9839 
9840   // Check for invalid redeclarations.
9841   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9842                                   SS, IdentLoc, Previous))
9843     return nullptr;
9844 
9845   // Check for bad qualifiers.
9846   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9847                               IdentLoc))
9848     return nullptr;
9849 
9850   DeclContext *LookupContext = computeDeclContext(SS);
9851   NamedDecl *D;
9852   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9853   if (!LookupContext || EllipsisLoc.isValid()) {
9854     if (HasTypenameKeyword) {
9855       // FIXME: not all declaration name kinds are legal here
9856       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9857                                               UsingLoc, TypenameLoc,
9858                                               QualifierLoc,
9859                                               IdentLoc, NameInfo.getName(),
9860                                               EllipsisLoc);
9861     } else {
9862       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9863                                            QualifierLoc, NameInfo, EllipsisLoc);
9864     }
9865     D->setAccess(AS);
9866     CurContext->addDecl(D);
9867     return D;
9868   }
9869 
9870   auto Build = [&](bool Invalid) {
9871     UsingDecl *UD =
9872         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9873                           UsingName, HasTypenameKeyword);
9874     UD->setAccess(AS);
9875     CurContext->addDecl(UD);
9876     UD->setInvalidDecl(Invalid);
9877     return UD;
9878   };
9879   auto BuildInvalid = [&]{ return Build(true); };
9880   auto BuildValid = [&]{ return Build(false); };
9881 
9882   if (RequireCompleteDeclContext(SS, LookupContext))
9883     return BuildInvalid();
9884 
9885   // Look up the target name.
9886   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9887 
9888   // Unlike most lookups, we don't always want to hide tag
9889   // declarations: tag names are visible through the using declaration
9890   // even if hidden by ordinary names, *except* in a dependent context
9891   // where it's important for the sanity of two-phase lookup.
9892   if (!IsInstantiation)
9893     R.setHideTags(false);
9894 
9895   // For the purposes of this lookup, we have a base object type
9896   // equal to that of the current context.
9897   if (CurContext->isRecord()) {
9898     R.setBaseObjectType(
9899                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9900   }
9901 
9902   LookupQualifiedName(R, LookupContext);
9903 
9904   // Try to correct typos if possible. If constructor name lookup finds no
9905   // results, that means the named class has no explicit constructors, and we
9906   // suppressed declaring implicit ones (probably because it's dependent or
9907   // invalid).
9908   if (R.empty() &&
9909       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9910     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9911     // it will believe that glibc provides a ::gets in cases where it does not,
9912     // and will try to pull it into namespace std with a using-declaration.
9913     // Just ignore the using-declaration in that case.
9914     auto *II = NameInfo.getName().getAsIdentifierInfo();
9915     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9916         CurContext->isStdNamespace() &&
9917         isa<TranslationUnitDecl>(LookupContext) &&
9918         getSourceManager().isInSystemHeader(UsingLoc))
9919       return nullptr;
9920     if (TypoCorrection Corrected = CorrectTypo(
9921             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9922             llvm::make_unique<UsingValidatorCCC>(
9923                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9924                 dyn_cast<CXXRecordDecl>(CurContext)),
9925             CTK_ErrorRecovery)) {
9926       // We reject candidates where DroppedSpecifier == true, hence the
9927       // literal '0' below.
9928       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9929                                 << NameInfo.getName() << LookupContext << 0
9930                                 << SS.getRange());
9931 
9932       // If we picked a correction with no attached Decl we can't do anything
9933       // useful with it, bail out.
9934       NamedDecl *ND = Corrected.getCorrectionDecl();
9935       if (!ND)
9936         return BuildInvalid();
9937 
9938       // If we corrected to an inheriting constructor, handle it as one.
9939       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9940       if (RD && RD->isInjectedClassName()) {
9941         // The parent of the injected class name is the class itself.
9942         RD = cast<CXXRecordDecl>(RD->getParent());
9943 
9944         // Fix up the information we'll use to build the using declaration.
9945         if (Corrected.WillReplaceSpecifier()) {
9946           NestedNameSpecifierLocBuilder Builder;
9947           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9948                               QualifierLoc.getSourceRange());
9949           QualifierLoc = Builder.getWithLocInContext(Context);
9950         }
9951 
9952         // In this case, the name we introduce is the name of a derived class
9953         // constructor.
9954         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9955         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9956             Context.getCanonicalType(Context.getRecordType(CurClass))));
9957         UsingName.setNamedTypeInfo(nullptr);
9958         for (auto *Ctor : LookupConstructors(RD))
9959           R.addDecl(Ctor);
9960         R.resolveKind();
9961       } else {
9962         // FIXME: Pick up all the declarations if we found an overloaded
9963         // function.
9964         UsingName.setName(ND->getDeclName());
9965         R.addDecl(ND);
9966       }
9967     } else {
9968       Diag(IdentLoc, diag::err_no_member)
9969         << NameInfo.getName() << LookupContext << SS.getRange();
9970       return BuildInvalid();
9971     }
9972   }
9973 
9974   if (R.isAmbiguous())
9975     return BuildInvalid();
9976 
9977   if (HasTypenameKeyword) {
9978     // If we asked for a typename and got a non-type decl, error out.
9979     if (!R.getAsSingle<TypeDecl>()) {
9980       Diag(IdentLoc, diag::err_using_typename_non_type);
9981       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9982         Diag((*I)->getUnderlyingDecl()->getLocation(),
9983              diag::note_using_decl_target);
9984       return BuildInvalid();
9985     }
9986   } else {
9987     // If we asked for a non-typename and we got a type, error out,
9988     // but only if this is an instantiation of an unresolved using
9989     // decl.  Otherwise just silently find the type name.
9990     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9991       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9992       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9993       return BuildInvalid();
9994     }
9995   }
9996 
9997   // C++14 [namespace.udecl]p6:
9998   // A using-declaration shall not name a namespace.
9999   if (R.getAsSingle<NamespaceDecl>()) {
10000     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10001       << SS.getRange();
10002     return BuildInvalid();
10003   }
10004 
10005   // C++14 [namespace.udecl]p7:
10006   // A using-declaration shall not name a scoped enumerator.
10007   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10008     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10009       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10010         << SS.getRange();
10011       return BuildInvalid();
10012     }
10013   }
10014 
10015   UsingDecl *UD = BuildValid();
10016 
10017   // Some additional rules apply to inheriting constructors.
10018   if (UsingName.getName().getNameKind() ==
10019         DeclarationName::CXXConstructorName) {
10020     // Suppress access diagnostics; the access check is instead performed at the
10021     // point of use for an inheriting constructor.
10022     R.suppressDiagnostics();
10023     if (CheckInheritingConstructorUsingDecl(UD))
10024       return UD;
10025   }
10026 
10027   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10028     UsingShadowDecl *PrevDecl = nullptr;
10029     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10030       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10031   }
10032 
10033   return UD;
10034 }
10035 
10036 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10037                                     ArrayRef<NamedDecl *> Expansions) {
10038   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10039          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10040          isa<UsingPackDecl>(InstantiatedFrom));
10041 
10042   auto *UPD =
10043       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10044   UPD->setAccess(InstantiatedFrom->getAccess());
10045   CurContext->addDecl(UPD);
10046   return UPD;
10047 }
10048 
10049 /// Additional checks for a using declaration referring to a constructor name.
10050 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10051   assert(!UD->hasTypename() && "expecting a constructor name");
10052 
10053   const Type *SourceType = UD->getQualifier()->getAsType();
10054   assert(SourceType &&
10055          "Using decl naming constructor doesn't have type in scope spec.");
10056   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10057 
10058   // Check whether the named type is a direct base class.
10059   bool AnyDependentBases = false;
10060   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10061                                       AnyDependentBases);
10062   if (!Base && !AnyDependentBases) {
10063     Diag(UD->getUsingLoc(),
10064          diag::err_using_decl_constructor_not_in_direct_base)
10065       << UD->getNameInfo().getSourceRange()
10066       << QualType(SourceType, 0) << TargetClass;
10067     UD->setInvalidDecl();
10068     return true;
10069   }
10070 
10071   if (Base)
10072     Base->setInheritConstructors();
10073 
10074   return false;
10075 }
10076 
10077 /// Checks that the given using declaration is not an invalid
10078 /// redeclaration.  Note that this is checking only for the using decl
10079 /// itself, not for any ill-formedness among the UsingShadowDecls.
10080 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10081                                        bool HasTypenameKeyword,
10082                                        const CXXScopeSpec &SS,
10083                                        SourceLocation NameLoc,
10084                                        const LookupResult &Prev) {
10085   NestedNameSpecifier *Qual = SS.getScopeRep();
10086 
10087   // C++03 [namespace.udecl]p8:
10088   // C++0x [namespace.udecl]p10:
10089   //   A using-declaration is a declaration and can therefore be used
10090   //   repeatedly where (and only where) multiple declarations are
10091   //   allowed.
10092   //
10093   // That's in non-member contexts.
10094   if (!CurContext->getRedeclContext()->isRecord()) {
10095     // A dependent qualifier outside a class can only ever resolve to an
10096     // enumeration type. Therefore it conflicts with any other non-type
10097     // declaration in the same scope.
10098     // FIXME: How should we check for dependent type-type conflicts at block
10099     // scope?
10100     if (Qual->isDependent() && !HasTypenameKeyword) {
10101       for (auto *D : Prev) {
10102         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10103           bool OldCouldBeEnumerator =
10104               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10105           Diag(NameLoc,
10106                OldCouldBeEnumerator ? diag::err_redefinition
10107                                     : diag::err_redefinition_different_kind)
10108               << Prev.getLookupName();
10109           Diag(D->getLocation(), diag::note_previous_definition);
10110           return true;
10111         }
10112       }
10113     }
10114     return false;
10115   }
10116 
10117   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10118     NamedDecl *D = *I;
10119 
10120     bool DTypename;
10121     NestedNameSpecifier *DQual;
10122     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10123       DTypename = UD->hasTypename();
10124       DQual = UD->getQualifier();
10125     } else if (UnresolvedUsingValueDecl *UD
10126                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10127       DTypename = false;
10128       DQual = UD->getQualifier();
10129     } else if (UnresolvedUsingTypenameDecl *UD
10130                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10131       DTypename = true;
10132       DQual = UD->getQualifier();
10133     } else continue;
10134 
10135     // using decls differ if one says 'typename' and the other doesn't.
10136     // FIXME: non-dependent using decls?
10137     if (HasTypenameKeyword != DTypename) continue;
10138 
10139     // using decls differ if they name different scopes (but note that
10140     // template instantiation can cause this check to trigger when it
10141     // didn't before instantiation).
10142     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10143         Context.getCanonicalNestedNameSpecifier(DQual))
10144       continue;
10145 
10146     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10147     Diag(D->getLocation(), diag::note_using_decl) << 1;
10148     return true;
10149   }
10150 
10151   return false;
10152 }
10153 
10154 
10155 /// Checks that the given nested-name qualifier used in a using decl
10156 /// in the current context is appropriately related to the current
10157 /// scope.  If an error is found, diagnoses it and returns true.
10158 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10159                                    bool HasTypename,
10160                                    const CXXScopeSpec &SS,
10161                                    const DeclarationNameInfo &NameInfo,
10162                                    SourceLocation NameLoc) {
10163   DeclContext *NamedContext = computeDeclContext(SS);
10164 
10165   if (!CurContext->isRecord()) {
10166     // C++03 [namespace.udecl]p3:
10167     // C++0x [namespace.udecl]p8:
10168     //   A using-declaration for a class member shall be a member-declaration.
10169 
10170     // If we weren't able to compute a valid scope, it might validly be a
10171     // dependent class scope or a dependent enumeration unscoped scope. If
10172     // we have a 'typename' keyword, the scope must resolve to a class type.
10173     if ((HasTypename && !NamedContext) ||
10174         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10175       auto *RD = NamedContext
10176                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10177                      : nullptr;
10178       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10179         RD = nullptr;
10180 
10181       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10182         << SS.getRange();
10183 
10184       // If we have a complete, non-dependent source type, try to suggest a
10185       // way to get the same effect.
10186       if (!RD)
10187         return true;
10188 
10189       // Find what this using-declaration was referring to.
10190       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10191       R.setHideTags(false);
10192       R.suppressDiagnostics();
10193       LookupQualifiedName(R, RD);
10194 
10195       if (R.getAsSingle<TypeDecl>()) {
10196         if (getLangOpts().CPlusPlus11) {
10197           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10198           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10199             << 0 // alias declaration
10200             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10201                                           NameInfo.getName().getAsString() +
10202                                               " = ");
10203         } else {
10204           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10205           SourceLocation InsertLoc =
10206               getLocForEndOfToken(NameInfo.getLocEnd());
10207           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10208             << 1 // typedef declaration
10209             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10210             << FixItHint::CreateInsertion(
10211                    InsertLoc, " " + NameInfo.getName().getAsString());
10212         }
10213       } else if (R.getAsSingle<VarDecl>()) {
10214         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10215         // repeating the type of the static data member here.
10216         FixItHint FixIt;
10217         if (getLangOpts().CPlusPlus11) {
10218           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10219           FixIt = FixItHint::CreateReplacement(
10220               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10221         }
10222 
10223         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10224           << 2 // reference declaration
10225           << FixIt;
10226       } else if (R.getAsSingle<EnumConstantDecl>()) {
10227         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10228         // repeating the type of the enumeration here, and we can't do so if
10229         // the type is anonymous.
10230         FixItHint FixIt;
10231         if (getLangOpts().CPlusPlus11) {
10232           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10233           FixIt = FixItHint::CreateReplacement(
10234               UsingLoc,
10235               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10236         }
10237 
10238         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10239           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10240           << FixIt;
10241       }
10242       return true;
10243     }
10244 
10245     // Otherwise, this might be valid.
10246     return false;
10247   }
10248 
10249   // The current scope is a record.
10250 
10251   // If the named context is dependent, we can't decide much.
10252   if (!NamedContext) {
10253     // FIXME: in C++0x, we can diagnose if we can prove that the
10254     // nested-name-specifier does not refer to a base class, which is
10255     // still possible in some cases.
10256 
10257     // Otherwise we have to conservatively report that things might be
10258     // okay.
10259     return false;
10260   }
10261 
10262   if (!NamedContext->isRecord()) {
10263     // Ideally this would point at the last name in the specifier,
10264     // but we don't have that level of source info.
10265     Diag(SS.getRange().getBegin(),
10266          diag::err_using_decl_nested_name_specifier_is_not_class)
10267       << SS.getScopeRep() << SS.getRange();
10268     return true;
10269   }
10270 
10271   if (!NamedContext->isDependentContext() &&
10272       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10273     return true;
10274 
10275   if (getLangOpts().CPlusPlus11) {
10276     // C++11 [namespace.udecl]p3:
10277     //   In a using-declaration used as a member-declaration, the
10278     //   nested-name-specifier shall name a base class of the class
10279     //   being defined.
10280 
10281     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10282                                  cast<CXXRecordDecl>(NamedContext))) {
10283       if (CurContext == NamedContext) {
10284         Diag(NameLoc,
10285              diag::err_using_decl_nested_name_specifier_is_current_class)
10286           << SS.getRange();
10287         return true;
10288       }
10289 
10290       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10291         Diag(SS.getRange().getBegin(),
10292              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10293           << SS.getScopeRep()
10294           << cast<CXXRecordDecl>(CurContext)
10295           << SS.getRange();
10296       }
10297       return true;
10298     }
10299 
10300     return false;
10301   }
10302 
10303   // C++03 [namespace.udecl]p4:
10304   //   A using-declaration used as a member-declaration shall refer
10305   //   to a member of a base class of the class being defined [etc.].
10306 
10307   // Salient point: SS doesn't have to name a base class as long as
10308   // lookup only finds members from base classes.  Therefore we can
10309   // diagnose here only if we can prove that that can't happen,
10310   // i.e. if the class hierarchies provably don't intersect.
10311 
10312   // TODO: it would be nice if "definitely valid" results were cached
10313   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10314   // need to be repeated.
10315 
10316   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10317   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10318     Bases.insert(Base);
10319     return true;
10320   };
10321 
10322   // Collect all bases. Return false if we find a dependent base.
10323   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10324     return false;
10325 
10326   // Returns true if the base is dependent or is one of the accumulated base
10327   // classes.
10328   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10329     return !Bases.count(Base);
10330   };
10331 
10332   // Return false if the class has a dependent base or if it or one
10333   // of its bases is present in the base set of the current context.
10334   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10335       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10336     return false;
10337 
10338   Diag(SS.getRange().getBegin(),
10339        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10340     << SS.getScopeRep()
10341     << cast<CXXRecordDecl>(CurContext)
10342     << SS.getRange();
10343 
10344   return true;
10345 }
10346 
10347 Decl *Sema::ActOnAliasDeclaration(Scope *S,
10348                                   AccessSpecifier AS,
10349                                   MultiTemplateParamsArg TemplateParamLists,
10350                                   SourceLocation UsingLoc,
10351                                   UnqualifiedId &Name,
10352                                   AttributeList *AttrList,
10353                                   TypeResult Type,
10354                                   Decl *DeclFromDeclSpec) {
10355   // Skip up to the relevant declaration scope.
10356   while (S->isTemplateParamScope())
10357     S = S->getParent();
10358   assert((S->getFlags() & Scope::DeclScope) &&
10359          "got alias-declaration outside of declaration scope");
10360 
10361   if (Type.isInvalid())
10362     return nullptr;
10363 
10364   bool Invalid = false;
10365   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10366   TypeSourceInfo *TInfo = nullptr;
10367   GetTypeFromParser(Type.get(), &TInfo);
10368 
10369   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10370     return nullptr;
10371 
10372   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10373                                       UPPC_DeclarationType)) {
10374     Invalid = true;
10375     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10376                                              TInfo->getTypeLoc().getBeginLoc());
10377   }
10378 
10379   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10380                         TemplateParamLists.size()
10381                             ? forRedeclarationInCurContext()
10382                             : ForVisibleRedeclaration);
10383   LookupName(Previous, S);
10384 
10385   // Warn about shadowing the name of a template parameter.
10386   if (Previous.isSingleResult() &&
10387       Previous.getFoundDecl()->isTemplateParameter()) {
10388     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10389     Previous.clear();
10390   }
10391 
10392   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10393          "name in alias declaration must be an identifier");
10394   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10395                                                Name.StartLocation,
10396                                                Name.Identifier, TInfo);
10397 
10398   NewTD->setAccess(AS);
10399 
10400   if (Invalid)
10401     NewTD->setInvalidDecl();
10402 
10403   ProcessDeclAttributeList(S, NewTD, AttrList);
10404   AddPragmaAttributes(S, NewTD);
10405 
10406   CheckTypedefForVariablyModifiedType(S, NewTD);
10407   Invalid |= NewTD->isInvalidDecl();
10408 
10409   bool Redeclaration = false;
10410 
10411   NamedDecl *NewND;
10412   if (TemplateParamLists.size()) {
10413     TypeAliasTemplateDecl *OldDecl = nullptr;
10414     TemplateParameterList *OldTemplateParams = nullptr;
10415 
10416     if (TemplateParamLists.size() != 1) {
10417       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10418         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10419          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10420     }
10421     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10422 
10423     // Check that we can declare a template here.
10424     if (CheckTemplateDeclScope(S, TemplateParams))
10425       return nullptr;
10426 
10427     // Only consider previous declarations in the same scope.
10428     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10429                          /*ExplicitInstantiationOrSpecialization*/false);
10430     if (!Previous.empty()) {
10431       Redeclaration = true;
10432 
10433       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10434       if (!OldDecl && !Invalid) {
10435         Diag(UsingLoc, diag::err_redefinition_different_kind)
10436           << Name.Identifier;
10437 
10438         NamedDecl *OldD = Previous.getRepresentativeDecl();
10439         if (OldD->getLocation().isValid())
10440           Diag(OldD->getLocation(), diag::note_previous_definition);
10441 
10442         Invalid = true;
10443       }
10444 
10445       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10446         if (TemplateParameterListsAreEqual(TemplateParams,
10447                                            OldDecl->getTemplateParameters(),
10448                                            /*Complain=*/true,
10449                                            TPL_TemplateMatch))
10450           OldTemplateParams = OldDecl->getTemplateParameters();
10451         else
10452           Invalid = true;
10453 
10454         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10455         if (!Invalid &&
10456             !Context.hasSameType(OldTD->getUnderlyingType(),
10457                                  NewTD->getUnderlyingType())) {
10458           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10459           // but we can't reasonably accept it.
10460           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10461             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10462           if (OldTD->getLocation().isValid())
10463             Diag(OldTD->getLocation(), diag::note_previous_definition);
10464           Invalid = true;
10465         }
10466       }
10467     }
10468 
10469     // Merge any previous default template arguments into our parameters,
10470     // and check the parameter list.
10471     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10472                                    TPC_TypeAliasTemplate))
10473       return nullptr;
10474 
10475     TypeAliasTemplateDecl *NewDecl =
10476       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10477                                     Name.Identifier, TemplateParams,
10478                                     NewTD);
10479     NewTD->setDescribedAliasTemplate(NewDecl);
10480 
10481     NewDecl->setAccess(AS);
10482 
10483     if (Invalid)
10484       NewDecl->setInvalidDecl();
10485     else if (OldDecl) {
10486       NewDecl->setPreviousDecl(OldDecl);
10487       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10488     }
10489 
10490     NewND = NewDecl;
10491   } else {
10492     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10493       setTagNameForLinkagePurposes(TD, NewTD);
10494       handleTagNumbering(TD, S);
10495     }
10496     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10497     NewND = NewTD;
10498   }
10499 
10500   PushOnScopeChains(NewND, S);
10501   ActOnDocumentableDecl(NewND);
10502   return NewND;
10503 }
10504 
10505 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10506                                    SourceLocation AliasLoc,
10507                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10508                                    SourceLocation IdentLoc,
10509                                    IdentifierInfo *Ident) {
10510 
10511   // Lookup the namespace name.
10512   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10513   LookupParsedName(R, S, &SS);
10514 
10515   if (R.isAmbiguous())
10516     return nullptr;
10517 
10518   if (R.empty()) {
10519     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10520       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10521       return nullptr;
10522     }
10523   }
10524   assert(!R.isAmbiguous() && !R.empty());
10525   NamedDecl *ND = R.getRepresentativeDecl();
10526 
10527   // Check if we have a previous declaration with the same name.
10528   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10529                      ForVisibleRedeclaration);
10530   LookupName(PrevR, S);
10531 
10532   // Check we're not shadowing a template parameter.
10533   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10534     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10535     PrevR.clear();
10536   }
10537 
10538   // Filter out any other lookup result from an enclosing scope.
10539   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10540                        /*AllowInlineNamespace*/false);
10541 
10542   // Find the previous declaration and check that we can redeclare it.
10543   NamespaceAliasDecl *Prev = nullptr;
10544   if (PrevR.isSingleResult()) {
10545     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10546     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10547       // We already have an alias with the same name that points to the same
10548       // namespace; check that it matches.
10549       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10550         Prev = AD;
10551       } else if (isVisible(PrevDecl)) {
10552         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10553           << Alias;
10554         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10555           << AD->getNamespace();
10556         return nullptr;
10557       }
10558     } else if (isVisible(PrevDecl)) {
10559       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10560                             ? diag::err_redefinition
10561                             : diag::err_redefinition_different_kind;
10562       Diag(AliasLoc, DiagID) << Alias;
10563       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10564       return nullptr;
10565     }
10566   }
10567 
10568   // The use of a nested name specifier may trigger deprecation warnings.
10569   DiagnoseUseOfDecl(ND, IdentLoc);
10570 
10571   NamespaceAliasDecl *AliasDecl =
10572     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10573                                Alias, SS.getWithLocInContext(Context),
10574                                IdentLoc, ND);
10575   if (Prev)
10576     AliasDecl->setPreviousDecl(Prev);
10577 
10578   PushOnScopeChains(AliasDecl, S);
10579   return AliasDecl;
10580 }
10581 
10582 namespace {
10583 struct SpecialMemberExceptionSpecInfo
10584     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10585   SourceLocation Loc;
10586   Sema::ImplicitExceptionSpecification ExceptSpec;
10587 
10588   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10589                                  Sema::CXXSpecialMember CSM,
10590                                  Sema::InheritedConstructorInfo *ICI,
10591                                  SourceLocation Loc)
10592       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10593 
10594   bool visitBase(CXXBaseSpecifier *Base);
10595   bool visitField(FieldDecl *FD);
10596 
10597   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10598                            unsigned Quals);
10599 
10600   void visitSubobjectCall(Subobject Subobj,
10601                           Sema::SpecialMemberOverloadResult SMOR);
10602 };
10603 }
10604 
10605 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10606   auto *RT = Base->getType()->getAs<RecordType>();
10607   if (!RT)
10608     return false;
10609 
10610   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10611   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10612   if (auto *BaseCtor = SMOR.getMethod()) {
10613     visitSubobjectCall(Base, BaseCtor);
10614     return false;
10615   }
10616 
10617   visitClassSubobject(BaseClass, Base, 0);
10618   return false;
10619 }
10620 
10621 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10622   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10623     Expr *E = FD->getInClassInitializer();
10624     if (!E)
10625       // FIXME: It's a little wasteful to build and throw away a
10626       // CXXDefaultInitExpr here.
10627       // FIXME: We should have a single context note pointing at Loc, and
10628       // this location should be MD->getLocation() instead, since that's
10629       // the location where we actually use the default init expression.
10630       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10631     if (E)
10632       ExceptSpec.CalledExpr(E);
10633   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10634                             ->getAs<RecordType>()) {
10635     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10636                         FD->getType().getCVRQualifiers());
10637   }
10638   return false;
10639 }
10640 
10641 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10642                                                          Subobject Subobj,
10643                                                          unsigned Quals) {
10644   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10645   bool IsMutable = Field && Field->isMutable();
10646   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10647 }
10648 
10649 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10650     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10651   // Note, if lookup fails, it doesn't matter what exception specification we
10652   // choose because the special member will be deleted.
10653   if (CXXMethodDecl *MD = SMOR.getMethod())
10654     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10655 }
10656 
10657 static Sema::ImplicitExceptionSpecification
10658 ComputeDefaultedSpecialMemberExceptionSpec(
10659     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10660     Sema::InheritedConstructorInfo *ICI) {
10661   CXXRecordDecl *ClassDecl = MD->getParent();
10662 
10663   // C++ [except.spec]p14:
10664   //   An implicitly declared special member function (Clause 12) shall have an
10665   //   exception-specification. [...]
10666   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10667   if (ClassDecl->isInvalidDecl())
10668     return Info.ExceptSpec;
10669 
10670   // C++1z [except.spec]p7:
10671   //   [Look for exceptions thrown by] a constructor selected [...] to
10672   //   initialize a potentially constructed subobject,
10673   // C++1z [except.spec]p8:
10674   //   The exception specification for an implicitly-declared destructor, or a
10675   //   destructor without a noexcept-specifier, is potentially-throwing if and
10676   //   only if any of the destructors for any of its potentially constructed
10677   //   subojects is potentially throwing.
10678   // FIXME: We respect the first rule but ignore the "potentially constructed"
10679   // in the second rule to resolve a core issue (no number yet) that would have
10680   // us reject:
10681   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10682   //   struct B : A {};
10683   //   struct C : B { void f(); };
10684   // ... due to giving B::~B() a non-throwing exception specification.
10685   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10686                                 : Info.VisitAllBases);
10687 
10688   return Info.ExceptSpec;
10689 }
10690 
10691 namespace {
10692 /// RAII object to register a special member as being currently declared.
10693 struct DeclaringSpecialMember {
10694   Sema &S;
10695   Sema::SpecialMemberDecl D;
10696   Sema::ContextRAII SavedContext;
10697   bool WasAlreadyBeingDeclared;
10698 
10699   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10700       : S(S), D(RD, CSM), SavedContext(S, RD) {
10701     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10702     if (WasAlreadyBeingDeclared)
10703       // This almost never happens, but if it does, ensure that our cache
10704       // doesn't contain a stale result.
10705       S.SpecialMemberCache.clear();
10706     else {
10707       // Register a note to be produced if we encounter an error while
10708       // declaring the special member.
10709       Sema::CodeSynthesisContext Ctx;
10710       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10711       // FIXME: We don't have a location to use here. Using the class's
10712       // location maintains the fiction that we declare all special members
10713       // with the class, but (1) it's not clear that lying about that helps our
10714       // users understand what's going on, and (2) there may be outer contexts
10715       // on the stack (some of which are relevant) and printing them exposes
10716       // our lies.
10717       Ctx.PointOfInstantiation = RD->getLocation();
10718       Ctx.Entity = RD;
10719       Ctx.SpecialMember = CSM;
10720       S.pushCodeSynthesisContext(Ctx);
10721     }
10722   }
10723   ~DeclaringSpecialMember() {
10724     if (!WasAlreadyBeingDeclared) {
10725       S.SpecialMembersBeingDeclared.erase(D);
10726       S.popCodeSynthesisContext();
10727     }
10728   }
10729 
10730   /// Are we already trying to declare this special member?
10731   bool isAlreadyBeingDeclared() const {
10732     return WasAlreadyBeingDeclared;
10733   }
10734 };
10735 }
10736 
10737 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10738   // Look up any existing declarations, but don't trigger declaration of all
10739   // implicit special members with this name.
10740   DeclarationName Name = FD->getDeclName();
10741   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10742                  ForExternalRedeclaration);
10743   for (auto *D : FD->getParent()->lookup(Name))
10744     if (auto *Acceptable = R.getAcceptableDecl(D))
10745       R.addDecl(Acceptable);
10746   R.resolveKind();
10747   R.suppressDiagnostics();
10748 
10749   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10750 }
10751 
10752 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10753                                                      CXXRecordDecl *ClassDecl) {
10754   // C++ [class.ctor]p5:
10755   //   A default constructor for a class X is a constructor of class X
10756   //   that can be called without an argument. If there is no
10757   //   user-declared constructor for class X, a default constructor is
10758   //   implicitly declared. An implicitly-declared default constructor
10759   //   is an inline public member of its class.
10760   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10761          "Should not build implicit default constructor!");
10762 
10763   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10764   if (DSM.isAlreadyBeingDeclared())
10765     return nullptr;
10766 
10767   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10768                                                      CXXDefaultConstructor,
10769                                                      false);
10770 
10771   // Create the actual constructor declaration.
10772   CanQualType ClassType
10773     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10774   SourceLocation ClassLoc = ClassDecl->getLocation();
10775   DeclarationName Name
10776     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10777   DeclarationNameInfo NameInfo(Name, ClassLoc);
10778   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10779       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10780       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10781       /*isImplicitlyDeclared=*/true, Constexpr);
10782   DefaultCon->setAccess(AS_public);
10783   DefaultCon->setDefaulted();
10784 
10785   if (getLangOpts().CUDA) {
10786     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10787                                             DefaultCon,
10788                                             /* ConstRHS */ false,
10789                                             /* Diagnose */ false);
10790   }
10791 
10792   // Build an exception specification pointing back at this constructor.
10793   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10794   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10795 
10796   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10797   // constructors is easy to compute.
10798   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10799 
10800   // Note that we have declared this constructor.
10801   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10802 
10803   Scope *S = getScopeForContext(ClassDecl);
10804   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10805 
10806   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10807     SetDeclDeleted(DefaultCon, ClassLoc);
10808 
10809   if (S)
10810     PushOnScopeChains(DefaultCon, S, false);
10811   ClassDecl->addDecl(DefaultCon);
10812 
10813   return DefaultCon;
10814 }
10815 
10816 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10817                                             CXXConstructorDecl *Constructor) {
10818   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10819           !Constructor->doesThisDeclarationHaveABody() &&
10820           !Constructor->isDeleted()) &&
10821     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10822   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10823     return;
10824 
10825   CXXRecordDecl *ClassDecl = Constructor->getParent();
10826   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10827 
10828   SynthesizedFunctionScope Scope(*this, Constructor);
10829 
10830   // The exception specification is needed because we are defining the
10831   // function.
10832   ResolveExceptionSpec(CurrentLocation,
10833                        Constructor->getType()->castAs<FunctionProtoType>());
10834   MarkVTableUsed(CurrentLocation, ClassDecl);
10835 
10836   // Add a context note for diagnostics produced after this point.
10837   Scope.addContextNote(CurrentLocation);
10838 
10839   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10840     Constructor->setInvalidDecl();
10841     return;
10842   }
10843 
10844   SourceLocation Loc = Constructor->getLocEnd().isValid()
10845                            ? Constructor->getLocEnd()
10846                            : Constructor->getLocation();
10847   Constructor->setBody(new (Context) CompoundStmt(Loc));
10848   Constructor->markUsed(Context);
10849 
10850   if (ASTMutationListener *L = getASTMutationListener()) {
10851     L->CompletedImplicitDefinition(Constructor);
10852   }
10853 
10854   DiagnoseUninitializedFields(*this, Constructor);
10855 }
10856 
10857 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10858   // Perform any delayed checks on exception specifications.
10859   CheckDelayedMemberExceptionSpecs();
10860 }
10861 
10862 /// Find or create the fake constructor we synthesize to model constructing an
10863 /// object of a derived class via a constructor of a base class.
10864 CXXConstructorDecl *
10865 Sema::findInheritingConstructor(SourceLocation Loc,
10866                                 CXXConstructorDecl *BaseCtor,
10867                                 ConstructorUsingShadowDecl *Shadow) {
10868   CXXRecordDecl *Derived = Shadow->getParent();
10869   SourceLocation UsingLoc = Shadow->getLocation();
10870 
10871   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10872   // For now we use the name of the base class constructor as a member of the
10873   // derived class to indicate a (fake) inherited constructor name.
10874   DeclarationName Name = BaseCtor->getDeclName();
10875 
10876   // Check to see if we already have a fake constructor for this inherited
10877   // constructor call.
10878   for (NamedDecl *Ctor : Derived->lookup(Name))
10879     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10880                                ->getInheritedConstructor()
10881                                .getConstructor(),
10882                            BaseCtor))
10883       return cast<CXXConstructorDecl>(Ctor);
10884 
10885   DeclarationNameInfo NameInfo(Name, UsingLoc);
10886   TypeSourceInfo *TInfo =
10887       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10888   FunctionProtoTypeLoc ProtoLoc =
10889       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10890 
10891   // Check the inherited constructor is valid and find the list of base classes
10892   // from which it was inherited.
10893   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10894 
10895   bool Constexpr =
10896       BaseCtor->isConstexpr() &&
10897       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10898                                         false, BaseCtor, &ICI);
10899 
10900   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10901       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10902       BaseCtor->isExplicit(), /*Inline=*/true,
10903       /*ImplicitlyDeclared=*/true, Constexpr,
10904       InheritedConstructor(Shadow, BaseCtor));
10905   if (Shadow->isInvalidDecl())
10906     DerivedCtor->setInvalidDecl();
10907 
10908   // Build an unevaluated exception specification for this fake constructor.
10909   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10910   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10911   EPI.ExceptionSpec.Type = EST_Unevaluated;
10912   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10913   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10914                                                FPT->getParamTypes(), EPI));
10915 
10916   // Build the parameter declarations.
10917   SmallVector<ParmVarDecl *, 16> ParamDecls;
10918   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10919     TypeSourceInfo *TInfo =
10920         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10921     ParmVarDecl *PD = ParmVarDecl::Create(
10922         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10923         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10924     PD->setScopeInfo(0, I);
10925     PD->setImplicit();
10926     // Ensure attributes are propagated onto parameters (this matters for
10927     // format, pass_object_size, ...).
10928     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10929     ParamDecls.push_back(PD);
10930     ProtoLoc.setParam(I, PD);
10931   }
10932 
10933   // Set up the new constructor.
10934   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10935   DerivedCtor->setAccess(BaseCtor->getAccess());
10936   DerivedCtor->setParams(ParamDecls);
10937   Derived->addDecl(DerivedCtor);
10938 
10939   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10940     SetDeclDeleted(DerivedCtor, UsingLoc);
10941 
10942   return DerivedCtor;
10943 }
10944 
10945 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10946   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10947                                Ctor->getInheritedConstructor().getShadowDecl());
10948   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10949                             /*Diagnose*/true);
10950 }
10951 
10952 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10953                                        CXXConstructorDecl *Constructor) {
10954   CXXRecordDecl *ClassDecl = Constructor->getParent();
10955   assert(Constructor->getInheritedConstructor() &&
10956          !Constructor->doesThisDeclarationHaveABody() &&
10957          !Constructor->isDeleted());
10958   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10959     return;
10960 
10961   // Initializations are performed "as if by a defaulted default constructor",
10962   // so enter the appropriate scope.
10963   SynthesizedFunctionScope Scope(*this, Constructor);
10964 
10965   // The exception specification is needed because we are defining the
10966   // function.
10967   ResolveExceptionSpec(CurrentLocation,
10968                        Constructor->getType()->castAs<FunctionProtoType>());
10969   MarkVTableUsed(CurrentLocation, ClassDecl);
10970 
10971   // Add a context note for diagnostics produced after this point.
10972   Scope.addContextNote(CurrentLocation);
10973 
10974   ConstructorUsingShadowDecl *Shadow =
10975       Constructor->getInheritedConstructor().getShadowDecl();
10976   CXXConstructorDecl *InheritedCtor =
10977       Constructor->getInheritedConstructor().getConstructor();
10978 
10979   // [class.inhctor.init]p1:
10980   //   initialization proceeds as if a defaulted default constructor is used to
10981   //   initialize the D object and each base class subobject from which the
10982   //   constructor was inherited
10983 
10984   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10985   CXXRecordDecl *RD = Shadow->getParent();
10986   SourceLocation InitLoc = Shadow->getLocation();
10987 
10988   // Build explicit initializers for all base classes from which the
10989   // constructor was inherited.
10990   SmallVector<CXXCtorInitializer*, 8> Inits;
10991   for (bool VBase : {false, true}) {
10992     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10993       if (B.isVirtual() != VBase)
10994         continue;
10995 
10996       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10997       if (!BaseRD)
10998         continue;
10999 
11000       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11001       if (!BaseCtor.first)
11002         continue;
11003 
11004       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11005       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11006           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11007 
11008       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11009       Inits.push_back(new (Context) CXXCtorInitializer(
11010           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11011           SourceLocation()));
11012     }
11013   }
11014 
11015   // We now proceed as if for a defaulted default constructor, with the relevant
11016   // initializers replaced.
11017 
11018   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11019     Constructor->setInvalidDecl();
11020     return;
11021   }
11022 
11023   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11024   Constructor->markUsed(Context);
11025 
11026   if (ASTMutationListener *L = getASTMutationListener()) {
11027     L->CompletedImplicitDefinition(Constructor);
11028   }
11029 
11030   DiagnoseUninitializedFields(*this, Constructor);
11031 }
11032 
11033 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11034   // C++ [class.dtor]p2:
11035   //   If a class has no user-declared destructor, a destructor is
11036   //   declared implicitly. An implicitly-declared destructor is an
11037   //   inline public member of its class.
11038   assert(ClassDecl->needsImplicitDestructor());
11039 
11040   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11041   if (DSM.isAlreadyBeingDeclared())
11042     return nullptr;
11043 
11044   // Create the actual destructor declaration.
11045   CanQualType ClassType
11046     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11047   SourceLocation ClassLoc = ClassDecl->getLocation();
11048   DeclarationName Name
11049     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11050   DeclarationNameInfo NameInfo(Name, ClassLoc);
11051   CXXDestructorDecl *Destructor
11052       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11053                                   QualType(), nullptr, /*isInline=*/true,
11054                                   /*isImplicitlyDeclared=*/true);
11055   Destructor->setAccess(AS_public);
11056   Destructor->setDefaulted();
11057 
11058   if (getLangOpts().CUDA) {
11059     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11060                                             Destructor,
11061                                             /* ConstRHS */ false,
11062                                             /* Diagnose */ false);
11063   }
11064 
11065   // Build an exception specification pointing back at this destructor.
11066   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11067   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11068 
11069   // We don't need to use SpecialMemberIsTrivial here; triviality for
11070   // destructors is easy to compute.
11071   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11072   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11073                                 ClassDecl->hasTrivialDestructorForCall());
11074 
11075   // Note that we have declared this destructor.
11076   ++ASTContext::NumImplicitDestructorsDeclared;
11077 
11078   Scope *S = getScopeForContext(ClassDecl);
11079   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11080 
11081   // We can't check whether an implicit destructor is deleted before we complete
11082   // the definition of the class, because its validity depends on the alignment
11083   // of the class. We'll check this from ActOnFields once the class is complete.
11084   if (ClassDecl->isCompleteDefinition() &&
11085       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11086     SetDeclDeleted(Destructor, ClassLoc);
11087 
11088   // Introduce this destructor into its scope.
11089   if (S)
11090     PushOnScopeChains(Destructor, S, false);
11091   ClassDecl->addDecl(Destructor);
11092 
11093   return Destructor;
11094 }
11095 
11096 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11097                                     CXXDestructorDecl *Destructor) {
11098   assert((Destructor->isDefaulted() &&
11099           !Destructor->doesThisDeclarationHaveABody() &&
11100           !Destructor->isDeleted()) &&
11101          "DefineImplicitDestructor - call it for implicit default dtor");
11102   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11103     return;
11104 
11105   CXXRecordDecl *ClassDecl = Destructor->getParent();
11106   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11107 
11108   SynthesizedFunctionScope Scope(*this, Destructor);
11109 
11110   // The exception specification is needed because we are defining the
11111   // function.
11112   ResolveExceptionSpec(CurrentLocation,
11113                        Destructor->getType()->castAs<FunctionProtoType>());
11114   MarkVTableUsed(CurrentLocation, ClassDecl);
11115 
11116   // Add a context note for diagnostics produced after this point.
11117   Scope.addContextNote(CurrentLocation);
11118 
11119   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11120                                          Destructor->getParent());
11121 
11122   if (CheckDestructor(Destructor)) {
11123     Destructor->setInvalidDecl();
11124     return;
11125   }
11126 
11127   SourceLocation Loc = Destructor->getLocEnd().isValid()
11128                            ? Destructor->getLocEnd()
11129                            : Destructor->getLocation();
11130   Destructor->setBody(new (Context) CompoundStmt(Loc));
11131   Destructor->markUsed(Context);
11132 
11133   if (ASTMutationListener *L = getASTMutationListener()) {
11134     L->CompletedImplicitDefinition(Destructor);
11135   }
11136 }
11137 
11138 /// Perform any semantic analysis which needs to be delayed until all
11139 /// pending class member declarations have been parsed.
11140 void Sema::ActOnFinishCXXMemberDecls() {
11141   // If the context is an invalid C++ class, just suppress these checks.
11142   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11143     if (Record->isInvalidDecl()) {
11144       DelayedDefaultedMemberExceptionSpecs.clear();
11145       DelayedExceptionSpecChecks.clear();
11146       return;
11147     }
11148     checkForMultipleExportedDefaultConstructors(*this, Record);
11149   }
11150 }
11151 
11152 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11153   referenceDLLExportedClassMethods();
11154 }
11155 
11156 void Sema::referenceDLLExportedClassMethods() {
11157   if (!DelayedDllExportClasses.empty()) {
11158     // Calling ReferenceDllExportedMembers might cause the current function to
11159     // be called again, so use a local copy of DelayedDllExportClasses.
11160     SmallVector<CXXRecordDecl *, 4> WorkList;
11161     std::swap(DelayedDllExportClasses, WorkList);
11162     for (CXXRecordDecl *Class : WorkList)
11163       ReferenceDllExportedMembers(*this, Class);
11164   }
11165 }
11166 
11167 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
11168                                          CXXDestructorDecl *Destructor) {
11169   assert(getLangOpts().CPlusPlus11 &&
11170          "adjusting dtor exception specs was introduced in c++11");
11171 
11172   // C++11 [class.dtor]p3:
11173   //   A declaration of a destructor that does not have an exception-
11174   //   specification is implicitly considered to have the same exception-
11175   //   specification as an implicit declaration.
11176   const FunctionProtoType *DtorType = Destructor->getType()->
11177                                         getAs<FunctionProtoType>();
11178   if (DtorType->hasExceptionSpec())
11179     return;
11180 
11181   // Replace the destructor's type, building off the existing one. Fortunately,
11182   // the only thing of interest in the destructor type is its extended info.
11183   // The return and arguments are fixed.
11184   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11185   EPI.ExceptionSpec.Type = EST_Unevaluated;
11186   EPI.ExceptionSpec.SourceDecl = Destructor;
11187   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11188 
11189   // FIXME: If the destructor has a body that could throw, and the newly created
11190   // spec doesn't allow exceptions, we should emit a warning, because this
11191   // change in behavior can break conforming C++03 programs at runtime.
11192   // However, we don't have a body or an exception specification yet, so it
11193   // needs to be done somewhere else.
11194 }
11195 
11196 namespace {
11197 /// An abstract base class for all helper classes used in building the
11198 //  copy/move operators. These classes serve as factory functions and help us
11199 //  avoid using the same Expr* in the AST twice.
11200 class ExprBuilder {
11201   ExprBuilder(const ExprBuilder&) = delete;
11202   ExprBuilder &operator=(const ExprBuilder&) = delete;
11203 
11204 protected:
11205   static Expr *assertNotNull(Expr *E) {
11206     assert(E && "Expression construction must not fail.");
11207     return E;
11208   }
11209 
11210 public:
11211   ExprBuilder() {}
11212   virtual ~ExprBuilder() {}
11213 
11214   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11215 };
11216 
11217 class RefBuilder: public ExprBuilder {
11218   VarDecl *Var;
11219   QualType VarType;
11220 
11221 public:
11222   Expr *build(Sema &S, SourceLocation Loc) const override {
11223     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11224   }
11225 
11226   RefBuilder(VarDecl *Var, QualType VarType)
11227       : Var(Var), VarType(VarType) {}
11228 };
11229 
11230 class ThisBuilder: public ExprBuilder {
11231 public:
11232   Expr *build(Sema &S, SourceLocation Loc) const override {
11233     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11234   }
11235 };
11236 
11237 class CastBuilder: public ExprBuilder {
11238   const ExprBuilder &Builder;
11239   QualType Type;
11240   ExprValueKind Kind;
11241   const CXXCastPath &Path;
11242 
11243 public:
11244   Expr *build(Sema &S, SourceLocation Loc) const override {
11245     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11246                                              CK_UncheckedDerivedToBase, Kind,
11247                                              &Path).get());
11248   }
11249 
11250   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11251               const CXXCastPath &Path)
11252       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11253 };
11254 
11255 class DerefBuilder: public ExprBuilder {
11256   const ExprBuilder &Builder;
11257 
11258 public:
11259   Expr *build(Sema &S, SourceLocation Loc) const override {
11260     return assertNotNull(
11261         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11262   }
11263 
11264   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11265 };
11266 
11267 class MemberBuilder: public ExprBuilder {
11268   const ExprBuilder &Builder;
11269   QualType Type;
11270   CXXScopeSpec SS;
11271   bool IsArrow;
11272   LookupResult &MemberLookup;
11273 
11274 public:
11275   Expr *build(Sema &S, SourceLocation Loc) const override {
11276     return assertNotNull(S.BuildMemberReferenceExpr(
11277         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11278         nullptr, MemberLookup, nullptr, nullptr).get());
11279   }
11280 
11281   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11282                 LookupResult &MemberLookup)
11283       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11284         MemberLookup(MemberLookup) {}
11285 };
11286 
11287 class MoveCastBuilder: public ExprBuilder {
11288   const ExprBuilder &Builder;
11289 
11290 public:
11291   Expr *build(Sema &S, SourceLocation Loc) const override {
11292     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11293   }
11294 
11295   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11296 };
11297 
11298 class LvalueConvBuilder: public ExprBuilder {
11299   const ExprBuilder &Builder;
11300 
11301 public:
11302   Expr *build(Sema &S, SourceLocation Loc) const override {
11303     return assertNotNull(
11304         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11305   }
11306 
11307   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11308 };
11309 
11310 class SubscriptBuilder: public ExprBuilder {
11311   const ExprBuilder &Base;
11312   const ExprBuilder &Index;
11313 
11314 public:
11315   Expr *build(Sema &S, SourceLocation Loc) const override {
11316     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11317         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11318   }
11319 
11320   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11321       : Base(Base), Index(Index) {}
11322 };
11323 
11324 } // end anonymous namespace
11325 
11326 /// When generating a defaulted copy or move assignment operator, if a field
11327 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11328 /// do so. This optimization only applies for arrays of scalars, and for arrays
11329 /// of class type where the selected copy/move-assignment operator is trivial.
11330 static StmtResult
11331 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11332                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11333   // Compute the size of the memory buffer to be copied.
11334   QualType SizeType = S.Context.getSizeType();
11335   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11336                    S.Context.getTypeSizeInChars(T).getQuantity());
11337 
11338   // Take the address of the field references for "from" and "to". We
11339   // directly construct UnaryOperators here because semantic analysis
11340   // does not permit us to take the address of an xvalue.
11341   Expr *From = FromB.build(S, Loc);
11342   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11343                          S.Context.getPointerType(From->getType()),
11344                          VK_RValue, OK_Ordinary, Loc, false);
11345   Expr *To = ToB.build(S, Loc);
11346   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11347                        S.Context.getPointerType(To->getType()),
11348                        VK_RValue, OK_Ordinary, Loc, false);
11349 
11350   const Type *E = T->getBaseElementTypeUnsafe();
11351   bool NeedsCollectableMemCpy =
11352     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11353 
11354   // Create a reference to the __builtin_objc_memmove_collectable function
11355   StringRef MemCpyName = NeedsCollectableMemCpy ?
11356     "__builtin_objc_memmove_collectable" :
11357     "__builtin_memcpy";
11358   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11359                  Sema::LookupOrdinaryName);
11360   S.LookupName(R, S.TUScope, true);
11361 
11362   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11363   if (!MemCpy)
11364     // Something went horribly wrong earlier, and we will have complained
11365     // about it.
11366     return StmtError();
11367 
11368   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11369                                             VK_RValue, Loc, nullptr);
11370   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11371 
11372   Expr *CallArgs[] = {
11373     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11374   };
11375   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11376                                     Loc, CallArgs, Loc);
11377 
11378   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11379   return Call.getAs<Stmt>();
11380 }
11381 
11382 /// Builds a statement that copies/moves the given entity from \p From to
11383 /// \c To.
11384 ///
11385 /// This routine is used to copy/move the members of a class with an
11386 /// implicitly-declared copy/move assignment operator. When the entities being
11387 /// copied are arrays, this routine builds for loops to copy them.
11388 ///
11389 /// \param S The Sema object used for type-checking.
11390 ///
11391 /// \param Loc The location where the implicit copy/move is being generated.
11392 ///
11393 /// \param T The type of the expressions being copied/moved. Both expressions
11394 /// must have this type.
11395 ///
11396 /// \param To The expression we are copying/moving to.
11397 ///
11398 /// \param From The expression we are copying/moving from.
11399 ///
11400 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11401 /// Otherwise, it's a non-static member subobject.
11402 ///
11403 /// \param Copying Whether we're copying or moving.
11404 ///
11405 /// \param Depth Internal parameter recording the depth of the recursion.
11406 ///
11407 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11408 /// if a memcpy should be used instead.
11409 static StmtResult
11410 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11411                                  const ExprBuilder &To, const ExprBuilder &From,
11412                                  bool CopyingBaseSubobject, bool Copying,
11413                                  unsigned Depth = 0) {
11414   // C++11 [class.copy]p28:
11415   //   Each subobject is assigned in the manner appropriate to its type:
11416   //
11417   //     - if the subobject is of class type, as if by a call to operator= with
11418   //       the subobject as the object expression and the corresponding
11419   //       subobject of x as a single function argument (as if by explicit
11420   //       qualification; that is, ignoring any possible virtual overriding
11421   //       functions in more derived classes);
11422   //
11423   // C++03 [class.copy]p13:
11424   //     - if the subobject is of class type, the copy assignment operator for
11425   //       the class is used (as if by explicit qualification; that is,
11426   //       ignoring any possible virtual overriding functions in more derived
11427   //       classes);
11428   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11429     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11430 
11431     // Look for operator=.
11432     DeclarationName Name
11433       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11434     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11435     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11436 
11437     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11438     // operator.
11439     if (!S.getLangOpts().CPlusPlus11) {
11440       LookupResult::Filter F = OpLookup.makeFilter();
11441       while (F.hasNext()) {
11442         NamedDecl *D = F.next();
11443         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11444           if (Method->isCopyAssignmentOperator() ||
11445               (!Copying && Method->isMoveAssignmentOperator()))
11446             continue;
11447 
11448         F.erase();
11449       }
11450       F.done();
11451     }
11452 
11453     // Suppress the protected check (C++ [class.protected]) for each of the
11454     // assignment operators we found. This strange dance is required when
11455     // we're assigning via a base classes's copy-assignment operator. To
11456     // ensure that we're getting the right base class subobject (without
11457     // ambiguities), we need to cast "this" to that subobject type; to
11458     // ensure that we don't go through the virtual call mechanism, we need
11459     // to qualify the operator= name with the base class (see below). However,
11460     // this means that if the base class has a protected copy assignment
11461     // operator, the protected member access check will fail. So, we
11462     // rewrite "protected" access to "public" access in this case, since we
11463     // know by construction that we're calling from a derived class.
11464     if (CopyingBaseSubobject) {
11465       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11466            L != LEnd; ++L) {
11467         if (L.getAccess() == AS_protected)
11468           L.setAccess(AS_public);
11469       }
11470     }
11471 
11472     // Create the nested-name-specifier that will be used to qualify the
11473     // reference to operator=; this is required to suppress the virtual
11474     // call mechanism.
11475     CXXScopeSpec SS;
11476     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11477     SS.MakeTrivial(S.Context,
11478                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11479                                                CanonicalT),
11480                    Loc);
11481 
11482     // Create the reference to operator=.
11483     ExprResult OpEqualRef
11484       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11485                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11486                                    /*FirstQualifierInScope=*/nullptr,
11487                                    OpLookup,
11488                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11489                                    /*SuppressQualifierCheck=*/true);
11490     if (OpEqualRef.isInvalid())
11491       return StmtError();
11492 
11493     // Build the call to the assignment operator.
11494 
11495     Expr *FromInst = From.build(S, Loc);
11496     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11497                                                   OpEqualRef.getAs<Expr>(),
11498                                                   Loc, FromInst, Loc);
11499     if (Call.isInvalid())
11500       return StmtError();
11501 
11502     // If we built a call to a trivial 'operator=' while copying an array,
11503     // bail out. We'll replace the whole shebang with a memcpy.
11504     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11505     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11506       return StmtResult((Stmt*)nullptr);
11507 
11508     // Convert to an expression-statement, and clean up any produced
11509     // temporaries.
11510     return S.ActOnExprStmt(Call);
11511   }
11512 
11513   //     - if the subobject is of scalar type, the built-in assignment
11514   //       operator is used.
11515   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11516   if (!ArrayTy) {
11517     ExprResult Assignment = S.CreateBuiltinBinOp(
11518         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11519     if (Assignment.isInvalid())
11520       return StmtError();
11521     return S.ActOnExprStmt(Assignment);
11522   }
11523 
11524   //     - if the subobject is an array, each element is assigned, in the
11525   //       manner appropriate to the element type;
11526 
11527   // Construct a loop over the array bounds, e.g.,
11528   //
11529   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11530   //
11531   // that will copy each of the array elements.
11532   QualType SizeType = S.Context.getSizeType();
11533 
11534   // Create the iteration variable.
11535   IdentifierInfo *IterationVarName = nullptr;
11536   {
11537     SmallString<8> Str;
11538     llvm::raw_svector_ostream OS(Str);
11539     OS << "__i" << Depth;
11540     IterationVarName = &S.Context.Idents.get(OS.str());
11541   }
11542   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11543                                           IterationVarName, SizeType,
11544                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11545                                           SC_None);
11546 
11547   // Initialize the iteration variable to zero.
11548   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11549   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11550 
11551   // Creates a reference to the iteration variable.
11552   RefBuilder IterationVarRef(IterationVar, SizeType);
11553   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11554 
11555   // Create the DeclStmt that holds the iteration variable.
11556   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11557 
11558   // Subscript the "from" and "to" expressions with the iteration variable.
11559   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11560   MoveCastBuilder FromIndexMove(FromIndexCopy);
11561   const ExprBuilder *FromIndex;
11562   if (Copying)
11563     FromIndex = &FromIndexCopy;
11564   else
11565     FromIndex = &FromIndexMove;
11566 
11567   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11568 
11569   // Build the copy/move for an individual element of the array.
11570   StmtResult Copy =
11571     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11572                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11573                                      Copying, Depth + 1);
11574   // Bail out if copying fails or if we determined that we should use memcpy.
11575   if (Copy.isInvalid() || !Copy.get())
11576     return Copy;
11577 
11578   // Create the comparison against the array bound.
11579   llvm::APInt Upper
11580     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11581   Expr *Comparison
11582     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11583                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11584                                      BO_NE, S.Context.BoolTy,
11585                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11586 
11587   // Create the pre-increment of the iteration variable. We can determine
11588   // whether the increment will overflow based on the value of the array
11589   // bound.
11590   Expr *Increment = new (S.Context)
11591       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11592                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11593 
11594   // Construct the loop that copies all elements of this array.
11595   return S.ActOnForStmt(
11596       Loc, Loc, InitStmt,
11597       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11598       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11599 }
11600 
11601 static StmtResult
11602 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11603                       const ExprBuilder &To, const ExprBuilder &From,
11604                       bool CopyingBaseSubobject, bool Copying) {
11605   // Maybe we should use a memcpy?
11606   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11607       T.isTriviallyCopyableType(S.Context))
11608     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11609 
11610   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11611                                                      CopyingBaseSubobject,
11612                                                      Copying, 0));
11613 
11614   // If we ended up picking a trivial assignment operator for an array of a
11615   // non-trivially-copyable class type, just emit a memcpy.
11616   if (!Result.isInvalid() && !Result.get())
11617     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11618 
11619   return Result;
11620 }
11621 
11622 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11623   // Note: The following rules are largely analoguous to the copy
11624   // constructor rules. Note that virtual bases are not taken into account
11625   // for determining the argument type of the operator. Note also that
11626   // operators taking an object instead of a reference are allowed.
11627   assert(ClassDecl->needsImplicitCopyAssignment());
11628 
11629   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11630   if (DSM.isAlreadyBeingDeclared())
11631     return nullptr;
11632 
11633   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11634   QualType RetType = Context.getLValueReferenceType(ArgType);
11635   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11636   if (Const)
11637     ArgType = ArgType.withConst();
11638   ArgType = Context.getLValueReferenceType(ArgType);
11639 
11640   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11641                                                      CXXCopyAssignment,
11642                                                      Const);
11643 
11644   //   An implicitly-declared copy assignment operator is an inline public
11645   //   member of its class.
11646   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11647   SourceLocation ClassLoc = ClassDecl->getLocation();
11648   DeclarationNameInfo NameInfo(Name, ClassLoc);
11649   CXXMethodDecl *CopyAssignment =
11650       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11651                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11652                             /*isInline=*/true, Constexpr, SourceLocation());
11653   CopyAssignment->setAccess(AS_public);
11654   CopyAssignment->setDefaulted();
11655   CopyAssignment->setImplicit();
11656 
11657   if (getLangOpts().CUDA) {
11658     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11659                                             CopyAssignment,
11660                                             /* ConstRHS */ Const,
11661                                             /* Diagnose */ false);
11662   }
11663 
11664   // Build an exception specification pointing back at this member.
11665   FunctionProtoType::ExtProtoInfo EPI =
11666       getImplicitMethodEPI(*this, CopyAssignment);
11667   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11668 
11669   // Add the parameter to the operator.
11670   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11671                                                ClassLoc, ClassLoc,
11672                                                /*Id=*/nullptr, ArgType,
11673                                                /*TInfo=*/nullptr, SC_None,
11674                                                nullptr);
11675   CopyAssignment->setParams(FromParam);
11676 
11677   CopyAssignment->setTrivial(
11678     ClassDecl->needsOverloadResolutionForCopyAssignment()
11679       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11680       : ClassDecl->hasTrivialCopyAssignment());
11681 
11682   // Note that we have added this copy-assignment operator.
11683   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11684 
11685   Scope *S = getScopeForContext(ClassDecl);
11686   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11687 
11688   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11689     SetDeclDeleted(CopyAssignment, ClassLoc);
11690 
11691   if (S)
11692     PushOnScopeChains(CopyAssignment, S, false);
11693   ClassDecl->addDecl(CopyAssignment);
11694 
11695   return CopyAssignment;
11696 }
11697 
11698 /// Diagnose an implicit copy operation for a class which is odr-used, but
11699 /// which is deprecated because the class has a user-declared copy constructor,
11700 /// copy assignment operator, or destructor.
11701 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11702   assert(CopyOp->isImplicit());
11703 
11704   CXXRecordDecl *RD = CopyOp->getParent();
11705   CXXMethodDecl *UserDeclaredOperation = nullptr;
11706 
11707   // In Microsoft mode, assignment operations don't affect constructors and
11708   // vice versa.
11709   if (RD->hasUserDeclaredDestructor()) {
11710     UserDeclaredOperation = RD->getDestructor();
11711   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11712              RD->hasUserDeclaredCopyConstructor() &&
11713              !S.getLangOpts().MSVCCompat) {
11714     // Find any user-declared copy constructor.
11715     for (auto *I : RD->ctors()) {
11716       if (I->isCopyConstructor()) {
11717         UserDeclaredOperation = I;
11718         break;
11719       }
11720     }
11721     assert(UserDeclaredOperation);
11722   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11723              RD->hasUserDeclaredCopyAssignment() &&
11724              !S.getLangOpts().MSVCCompat) {
11725     // Find any user-declared move assignment operator.
11726     for (auto *I : RD->methods()) {
11727       if (I->isCopyAssignmentOperator()) {
11728         UserDeclaredOperation = I;
11729         break;
11730       }
11731     }
11732     assert(UserDeclaredOperation);
11733   }
11734 
11735   if (UserDeclaredOperation) {
11736     S.Diag(UserDeclaredOperation->getLocation(),
11737          diag::warn_deprecated_copy_operation)
11738       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11739       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11740   }
11741 }
11742 
11743 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11744                                         CXXMethodDecl *CopyAssignOperator) {
11745   assert((CopyAssignOperator->isDefaulted() &&
11746           CopyAssignOperator->isOverloadedOperator() &&
11747           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11748           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11749           !CopyAssignOperator->isDeleted()) &&
11750          "DefineImplicitCopyAssignment called for wrong function");
11751   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11752     return;
11753 
11754   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11755   if (ClassDecl->isInvalidDecl()) {
11756     CopyAssignOperator->setInvalidDecl();
11757     return;
11758   }
11759 
11760   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11761 
11762   // The exception specification is needed because we are defining the
11763   // function.
11764   ResolveExceptionSpec(CurrentLocation,
11765                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11766 
11767   // Add a context note for diagnostics produced after this point.
11768   Scope.addContextNote(CurrentLocation);
11769 
11770   // C++11 [class.copy]p18:
11771   //   The [definition of an implicitly declared copy assignment operator] is
11772   //   deprecated if the class has a user-declared copy constructor or a
11773   //   user-declared destructor.
11774   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11775     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11776 
11777   // C++0x [class.copy]p30:
11778   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11779   //   for a non-union class X performs memberwise copy assignment of its
11780   //   subobjects. The direct base classes of X are assigned first, in the
11781   //   order of their declaration in the base-specifier-list, and then the
11782   //   immediate non-static data members of X are assigned, in the order in
11783   //   which they were declared in the class definition.
11784 
11785   // The statements that form the synthesized function body.
11786   SmallVector<Stmt*, 8> Statements;
11787 
11788   // The parameter for the "other" object, which we are copying from.
11789   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11790   Qualifiers OtherQuals = Other->getType().getQualifiers();
11791   QualType OtherRefType = Other->getType();
11792   if (const LValueReferenceType *OtherRef
11793                                 = OtherRefType->getAs<LValueReferenceType>()) {
11794     OtherRefType = OtherRef->getPointeeType();
11795     OtherQuals = OtherRefType.getQualifiers();
11796   }
11797 
11798   // Our location for everything implicitly-generated.
11799   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11800                            ? CopyAssignOperator->getLocEnd()
11801                            : CopyAssignOperator->getLocation();
11802 
11803   // Builds a DeclRefExpr for the "other" object.
11804   RefBuilder OtherRef(Other, OtherRefType);
11805 
11806   // Builds the "this" pointer.
11807   ThisBuilder This;
11808 
11809   // Assign base classes.
11810   bool Invalid = false;
11811   for (auto &Base : ClassDecl->bases()) {
11812     // Form the assignment:
11813     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11814     QualType BaseType = Base.getType().getUnqualifiedType();
11815     if (!BaseType->isRecordType()) {
11816       Invalid = true;
11817       continue;
11818     }
11819 
11820     CXXCastPath BasePath;
11821     BasePath.push_back(&Base);
11822 
11823     // Construct the "from" expression, which is an implicit cast to the
11824     // appropriately-qualified base type.
11825     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11826                      VK_LValue, BasePath);
11827 
11828     // Dereference "this".
11829     DerefBuilder DerefThis(This);
11830     CastBuilder To(DerefThis,
11831                    Context.getCVRQualifiedType(
11832                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11833                    VK_LValue, BasePath);
11834 
11835     // Build the copy.
11836     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11837                                             To, From,
11838                                             /*CopyingBaseSubobject=*/true,
11839                                             /*Copying=*/true);
11840     if (Copy.isInvalid()) {
11841       CopyAssignOperator->setInvalidDecl();
11842       return;
11843     }
11844 
11845     // Success! Record the copy.
11846     Statements.push_back(Copy.getAs<Expr>());
11847   }
11848 
11849   // Assign non-static members.
11850   for (auto *Field : ClassDecl->fields()) {
11851     // FIXME: We should form some kind of AST representation for the implied
11852     // memcpy in a union copy operation.
11853     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11854       continue;
11855 
11856     if (Field->isInvalidDecl()) {
11857       Invalid = true;
11858       continue;
11859     }
11860 
11861     // Check for members of reference type; we can't copy those.
11862     if (Field->getType()->isReferenceType()) {
11863       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11864         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11865       Diag(Field->getLocation(), diag::note_declared_at);
11866       Invalid = true;
11867       continue;
11868     }
11869 
11870     // Check for members of const-qualified, non-class type.
11871     QualType BaseType = Context.getBaseElementType(Field->getType());
11872     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11873       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11874         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11875       Diag(Field->getLocation(), diag::note_declared_at);
11876       Invalid = true;
11877       continue;
11878     }
11879 
11880     // Suppress assigning zero-width bitfields.
11881     if (Field->isZeroLengthBitField(Context))
11882       continue;
11883 
11884     QualType FieldType = Field->getType().getNonReferenceType();
11885     if (FieldType->isIncompleteArrayType()) {
11886       assert(ClassDecl->hasFlexibleArrayMember() &&
11887              "Incomplete array type is not valid");
11888       continue;
11889     }
11890 
11891     // Build references to the field in the object we're copying from and to.
11892     CXXScopeSpec SS; // Intentionally empty
11893     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11894                               LookupMemberName);
11895     MemberLookup.addDecl(Field);
11896     MemberLookup.resolveKind();
11897 
11898     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11899 
11900     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11901 
11902     // Build the copy of this field.
11903     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11904                                             To, From,
11905                                             /*CopyingBaseSubobject=*/false,
11906                                             /*Copying=*/true);
11907     if (Copy.isInvalid()) {
11908       CopyAssignOperator->setInvalidDecl();
11909       return;
11910     }
11911 
11912     // Success! Record the copy.
11913     Statements.push_back(Copy.getAs<Stmt>());
11914   }
11915 
11916   if (!Invalid) {
11917     // Add a "return *this;"
11918     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11919 
11920     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11921     if (Return.isInvalid())
11922       Invalid = true;
11923     else
11924       Statements.push_back(Return.getAs<Stmt>());
11925   }
11926 
11927   if (Invalid) {
11928     CopyAssignOperator->setInvalidDecl();
11929     return;
11930   }
11931 
11932   StmtResult Body;
11933   {
11934     CompoundScopeRAII CompoundScope(*this);
11935     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11936                              /*isStmtExpr=*/false);
11937     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11938   }
11939   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11940   CopyAssignOperator->markUsed(Context);
11941 
11942   if (ASTMutationListener *L = getASTMutationListener()) {
11943     L->CompletedImplicitDefinition(CopyAssignOperator);
11944   }
11945 }
11946 
11947 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11948   assert(ClassDecl->needsImplicitMoveAssignment());
11949 
11950   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11951   if (DSM.isAlreadyBeingDeclared())
11952     return nullptr;
11953 
11954   // Note: The following rules are largely analoguous to the move
11955   // constructor rules.
11956 
11957   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11958   QualType RetType = Context.getLValueReferenceType(ArgType);
11959   ArgType = Context.getRValueReferenceType(ArgType);
11960 
11961   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11962                                                      CXXMoveAssignment,
11963                                                      false);
11964 
11965   //   An implicitly-declared move assignment operator is an inline public
11966   //   member of its class.
11967   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11968   SourceLocation ClassLoc = ClassDecl->getLocation();
11969   DeclarationNameInfo NameInfo(Name, ClassLoc);
11970   CXXMethodDecl *MoveAssignment =
11971       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11972                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11973                             /*isInline=*/true, Constexpr, SourceLocation());
11974   MoveAssignment->setAccess(AS_public);
11975   MoveAssignment->setDefaulted();
11976   MoveAssignment->setImplicit();
11977 
11978   if (getLangOpts().CUDA) {
11979     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11980                                             MoveAssignment,
11981                                             /* ConstRHS */ false,
11982                                             /* Diagnose */ false);
11983   }
11984 
11985   // Build an exception specification pointing back at this member.
11986   FunctionProtoType::ExtProtoInfo EPI =
11987       getImplicitMethodEPI(*this, MoveAssignment);
11988   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11989 
11990   // Add the parameter to the operator.
11991   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11992                                                ClassLoc, ClassLoc,
11993                                                /*Id=*/nullptr, ArgType,
11994                                                /*TInfo=*/nullptr, SC_None,
11995                                                nullptr);
11996   MoveAssignment->setParams(FromParam);
11997 
11998   MoveAssignment->setTrivial(
11999     ClassDecl->needsOverloadResolutionForMoveAssignment()
12000       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12001       : ClassDecl->hasTrivialMoveAssignment());
12002 
12003   // Note that we have added this copy-assignment operator.
12004   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12005 
12006   Scope *S = getScopeForContext(ClassDecl);
12007   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12008 
12009   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12010     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12011     SetDeclDeleted(MoveAssignment, ClassLoc);
12012   }
12013 
12014   if (S)
12015     PushOnScopeChains(MoveAssignment, S, false);
12016   ClassDecl->addDecl(MoveAssignment);
12017 
12018   return MoveAssignment;
12019 }
12020 
12021 /// Check if we're implicitly defining a move assignment operator for a class
12022 /// with virtual bases. Such a move assignment might move-assign the virtual
12023 /// base multiple times.
12024 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12025                                                SourceLocation CurrentLocation) {
12026   assert(!Class->isDependentContext() && "should not define dependent move");
12027 
12028   // Only a virtual base could get implicitly move-assigned multiple times.
12029   // Only a non-trivial move assignment can observe this. We only want to
12030   // diagnose if we implicitly define an assignment operator that assigns
12031   // two base classes, both of which move-assign the same virtual base.
12032   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12033       Class->getNumBases() < 2)
12034     return;
12035 
12036   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12037   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12038   VBaseMap VBases;
12039 
12040   for (auto &BI : Class->bases()) {
12041     Worklist.push_back(&BI);
12042     while (!Worklist.empty()) {
12043       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12044       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12045 
12046       // If the base has no non-trivial move assignment operators,
12047       // we don't care about moves from it.
12048       if (!Base->hasNonTrivialMoveAssignment())
12049         continue;
12050 
12051       // If there's nothing virtual here, skip it.
12052       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12053         continue;
12054 
12055       // If we're not actually going to call a move assignment for this base,
12056       // or the selected move assignment is trivial, skip it.
12057       Sema::SpecialMemberOverloadResult SMOR =
12058         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12059                               /*ConstArg*/false, /*VolatileArg*/false,
12060                               /*RValueThis*/true, /*ConstThis*/false,
12061                               /*VolatileThis*/false);
12062       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12063           !SMOR.getMethod()->isMoveAssignmentOperator())
12064         continue;
12065 
12066       if (BaseSpec->isVirtual()) {
12067         // We're going to move-assign this virtual base, and its move
12068         // assignment operator is not trivial. If this can happen for
12069         // multiple distinct direct bases of Class, diagnose it. (If it
12070         // only happens in one base, we'll diagnose it when synthesizing
12071         // that base class's move assignment operator.)
12072         CXXBaseSpecifier *&Existing =
12073             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12074                 .first->second;
12075         if (Existing && Existing != &BI) {
12076           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12077             << Class << Base;
12078           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
12079             << (Base->getCanonicalDecl() ==
12080                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12081             << Base << Existing->getType() << Existing->getSourceRange();
12082           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
12083             << (Base->getCanonicalDecl() ==
12084                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12085             << Base << BI.getType() << BaseSpec->getSourceRange();
12086 
12087           // Only diagnose each vbase once.
12088           Existing = nullptr;
12089         }
12090       } else {
12091         // Only walk over bases that have defaulted move assignment operators.
12092         // We assume that any user-provided move assignment operator handles
12093         // the multiple-moves-of-vbase case itself somehow.
12094         if (!SMOR.getMethod()->isDefaulted())
12095           continue;
12096 
12097         // We're going to move the base classes of Base. Add them to the list.
12098         for (auto &BI : Base->bases())
12099           Worklist.push_back(&BI);
12100       }
12101     }
12102   }
12103 }
12104 
12105 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12106                                         CXXMethodDecl *MoveAssignOperator) {
12107   assert((MoveAssignOperator->isDefaulted() &&
12108           MoveAssignOperator->isOverloadedOperator() &&
12109           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12110           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12111           !MoveAssignOperator->isDeleted()) &&
12112          "DefineImplicitMoveAssignment called for wrong function");
12113   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12114     return;
12115 
12116   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12117   if (ClassDecl->isInvalidDecl()) {
12118     MoveAssignOperator->setInvalidDecl();
12119     return;
12120   }
12121 
12122   // C++0x [class.copy]p28:
12123   //   The implicitly-defined or move assignment operator for a non-union class
12124   //   X performs memberwise move assignment of its subobjects. The direct base
12125   //   classes of X are assigned first, in the order of their declaration in the
12126   //   base-specifier-list, and then the immediate non-static data members of X
12127   //   are assigned, in the order in which they were declared in the class
12128   //   definition.
12129 
12130   // Issue a warning if our implicit move assignment operator will move
12131   // from a virtual base more than once.
12132   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12133 
12134   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12135 
12136   // The exception specification is needed because we are defining the
12137   // function.
12138   ResolveExceptionSpec(CurrentLocation,
12139                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12140 
12141   // Add a context note for diagnostics produced after this point.
12142   Scope.addContextNote(CurrentLocation);
12143 
12144   // The statements that form the synthesized function body.
12145   SmallVector<Stmt*, 8> Statements;
12146 
12147   // The parameter for the "other" object, which we are move from.
12148   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12149   QualType OtherRefType = Other->getType()->
12150       getAs<RValueReferenceType>()->getPointeeType();
12151   assert(!OtherRefType.getQualifiers() &&
12152          "Bad argument type of defaulted move assignment");
12153 
12154   // Our location for everything implicitly-generated.
12155   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
12156                            ? MoveAssignOperator->getLocEnd()
12157                            : MoveAssignOperator->getLocation();
12158 
12159   // Builds a reference to the "other" object.
12160   RefBuilder OtherRef(Other, OtherRefType);
12161   // Cast to rvalue.
12162   MoveCastBuilder MoveOther(OtherRef);
12163 
12164   // Builds the "this" pointer.
12165   ThisBuilder This;
12166 
12167   // Assign base classes.
12168   bool Invalid = false;
12169   for (auto &Base : ClassDecl->bases()) {
12170     // C++11 [class.copy]p28:
12171     //   It is unspecified whether subobjects representing virtual base classes
12172     //   are assigned more than once by the implicitly-defined copy assignment
12173     //   operator.
12174     // FIXME: Do not assign to a vbase that will be assigned by some other base
12175     // class. For a move-assignment, this can result in the vbase being moved
12176     // multiple times.
12177 
12178     // Form the assignment:
12179     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12180     QualType BaseType = Base.getType().getUnqualifiedType();
12181     if (!BaseType->isRecordType()) {
12182       Invalid = true;
12183       continue;
12184     }
12185 
12186     CXXCastPath BasePath;
12187     BasePath.push_back(&Base);
12188 
12189     // Construct the "from" expression, which is an implicit cast to the
12190     // appropriately-qualified base type.
12191     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12192 
12193     // Dereference "this".
12194     DerefBuilder DerefThis(This);
12195 
12196     // Implicitly cast "this" to the appropriately-qualified base type.
12197     CastBuilder To(DerefThis,
12198                    Context.getCVRQualifiedType(
12199                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12200                    VK_LValue, BasePath);
12201 
12202     // Build the move.
12203     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12204                                             To, From,
12205                                             /*CopyingBaseSubobject=*/true,
12206                                             /*Copying=*/false);
12207     if (Move.isInvalid()) {
12208       MoveAssignOperator->setInvalidDecl();
12209       return;
12210     }
12211 
12212     // Success! Record the move.
12213     Statements.push_back(Move.getAs<Expr>());
12214   }
12215 
12216   // Assign non-static members.
12217   for (auto *Field : ClassDecl->fields()) {
12218     // FIXME: We should form some kind of AST representation for the implied
12219     // memcpy in a union copy operation.
12220     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12221       continue;
12222 
12223     if (Field->isInvalidDecl()) {
12224       Invalid = true;
12225       continue;
12226     }
12227 
12228     // Check for members of reference type; we can't move those.
12229     if (Field->getType()->isReferenceType()) {
12230       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12231         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12232       Diag(Field->getLocation(), diag::note_declared_at);
12233       Invalid = true;
12234       continue;
12235     }
12236 
12237     // Check for members of const-qualified, non-class type.
12238     QualType BaseType = Context.getBaseElementType(Field->getType());
12239     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12240       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12241         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12242       Diag(Field->getLocation(), diag::note_declared_at);
12243       Invalid = true;
12244       continue;
12245     }
12246 
12247     // Suppress assigning zero-width bitfields.
12248     if (Field->isZeroLengthBitField(Context))
12249       continue;
12250 
12251     QualType FieldType = Field->getType().getNonReferenceType();
12252     if (FieldType->isIncompleteArrayType()) {
12253       assert(ClassDecl->hasFlexibleArrayMember() &&
12254              "Incomplete array type is not valid");
12255       continue;
12256     }
12257 
12258     // Build references to the field in the object we're copying from and to.
12259     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12260                               LookupMemberName);
12261     MemberLookup.addDecl(Field);
12262     MemberLookup.resolveKind();
12263     MemberBuilder From(MoveOther, OtherRefType,
12264                        /*IsArrow=*/false, MemberLookup);
12265     MemberBuilder To(This, getCurrentThisType(),
12266                      /*IsArrow=*/true, MemberLookup);
12267 
12268     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12269         "Member reference with rvalue base must be rvalue except for reference "
12270         "members, which aren't allowed for move assignment.");
12271 
12272     // Build the move of this field.
12273     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12274                                             To, From,
12275                                             /*CopyingBaseSubobject=*/false,
12276                                             /*Copying=*/false);
12277     if (Move.isInvalid()) {
12278       MoveAssignOperator->setInvalidDecl();
12279       return;
12280     }
12281 
12282     // Success! Record the copy.
12283     Statements.push_back(Move.getAs<Stmt>());
12284   }
12285 
12286   if (!Invalid) {
12287     // Add a "return *this;"
12288     ExprResult ThisObj =
12289         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12290 
12291     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12292     if (Return.isInvalid())
12293       Invalid = true;
12294     else
12295       Statements.push_back(Return.getAs<Stmt>());
12296   }
12297 
12298   if (Invalid) {
12299     MoveAssignOperator->setInvalidDecl();
12300     return;
12301   }
12302 
12303   StmtResult Body;
12304   {
12305     CompoundScopeRAII CompoundScope(*this);
12306     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12307                              /*isStmtExpr=*/false);
12308     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12309   }
12310   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12311   MoveAssignOperator->markUsed(Context);
12312 
12313   if (ASTMutationListener *L = getASTMutationListener()) {
12314     L->CompletedImplicitDefinition(MoveAssignOperator);
12315   }
12316 }
12317 
12318 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12319                                                     CXXRecordDecl *ClassDecl) {
12320   // C++ [class.copy]p4:
12321   //   If the class definition does not explicitly declare a copy
12322   //   constructor, one is declared implicitly.
12323   assert(ClassDecl->needsImplicitCopyConstructor());
12324 
12325   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12326   if (DSM.isAlreadyBeingDeclared())
12327     return nullptr;
12328 
12329   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12330   QualType ArgType = ClassType;
12331   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12332   if (Const)
12333     ArgType = ArgType.withConst();
12334   ArgType = Context.getLValueReferenceType(ArgType);
12335 
12336   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12337                                                      CXXCopyConstructor,
12338                                                      Const);
12339 
12340   DeclarationName Name
12341     = Context.DeclarationNames.getCXXConstructorName(
12342                                            Context.getCanonicalType(ClassType));
12343   SourceLocation ClassLoc = ClassDecl->getLocation();
12344   DeclarationNameInfo NameInfo(Name, ClassLoc);
12345 
12346   //   An implicitly-declared copy constructor is an inline public
12347   //   member of its class.
12348   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12349       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12350       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12351       Constexpr);
12352   CopyConstructor->setAccess(AS_public);
12353   CopyConstructor->setDefaulted();
12354 
12355   if (getLangOpts().CUDA) {
12356     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12357                                             CopyConstructor,
12358                                             /* ConstRHS */ Const,
12359                                             /* Diagnose */ false);
12360   }
12361 
12362   // Build an exception specification pointing back at this member.
12363   FunctionProtoType::ExtProtoInfo EPI =
12364       getImplicitMethodEPI(*this, CopyConstructor);
12365   CopyConstructor->setType(
12366       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12367 
12368   // Add the parameter to the constructor.
12369   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12370                                                ClassLoc, ClassLoc,
12371                                                /*IdentifierInfo=*/nullptr,
12372                                                ArgType, /*TInfo=*/nullptr,
12373                                                SC_None, nullptr);
12374   CopyConstructor->setParams(FromParam);
12375 
12376   CopyConstructor->setTrivial(
12377       ClassDecl->needsOverloadResolutionForCopyConstructor()
12378           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12379           : ClassDecl->hasTrivialCopyConstructor());
12380 
12381   CopyConstructor->setTrivialForCall(
12382       ClassDecl->hasAttr<TrivialABIAttr>() ||
12383       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12384            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12385              TAH_ConsiderTrivialABI)
12386            : ClassDecl->hasTrivialCopyConstructorForCall()));
12387 
12388   // Note that we have declared this constructor.
12389   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12390 
12391   Scope *S = getScopeForContext(ClassDecl);
12392   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12393 
12394   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12395     ClassDecl->setImplicitCopyConstructorIsDeleted();
12396     SetDeclDeleted(CopyConstructor, ClassLoc);
12397   }
12398 
12399   if (S)
12400     PushOnScopeChains(CopyConstructor, S, false);
12401   ClassDecl->addDecl(CopyConstructor);
12402 
12403   return CopyConstructor;
12404 }
12405 
12406 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12407                                          CXXConstructorDecl *CopyConstructor) {
12408   assert((CopyConstructor->isDefaulted() &&
12409           CopyConstructor->isCopyConstructor() &&
12410           !CopyConstructor->doesThisDeclarationHaveABody() &&
12411           !CopyConstructor->isDeleted()) &&
12412          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12413   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12414     return;
12415 
12416   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12417   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12418 
12419   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12420 
12421   // The exception specification is needed because we are defining the
12422   // function.
12423   ResolveExceptionSpec(CurrentLocation,
12424                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12425   MarkVTableUsed(CurrentLocation, ClassDecl);
12426 
12427   // Add a context note for diagnostics produced after this point.
12428   Scope.addContextNote(CurrentLocation);
12429 
12430   // C++11 [class.copy]p7:
12431   //   The [definition of an implicitly declared copy constructor] is
12432   //   deprecated if the class has a user-declared copy assignment operator
12433   //   or a user-declared destructor.
12434   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12435     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12436 
12437   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12438     CopyConstructor->setInvalidDecl();
12439   }  else {
12440     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12441                              ? CopyConstructor->getLocEnd()
12442                              : CopyConstructor->getLocation();
12443     Sema::CompoundScopeRAII CompoundScope(*this);
12444     CopyConstructor->setBody(
12445         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12446     CopyConstructor->markUsed(Context);
12447   }
12448 
12449   if (ASTMutationListener *L = getASTMutationListener()) {
12450     L->CompletedImplicitDefinition(CopyConstructor);
12451   }
12452 }
12453 
12454 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12455                                                     CXXRecordDecl *ClassDecl) {
12456   assert(ClassDecl->needsImplicitMoveConstructor());
12457 
12458   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12459   if (DSM.isAlreadyBeingDeclared())
12460     return nullptr;
12461 
12462   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12463   QualType ArgType = Context.getRValueReferenceType(ClassType);
12464 
12465   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12466                                                      CXXMoveConstructor,
12467                                                      false);
12468 
12469   DeclarationName Name
12470     = Context.DeclarationNames.getCXXConstructorName(
12471                                            Context.getCanonicalType(ClassType));
12472   SourceLocation ClassLoc = ClassDecl->getLocation();
12473   DeclarationNameInfo NameInfo(Name, ClassLoc);
12474 
12475   // C++11 [class.copy]p11:
12476   //   An implicitly-declared copy/move constructor is an inline public
12477   //   member of its class.
12478   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12479       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12480       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12481       Constexpr);
12482   MoveConstructor->setAccess(AS_public);
12483   MoveConstructor->setDefaulted();
12484 
12485   if (getLangOpts().CUDA) {
12486     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12487                                             MoveConstructor,
12488                                             /* ConstRHS */ false,
12489                                             /* Diagnose */ false);
12490   }
12491 
12492   // Build an exception specification pointing back at this member.
12493   FunctionProtoType::ExtProtoInfo EPI =
12494       getImplicitMethodEPI(*this, MoveConstructor);
12495   MoveConstructor->setType(
12496       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12497 
12498   // Add the parameter to the constructor.
12499   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12500                                                ClassLoc, ClassLoc,
12501                                                /*IdentifierInfo=*/nullptr,
12502                                                ArgType, /*TInfo=*/nullptr,
12503                                                SC_None, nullptr);
12504   MoveConstructor->setParams(FromParam);
12505 
12506   MoveConstructor->setTrivial(
12507       ClassDecl->needsOverloadResolutionForMoveConstructor()
12508           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12509           : ClassDecl->hasTrivialMoveConstructor());
12510 
12511   MoveConstructor->setTrivialForCall(
12512       ClassDecl->hasAttr<TrivialABIAttr>() ||
12513       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12514            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12515                                     TAH_ConsiderTrivialABI)
12516            : ClassDecl->hasTrivialMoveConstructorForCall()));
12517 
12518   // Note that we have declared this constructor.
12519   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12520 
12521   Scope *S = getScopeForContext(ClassDecl);
12522   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12523 
12524   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12525     ClassDecl->setImplicitMoveConstructorIsDeleted();
12526     SetDeclDeleted(MoveConstructor, ClassLoc);
12527   }
12528 
12529   if (S)
12530     PushOnScopeChains(MoveConstructor, S, false);
12531   ClassDecl->addDecl(MoveConstructor);
12532 
12533   return MoveConstructor;
12534 }
12535 
12536 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12537                                          CXXConstructorDecl *MoveConstructor) {
12538   assert((MoveConstructor->isDefaulted() &&
12539           MoveConstructor->isMoveConstructor() &&
12540           !MoveConstructor->doesThisDeclarationHaveABody() &&
12541           !MoveConstructor->isDeleted()) &&
12542          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12543   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12544     return;
12545 
12546   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12547   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12548 
12549   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12550 
12551   // The exception specification is needed because we are defining the
12552   // function.
12553   ResolveExceptionSpec(CurrentLocation,
12554                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12555   MarkVTableUsed(CurrentLocation, ClassDecl);
12556 
12557   // Add a context note for diagnostics produced after this point.
12558   Scope.addContextNote(CurrentLocation);
12559 
12560   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12561     MoveConstructor->setInvalidDecl();
12562   } else {
12563     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12564                              ? MoveConstructor->getLocEnd()
12565                              : MoveConstructor->getLocation();
12566     Sema::CompoundScopeRAII CompoundScope(*this);
12567     MoveConstructor->setBody(ActOnCompoundStmt(
12568         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12569     MoveConstructor->markUsed(Context);
12570   }
12571 
12572   if (ASTMutationListener *L = getASTMutationListener()) {
12573     L->CompletedImplicitDefinition(MoveConstructor);
12574   }
12575 }
12576 
12577 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12578   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12579 }
12580 
12581 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12582                             SourceLocation CurrentLocation,
12583                             CXXConversionDecl *Conv) {
12584   SynthesizedFunctionScope Scope(*this, Conv);
12585   assert(!Conv->getReturnType()->isUndeducedType());
12586 
12587   CXXRecordDecl *Lambda = Conv->getParent();
12588   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12589   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12590 
12591   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12592     CallOp = InstantiateFunctionDeclaration(
12593         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12594     if (!CallOp)
12595       return;
12596 
12597     Invoker = InstantiateFunctionDeclaration(
12598         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12599     if (!Invoker)
12600       return;
12601   }
12602 
12603   if (CallOp->isInvalidDecl())
12604     return;
12605 
12606   // Mark the call operator referenced (and add to pending instantiations
12607   // if necessary).
12608   // For both the conversion and static-invoker template specializations
12609   // we construct their body's in this function, so no need to add them
12610   // to the PendingInstantiations.
12611   MarkFunctionReferenced(CurrentLocation, CallOp);
12612 
12613   // Fill in the __invoke function with a dummy implementation. IR generation
12614   // will fill in the actual details. Update its type in case it contained
12615   // an 'auto'.
12616   Invoker->markUsed(Context);
12617   Invoker->setReferenced();
12618   Invoker->setType(Conv->getReturnType()->getPointeeType());
12619   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12620 
12621   // Construct the body of the conversion function { return __invoke; }.
12622   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12623                                        VK_LValue, Conv->getLocation()).get();
12624   assert(FunctionRef && "Can't refer to __invoke function?");
12625   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12626   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12627                                      Conv->getLocation()));
12628   Conv->markUsed(Context);
12629   Conv->setReferenced();
12630 
12631   if (ASTMutationListener *L = getASTMutationListener()) {
12632     L->CompletedImplicitDefinition(Conv);
12633     L->CompletedImplicitDefinition(Invoker);
12634   }
12635 }
12636 
12637 
12638 
12639 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12640        SourceLocation CurrentLocation,
12641        CXXConversionDecl *Conv)
12642 {
12643   assert(!Conv->getParent()->isGenericLambda());
12644 
12645   SynthesizedFunctionScope Scope(*this, Conv);
12646 
12647   // Copy-initialize the lambda object as needed to capture it.
12648   Expr *This = ActOnCXXThis(CurrentLocation).get();
12649   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12650 
12651   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12652                                                         Conv->getLocation(),
12653                                                         Conv, DerefThis);
12654 
12655   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12656   // behavior.  Note that only the general conversion function does this
12657   // (since it's unusable otherwise); in the case where we inline the
12658   // block literal, it has block literal lifetime semantics.
12659   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12660     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12661                                           CK_CopyAndAutoreleaseBlockObject,
12662                                           BuildBlock.get(), nullptr, VK_RValue);
12663 
12664   if (BuildBlock.isInvalid()) {
12665     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12666     Conv->setInvalidDecl();
12667     return;
12668   }
12669 
12670   // Create the return statement that returns the block from the conversion
12671   // function.
12672   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12673   if (Return.isInvalid()) {
12674     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12675     Conv->setInvalidDecl();
12676     return;
12677   }
12678 
12679   // Set the body of the conversion function.
12680   Stmt *ReturnS = Return.get();
12681   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12682                                      Conv->getLocation()));
12683   Conv->markUsed(Context);
12684 
12685   // We're done; notify the mutation listener, if any.
12686   if (ASTMutationListener *L = getASTMutationListener()) {
12687     L->CompletedImplicitDefinition(Conv);
12688   }
12689 }
12690 
12691 /// Determine whether the given list arguments contains exactly one
12692 /// "real" (non-default) argument.
12693 static bool hasOneRealArgument(MultiExprArg Args) {
12694   switch (Args.size()) {
12695   case 0:
12696     return false;
12697 
12698   default:
12699     if (!Args[1]->isDefaultArgument())
12700       return false;
12701 
12702     LLVM_FALLTHROUGH;
12703   case 1:
12704     return !Args[0]->isDefaultArgument();
12705   }
12706 
12707   return false;
12708 }
12709 
12710 ExprResult
12711 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12712                             NamedDecl *FoundDecl,
12713                             CXXConstructorDecl *Constructor,
12714                             MultiExprArg ExprArgs,
12715                             bool HadMultipleCandidates,
12716                             bool IsListInitialization,
12717                             bool IsStdInitListInitialization,
12718                             bool RequiresZeroInit,
12719                             unsigned ConstructKind,
12720                             SourceRange ParenRange) {
12721   bool Elidable = false;
12722 
12723   // C++0x [class.copy]p34:
12724   //   When certain criteria are met, an implementation is allowed to
12725   //   omit the copy/move construction of a class object, even if the
12726   //   copy/move constructor and/or destructor for the object have
12727   //   side effects. [...]
12728   //     - when a temporary class object that has not been bound to a
12729   //       reference (12.2) would be copied/moved to a class object
12730   //       with the same cv-unqualified type, the copy/move operation
12731   //       can be omitted by constructing the temporary object
12732   //       directly into the target of the omitted copy/move
12733   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12734       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12735     Expr *SubExpr = ExprArgs[0];
12736     Elidable = SubExpr->isTemporaryObject(
12737         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12738   }
12739 
12740   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12741                                FoundDecl, Constructor,
12742                                Elidable, ExprArgs, HadMultipleCandidates,
12743                                IsListInitialization,
12744                                IsStdInitListInitialization, RequiresZeroInit,
12745                                ConstructKind, ParenRange);
12746 }
12747 
12748 ExprResult
12749 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12750                             NamedDecl *FoundDecl,
12751                             CXXConstructorDecl *Constructor,
12752                             bool Elidable,
12753                             MultiExprArg ExprArgs,
12754                             bool HadMultipleCandidates,
12755                             bool IsListInitialization,
12756                             bool IsStdInitListInitialization,
12757                             bool RequiresZeroInit,
12758                             unsigned ConstructKind,
12759                             SourceRange ParenRange) {
12760   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12761     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12762     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12763       return ExprError();
12764   }
12765 
12766   return BuildCXXConstructExpr(
12767       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12768       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12769       RequiresZeroInit, ConstructKind, ParenRange);
12770 }
12771 
12772 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12773 /// including handling of its default argument expressions.
12774 ExprResult
12775 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12776                             CXXConstructorDecl *Constructor,
12777                             bool Elidable,
12778                             MultiExprArg ExprArgs,
12779                             bool HadMultipleCandidates,
12780                             bool IsListInitialization,
12781                             bool IsStdInitListInitialization,
12782                             bool RequiresZeroInit,
12783                             unsigned ConstructKind,
12784                             SourceRange ParenRange) {
12785   assert(declaresSameEntity(
12786              Constructor->getParent(),
12787              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12788          "given constructor for wrong type");
12789   MarkFunctionReferenced(ConstructLoc, Constructor);
12790   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12791     return ExprError();
12792 
12793   return CXXConstructExpr::Create(
12794       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12795       ExprArgs, HadMultipleCandidates, IsListInitialization,
12796       IsStdInitListInitialization, RequiresZeroInit,
12797       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12798       ParenRange);
12799 }
12800 
12801 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12802   assert(Field->hasInClassInitializer());
12803 
12804   // If we already have the in-class initializer nothing needs to be done.
12805   if (Field->getInClassInitializer())
12806     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12807 
12808   // If we might have already tried and failed to instantiate, don't try again.
12809   if (Field->isInvalidDecl())
12810     return ExprError();
12811 
12812   // Maybe we haven't instantiated the in-class initializer. Go check the
12813   // pattern FieldDecl to see if it has one.
12814   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12815 
12816   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12817     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12818     DeclContext::lookup_result Lookup =
12819         ClassPattern->lookup(Field->getDeclName());
12820 
12821     // Lookup can return at most two results: the pattern for the field, or the
12822     // injected class name of the parent record. No other member can have the
12823     // same name as the field.
12824     // In modules mode, lookup can return multiple results (coming from
12825     // different modules).
12826     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12827            "more than two lookup results for field name");
12828     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12829     if (!Pattern) {
12830       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12831              "cannot have other non-field member with same name");
12832       for (auto L : Lookup)
12833         if (isa<FieldDecl>(L)) {
12834           Pattern = cast<FieldDecl>(L);
12835           break;
12836         }
12837       assert(Pattern && "We must have set the Pattern!");
12838     }
12839 
12840     if (!Pattern->hasInClassInitializer() ||
12841         InstantiateInClassInitializer(Loc, Field, Pattern,
12842                                       getTemplateInstantiationArgs(Field))) {
12843       // Don't diagnose this again.
12844       Field->setInvalidDecl();
12845       return ExprError();
12846     }
12847     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12848   }
12849 
12850   // DR1351:
12851   //   If the brace-or-equal-initializer of a non-static data member
12852   //   invokes a defaulted default constructor of its class or of an
12853   //   enclosing class in a potentially evaluated subexpression, the
12854   //   program is ill-formed.
12855   //
12856   // This resolution is unworkable: the exception specification of the
12857   // default constructor can be needed in an unevaluated context, in
12858   // particular, in the operand of a noexcept-expression, and we can be
12859   // unable to compute an exception specification for an enclosed class.
12860   //
12861   // Any attempt to resolve the exception specification of a defaulted default
12862   // constructor before the initializer is lexically complete will ultimately
12863   // come here at which point we can diagnose it.
12864   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12865   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12866       << OutermostClass << Field;
12867   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12868   // Recover by marking the field invalid, unless we're in a SFINAE context.
12869   if (!isSFINAEContext())
12870     Field->setInvalidDecl();
12871   return ExprError();
12872 }
12873 
12874 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12875   if (VD->isInvalidDecl()) return;
12876 
12877   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12878   if (ClassDecl->isInvalidDecl()) return;
12879   if (ClassDecl->hasIrrelevantDestructor()) return;
12880   if (ClassDecl->isDependentContext()) return;
12881 
12882   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12883   MarkFunctionReferenced(VD->getLocation(), Destructor);
12884   CheckDestructorAccess(VD->getLocation(), Destructor,
12885                         PDiag(diag::err_access_dtor_var)
12886                         << VD->getDeclName()
12887                         << VD->getType());
12888   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12889 
12890   if (Destructor->isTrivial()) return;
12891   if (!VD->hasGlobalStorage()) return;
12892 
12893   // Emit warning for non-trivial dtor in global scope (a real global,
12894   // class-static, function-static).
12895   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12896 
12897   // TODO: this should be re-enabled for static locals by !CXAAtExit
12898   if (!VD->isStaticLocal())
12899     Diag(VD->getLocation(), diag::warn_global_destructor);
12900 }
12901 
12902 /// Given a constructor and the set of arguments provided for the
12903 /// constructor, convert the arguments and add any required default arguments
12904 /// to form a proper call to this constructor.
12905 ///
12906 /// \returns true if an error occurred, false otherwise.
12907 bool
12908 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12909                               MultiExprArg ArgsPtr,
12910                               SourceLocation Loc,
12911                               SmallVectorImpl<Expr*> &ConvertedArgs,
12912                               bool AllowExplicit,
12913                               bool IsListInitialization) {
12914   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12915   unsigned NumArgs = ArgsPtr.size();
12916   Expr **Args = ArgsPtr.data();
12917 
12918   const FunctionProtoType *Proto
12919     = Constructor->getType()->getAs<FunctionProtoType>();
12920   assert(Proto && "Constructor without a prototype?");
12921   unsigned NumParams = Proto->getNumParams();
12922 
12923   // If too few arguments are available, we'll fill in the rest with defaults.
12924   if (NumArgs < NumParams)
12925     ConvertedArgs.reserve(NumParams);
12926   else
12927     ConvertedArgs.reserve(NumArgs);
12928 
12929   VariadicCallType CallType =
12930     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12931   SmallVector<Expr *, 8> AllArgs;
12932   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12933                                         Proto, 0,
12934                                         llvm::makeArrayRef(Args, NumArgs),
12935                                         AllArgs,
12936                                         CallType, AllowExplicit,
12937                                         IsListInitialization);
12938   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12939 
12940   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12941 
12942   CheckConstructorCall(Constructor,
12943                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12944                        Proto, Loc);
12945 
12946   return Invalid;
12947 }
12948 
12949 static inline bool
12950 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12951                                        const FunctionDecl *FnDecl) {
12952   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12953   if (isa<NamespaceDecl>(DC)) {
12954     return SemaRef.Diag(FnDecl->getLocation(),
12955                         diag::err_operator_new_delete_declared_in_namespace)
12956       << FnDecl->getDeclName();
12957   }
12958 
12959   if (isa<TranslationUnitDecl>(DC) &&
12960       FnDecl->getStorageClass() == SC_Static) {
12961     return SemaRef.Diag(FnDecl->getLocation(),
12962                         diag::err_operator_new_delete_declared_static)
12963       << FnDecl->getDeclName();
12964   }
12965 
12966   return false;
12967 }
12968 
12969 static inline bool
12970 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12971                             CanQualType ExpectedResultType,
12972                             CanQualType ExpectedFirstParamType,
12973                             unsigned DependentParamTypeDiag,
12974                             unsigned InvalidParamTypeDiag) {
12975   QualType ResultType =
12976       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12977 
12978   // Check that the result type is not dependent.
12979   if (ResultType->isDependentType())
12980     return SemaRef.Diag(FnDecl->getLocation(),
12981                         diag::err_operator_new_delete_dependent_result_type)
12982     << FnDecl->getDeclName() << ExpectedResultType;
12983 
12984   // Check that the result type is what we expect.
12985   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12986     return SemaRef.Diag(FnDecl->getLocation(),
12987                         diag::err_operator_new_delete_invalid_result_type)
12988     << FnDecl->getDeclName() << ExpectedResultType;
12989 
12990   // A function template must have at least 2 parameters.
12991   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12992     return SemaRef.Diag(FnDecl->getLocation(),
12993                       diag::err_operator_new_delete_template_too_few_parameters)
12994         << FnDecl->getDeclName();
12995 
12996   // The function decl must have at least 1 parameter.
12997   if (FnDecl->getNumParams() == 0)
12998     return SemaRef.Diag(FnDecl->getLocation(),
12999                         diag::err_operator_new_delete_too_few_parameters)
13000       << FnDecl->getDeclName();
13001 
13002   // Check the first parameter type is not dependent.
13003   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13004   if (FirstParamType->isDependentType())
13005     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13006       << FnDecl->getDeclName() << ExpectedFirstParamType;
13007 
13008   // Check that the first parameter type is what we expect.
13009   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13010       ExpectedFirstParamType)
13011     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13012     << FnDecl->getDeclName() << ExpectedFirstParamType;
13013 
13014   return false;
13015 }
13016 
13017 static bool
13018 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13019   // C++ [basic.stc.dynamic.allocation]p1:
13020   //   A program is ill-formed if an allocation function is declared in a
13021   //   namespace scope other than global scope or declared static in global
13022   //   scope.
13023   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13024     return true;
13025 
13026   CanQualType SizeTy =
13027     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13028 
13029   // C++ [basic.stc.dynamic.allocation]p1:
13030   //  The return type shall be void*. The first parameter shall have type
13031   //  std::size_t.
13032   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13033                                   SizeTy,
13034                                   diag::err_operator_new_dependent_param_type,
13035                                   diag::err_operator_new_param_type))
13036     return true;
13037 
13038   // C++ [basic.stc.dynamic.allocation]p1:
13039   //  The first parameter shall not have an associated default argument.
13040   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13041     return SemaRef.Diag(FnDecl->getLocation(),
13042                         diag::err_operator_new_default_arg)
13043       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13044 
13045   return false;
13046 }
13047 
13048 static bool
13049 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13050   // C++ [basic.stc.dynamic.deallocation]p1:
13051   //   A program is ill-formed if deallocation functions are declared in a
13052   //   namespace scope other than global scope or declared static in global
13053   //   scope.
13054   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13055     return true;
13056 
13057   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13058 
13059   // C++ P0722:
13060   //   Within a class C, the first parameter of a destroying operator delete
13061   //   shall be of type C *. The first parameter of any other deallocation
13062   //   function shall be of type void *.
13063   CanQualType ExpectedFirstParamType =
13064       MD && MD->isDestroyingOperatorDelete()
13065           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13066                 SemaRef.Context.getRecordType(MD->getParent())))
13067           : SemaRef.Context.VoidPtrTy;
13068 
13069   // C++ [basic.stc.dynamic.deallocation]p2:
13070   //   Each deallocation function shall return void
13071   if (CheckOperatorNewDeleteTypes(
13072           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13073           diag::err_operator_delete_dependent_param_type,
13074           diag::err_operator_delete_param_type))
13075     return true;
13076 
13077   // C++ P0722:
13078   //   A destroying operator delete shall be a usual deallocation function.
13079   if (MD && !MD->getParent()->isDependentContext() &&
13080       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
13081     SemaRef.Diag(MD->getLocation(),
13082                  diag::err_destroying_operator_delete_not_usual);
13083     return true;
13084   }
13085 
13086   return false;
13087 }
13088 
13089 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13090 /// of this overloaded operator is well-formed. If so, returns false;
13091 /// otherwise, emits appropriate diagnostics and returns true.
13092 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13093   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13094          "Expected an overloaded operator declaration");
13095 
13096   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13097 
13098   // C++ [over.oper]p5:
13099   //   The allocation and deallocation functions, operator new,
13100   //   operator new[], operator delete and operator delete[], are
13101   //   described completely in 3.7.3. The attributes and restrictions
13102   //   found in the rest of this subclause do not apply to them unless
13103   //   explicitly stated in 3.7.3.
13104   if (Op == OO_Delete || Op == OO_Array_Delete)
13105     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13106 
13107   if (Op == OO_New || Op == OO_Array_New)
13108     return CheckOperatorNewDeclaration(*this, FnDecl);
13109 
13110   // C++ [over.oper]p6:
13111   //   An operator function shall either be a non-static member
13112   //   function or be a non-member function and have at least one
13113   //   parameter whose type is a class, a reference to a class, an
13114   //   enumeration, or a reference to an enumeration.
13115   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13116     if (MethodDecl->isStatic())
13117       return Diag(FnDecl->getLocation(),
13118                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13119   } else {
13120     bool ClassOrEnumParam = false;
13121     for (auto Param : FnDecl->parameters()) {
13122       QualType ParamType = Param->getType().getNonReferenceType();
13123       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13124           ParamType->isEnumeralType()) {
13125         ClassOrEnumParam = true;
13126         break;
13127       }
13128     }
13129 
13130     if (!ClassOrEnumParam)
13131       return Diag(FnDecl->getLocation(),
13132                   diag::err_operator_overload_needs_class_or_enum)
13133         << FnDecl->getDeclName();
13134   }
13135 
13136   // C++ [over.oper]p8:
13137   //   An operator function cannot have default arguments (8.3.6),
13138   //   except where explicitly stated below.
13139   //
13140   // Only the function-call operator allows default arguments
13141   // (C++ [over.call]p1).
13142   if (Op != OO_Call) {
13143     for (auto Param : FnDecl->parameters()) {
13144       if (Param->hasDefaultArg())
13145         return Diag(Param->getLocation(),
13146                     diag::err_operator_overload_default_arg)
13147           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13148     }
13149   }
13150 
13151   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13152     { false, false, false }
13153 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13154     , { Unary, Binary, MemberOnly }
13155 #include "clang/Basic/OperatorKinds.def"
13156   };
13157 
13158   bool CanBeUnaryOperator = OperatorUses[Op][0];
13159   bool CanBeBinaryOperator = OperatorUses[Op][1];
13160   bool MustBeMemberOperator = OperatorUses[Op][2];
13161 
13162   // C++ [over.oper]p8:
13163   //   [...] Operator functions cannot have more or fewer parameters
13164   //   than the number required for the corresponding operator, as
13165   //   described in the rest of this subclause.
13166   unsigned NumParams = FnDecl->getNumParams()
13167                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13168   if (Op != OO_Call &&
13169       ((NumParams == 1 && !CanBeUnaryOperator) ||
13170        (NumParams == 2 && !CanBeBinaryOperator) ||
13171        (NumParams < 1) || (NumParams > 2))) {
13172     // We have the wrong number of parameters.
13173     unsigned ErrorKind;
13174     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13175       ErrorKind = 2;  // 2 -> unary or binary.
13176     } else if (CanBeUnaryOperator) {
13177       ErrorKind = 0;  // 0 -> unary
13178     } else {
13179       assert(CanBeBinaryOperator &&
13180              "All non-call overloaded operators are unary or binary!");
13181       ErrorKind = 1;  // 1 -> binary
13182     }
13183 
13184     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13185       << FnDecl->getDeclName() << NumParams << ErrorKind;
13186   }
13187 
13188   // Overloaded operators other than operator() cannot be variadic.
13189   if (Op != OO_Call &&
13190       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13191     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13192       << FnDecl->getDeclName();
13193   }
13194 
13195   // Some operators must be non-static member functions.
13196   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13197     return Diag(FnDecl->getLocation(),
13198                 diag::err_operator_overload_must_be_member)
13199       << FnDecl->getDeclName();
13200   }
13201 
13202   // C++ [over.inc]p1:
13203   //   The user-defined function called operator++ implements the
13204   //   prefix and postfix ++ operator. If this function is a member
13205   //   function with no parameters, or a non-member function with one
13206   //   parameter of class or enumeration type, it defines the prefix
13207   //   increment operator ++ for objects of that type. If the function
13208   //   is a member function with one parameter (which shall be of type
13209   //   int) or a non-member function with two parameters (the second
13210   //   of which shall be of type int), it defines the postfix
13211   //   increment operator ++ for objects of that type.
13212   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13213     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13214     QualType ParamType = LastParam->getType();
13215 
13216     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13217         !ParamType->isDependentType())
13218       return Diag(LastParam->getLocation(),
13219                   diag::err_operator_overload_post_incdec_must_be_int)
13220         << LastParam->getType() << (Op == OO_MinusMinus);
13221   }
13222 
13223   return false;
13224 }
13225 
13226 static bool
13227 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13228                                           FunctionTemplateDecl *TpDecl) {
13229   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13230 
13231   // Must have one or two template parameters.
13232   if (TemplateParams->size() == 1) {
13233     NonTypeTemplateParmDecl *PmDecl =
13234         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13235 
13236     // The template parameter must be a char parameter pack.
13237     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13238         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13239       return false;
13240 
13241   } else if (TemplateParams->size() == 2) {
13242     TemplateTypeParmDecl *PmType =
13243         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13244     NonTypeTemplateParmDecl *PmArgs =
13245         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13246 
13247     // The second template parameter must be a parameter pack with the
13248     // first template parameter as its type.
13249     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13250         PmArgs->isTemplateParameterPack()) {
13251       const TemplateTypeParmType *TArgs =
13252           PmArgs->getType()->getAs<TemplateTypeParmType>();
13253       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13254           TArgs->getIndex() == PmType->getIndex()) {
13255         if (!SemaRef.inTemplateInstantiation())
13256           SemaRef.Diag(TpDecl->getLocation(),
13257                        diag::ext_string_literal_operator_template);
13258         return false;
13259       }
13260     }
13261   }
13262 
13263   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13264                diag::err_literal_operator_template)
13265       << TpDecl->getTemplateParameters()->getSourceRange();
13266   return true;
13267 }
13268 
13269 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13270 /// of this literal operator function is well-formed. If so, returns
13271 /// false; otherwise, emits appropriate diagnostics and returns true.
13272 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13273   if (isa<CXXMethodDecl>(FnDecl)) {
13274     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13275       << FnDecl->getDeclName();
13276     return true;
13277   }
13278 
13279   if (FnDecl->isExternC()) {
13280     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13281     if (const LinkageSpecDecl *LSD =
13282             FnDecl->getDeclContext()->getExternCContext())
13283       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13284     return true;
13285   }
13286 
13287   // This might be the definition of a literal operator template.
13288   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13289 
13290   // This might be a specialization of a literal operator template.
13291   if (!TpDecl)
13292     TpDecl = FnDecl->getPrimaryTemplate();
13293 
13294   // template <char...> type operator "" name() and
13295   // template <class T, T...> type operator "" name() are the only valid
13296   // template signatures, and the only valid signatures with no parameters.
13297   if (TpDecl) {
13298     if (FnDecl->param_size() != 0) {
13299       Diag(FnDecl->getLocation(),
13300            diag::err_literal_operator_template_with_params);
13301       return true;
13302     }
13303 
13304     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13305       return true;
13306 
13307   } else if (FnDecl->param_size() == 1) {
13308     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13309 
13310     QualType ParamType = Param->getType().getUnqualifiedType();
13311 
13312     // Only unsigned long long int, long double, any character type, and const
13313     // char * are allowed as the only parameters.
13314     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13315         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13316         Context.hasSameType(ParamType, Context.CharTy) ||
13317         Context.hasSameType(ParamType, Context.WideCharTy) ||
13318         Context.hasSameType(ParamType, Context.Char8Ty) ||
13319         Context.hasSameType(ParamType, Context.Char16Ty) ||
13320         Context.hasSameType(ParamType, Context.Char32Ty)) {
13321     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13322       QualType InnerType = Ptr->getPointeeType();
13323 
13324       // Pointer parameter must be a const char *.
13325       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13326                                 Context.CharTy) &&
13327             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13328         Diag(Param->getSourceRange().getBegin(),
13329              diag::err_literal_operator_param)
13330             << ParamType << "'const char *'" << Param->getSourceRange();
13331         return true;
13332       }
13333 
13334     } else if (ParamType->isRealFloatingType()) {
13335       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13336           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13337       return true;
13338 
13339     } else if (ParamType->isIntegerType()) {
13340       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13341           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13342       return true;
13343 
13344     } else {
13345       Diag(Param->getSourceRange().getBegin(),
13346            diag::err_literal_operator_invalid_param)
13347           << ParamType << Param->getSourceRange();
13348       return true;
13349     }
13350 
13351   } else if (FnDecl->param_size() == 2) {
13352     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13353 
13354     // First, verify that the first parameter is correct.
13355 
13356     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13357 
13358     // Two parameter function must have a pointer to const as a
13359     // first parameter; let's strip those qualifiers.
13360     const PointerType *PT = FirstParamType->getAs<PointerType>();
13361 
13362     if (!PT) {
13363       Diag((*Param)->getSourceRange().getBegin(),
13364            diag::err_literal_operator_param)
13365           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13366       return true;
13367     }
13368 
13369     QualType PointeeType = PT->getPointeeType();
13370     // First parameter must be const
13371     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13372       Diag((*Param)->getSourceRange().getBegin(),
13373            diag::err_literal_operator_param)
13374           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13375       return true;
13376     }
13377 
13378     QualType InnerType = PointeeType.getUnqualifiedType();
13379     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13380     // const char32_t* are allowed as the first parameter to a two-parameter
13381     // function
13382     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13383           Context.hasSameType(InnerType, Context.WideCharTy) ||
13384           Context.hasSameType(InnerType, Context.Char8Ty) ||
13385           Context.hasSameType(InnerType, Context.Char16Ty) ||
13386           Context.hasSameType(InnerType, Context.Char32Ty))) {
13387       Diag((*Param)->getSourceRange().getBegin(),
13388            diag::err_literal_operator_param)
13389           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13390       return true;
13391     }
13392 
13393     // Move on to the second and final parameter.
13394     ++Param;
13395 
13396     // The second parameter must be a std::size_t.
13397     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13398     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13399       Diag((*Param)->getSourceRange().getBegin(),
13400            diag::err_literal_operator_param)
13401           << SecondParamType << Context.getSizeType()
13402           << (*Param)->getSourceRange();
13403       return true;
13404     }
13405   } else {
13406     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13407     return true;
13408   }
13409 
13410   // Parameters are good.
13411 
13412   // A parameter-declaration-clause containing a default argument is not
13413   // equivalent to any of the permitted forms.
13414   for (auto Param : FnDecl->parameters()) {
13415     if (Param->hasDefaultArg()) {
13416       Diag(Param->getDefaultArgRange().getBegin(),
13417            diag::err_literal_operator_default_argument)
13418         << Param->getDefaultArgRange();
13419       break;
13420     }
13421   }
13422 
13423   StringRef LiteralName
13424     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13425   if (LiteralName[0] != '_' &&
13426       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13427     // C++11 [usrlit.suffix]p1:
13428     //   Literal suffix identifiers that do not start with an underscore
13429     //   are reserved for future standardization.
13430     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13431       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13432   }
13433 
13434   return false;
13435 }
13436 
13437 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13438 /// linkage specification, including the language and (if present)
13439 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13440 /// language string literal. LBraceLoc, if valid, provides the location of
13441 /// the '{' brace. Otherwise, this linkage specification does not
13442 /// have any braces.
13443 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13444                                            Expr *LangStr,
13445                                            SourceLocation LBraceLoc) {
13446   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13447   if (!Lit->isAscii()) {
13448     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13449       << LangStr->getSourceRange();
13450     return nullptr;
13451   }
13452 
13453   StringRef Lang = Lit->getString();
13454   LinkageSpecDecl::LanguageIDs Language;
13455   if (Lang == "C")
13456     Language = LinkageSpecDecl::lang_c;
13457   else if (Lang == "C++")
13458     Language = LinkageSpecDecl::lang_cxx;
13459   else {
13460     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13461       << LangStr->getSourceRange();
13462     return nullptr;
13463   }
13464 
13465   // FIXME: Add all the various semantics of linkage specifications
13466 
13467   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13468                                                LangStr->getExprLoc(), Language,
13469                                                LBraceLoc.isValid());
13470   CurContext->addDecl(D);
13471   PushDeclContext(S, D);
13472   return D;
13473 }
13474 
13475 /// ActOnFinishLinkageSpecification - Complete the definition of
13476 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13477 /// valid, it's the position of the closing '}' brace in a linkage
13478 /// specification that uses braces.
13479 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13480                                             Decl *LinkageSpec,
13481                                             SourceLocation RBraceLoc) {
13482   if (RBraceLoc.isValid()) {
13483     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13484     LSDecl->setRBraceLoc(RBraceLoc);
13485   }
13486   PopDeclContext();
13487   return LinkageSpec;
13488 }
13489 
13490 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13491                                   AttributeList *AttrList,
13492                                   SourceLocation SemiLoc) {
13493   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13494   // Attribute declarations appertain to empty declaration so we handle
13495   // them here.
13496   if (AttrList)
13497     ProcessDeclAttributeList(S, ED, AttrList);
13498 
13499   CurContext->addDecl(ED);
13500   return ED;
13501 }
13502 
13503 /// Perform semantic analysis for the variable declaration that
13504 /// occurs within a C++ catch clause, returning the newly-created
13505 /// variable.
13506 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13507                                          TypeSourceInfo *TInfo,
13508                                          SourceLocation StartLoc,
13509                                          SourceLocation Loc,
13510                                          IdentifierInfo *Name) {
13511   bool Invalid = false;
13512   QualType ExDeclType = TInfo->getType();
13513 
13514   // Arrays and functions decay.
13515   if (ExDeclType->isArrayType())
13516     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13517   else if (ExDeclType->isFunctionType())
13518     ExDeclType = Context.getPointerType(ExDeclType);
13519 
13520   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13521   // The exception-declaration shall not denote a pointer or reference to an
13522   // incomplete type, other than [cv] void*.
13523   // N2844 forbids rvalue references.
13524   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13525     Diag(Loc, diag::err_catch_rvalue_ref);
13526     Invalid = true;
13527   }
13528 
13529   if (ExDeclType->isVariablyModifiedType()) {
13530     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13531     Invalid = true;
13532   }
13533 
13534   QualType BaseType = ExDeclType;
13535   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13536   unsigned DK = diag::err_catch_incomplete;
13537   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13538     BaseType = Ptr->getPointeeType();
13539     Mode = 1;
13540     DK = diag::err_catch_incomplete_ptr;
13541   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13542     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13543     BaseType = Ref->getPointeeType();
13544     Mode = 2;
13545     DK = diag::err_catch_incomplete_ref;
13546   }
13547   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13548       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13549     Invalid = true;
13550 
13551   if (!Invalid && !ExDeclType->isDependentType() &&
13552       RequireNonAbstractType(Loc, ExDeclType,
13553                              diag::err_abstract_type_in_decl,
13554                              AbstractVariableType))
13555     Invalid = true;
13556 
13557   // Only the non-fragile NeXT runtime currently supports C++ catches
13558   // of ObjC types, and no runtime supports catching ObjC types by value.
13559   if (!Invalid && getLangOpts().ObjC1) {
13560     QualType T = ExDeclType;
13561     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13562       T = RT->getPointeeType();
13563 
13564     if (T->isObjCObjectType()) {
13565       Diag(Loc, diag::err_objc_object_catch);
13566       Invalid = true;
13567     } else if (T->isObjCObjectPointerType()) {
13568       // FIXME: should this be a test for macosx-fragile specifically?
13569       if (getLangOpts().ObjCRuntime.isFragile())
13570         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13571     }
13572   }
13573 
13574   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13575                                     ExDeclType, TInfo, SC_None);
13576   ExDecl->setExceptionVariable(true);
13577 
13578   // In ARC, infer 'retaining' for variables of retainable type.
13579   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13580     Invalid = true;
13581 
13582   if (!Invalid && !ExDeclType->isDependentType()) {
13583     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13584       // Insulate this from anything else we might currently be parsing.
13585       EnterExpressionEvaluationContext scope(
13586           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13587 
13588       // C++ [except.handle]p16:
13589       //   The object declared in an exception-declaration or, if the
13590       //   exception-declaration does not specify a name, a temporary (12.2) is
13591       //   copy-initialized (8.5) from the exception object. [...]
13592       //   The object is destroyed when the handler exits, after the destruction
13593       //   of any automatic objects initialized within the handler.
13594       //
13595       // We just pretend to initialize the object with itself, then make sure
13596       // it can be destroyed later.
13597       QualType initType = Context.getExceptionObjectType(ExDeclType);
13598 
13599       InitializedEntity entity =
13600         InitializedEntity::InitializeVariable(ExDecl);
13601       InitializationKind initKind =
13602         InitializationKind::CreateCopy(Loc, SourceLocation());
13603 
13604       Expr *opaqueValue =
13605         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13606       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13607       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13608       if (result.isInvalid())
13609         Invalid = true;
13610       else {
13611         // If the constructor used was non-trivial, set this as the
13612         // "initializer".
13613         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13614         if (!construct->getConstructor()->isTrivial()) {
13615           Expr *init = MaybeCreateExprWithCleanups(construct);
13616           ExDecl->setInit(init);
13617         }
13618 
13619         // And make sure it's destructable.
13620         FinalizeVarWithDestructor(ExDecl, recordType);
13621       }
13622     }
13623   }
13624 
13625   if (Invalid)
13626     ExDecl->setInvalidDecl();
13627 
13628   return ExDecl;
13629 }
13630 
13631 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13632 /// handler.
13633 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13634   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13635   bool Invalid = D.isInvalidType();
13636 
13637   // Check for unexpanded parameter packs.
13638   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13639                                       UPPC_ExceptionType)) {
13640     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13641                                              D.getIdentifierLoc());
13642     Invalid = true;
13643   }
13644 
13645   IdentifierInfo *II = D.getIdentifier();
13646   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13647                                              LookupOrdinaryName,
13648                                              ForVisibleRedeclaration)) {
13649     // The scope should be freshly made just for us. There is just no way
13650     // it contains any previous declaration, except for function parameters in
13651     // a function-try-block's catch statement.
13652     assert(!S->isDeclScope(PrevDecl));
13653     if (isDeclInScope(PrevDecl, CurContext, S)) {
13654       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13655         << D.getIdentifier();
13656       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13657       Invalid = true;
13658     } else if (PrevDecl->isTemplateParameter())
13659       // Maybe we will complain about the shadowed template parameter.
13660       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13661   }
13662 
13663   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13664     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13665       << D.getCXXScopeSpec().getRange();
13666     Invalid = true;
13667   }
13668 
13669   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13670                                               D.getLocStart(),
13671                                               D.getIdentifierLoc(),
13672                                               D.getIdentifier());
13673   if (Invalid)
13674     ExDecl->setInvalidDecl();
13675 
13676   // Add the exception declaration into this scope.
13677   if (II)
13678     PushOnScopeChains(ExDecl, S);
13679   else
13680     CurContext->addDecl(ExDecl);
13681 
13682   ProcessDeclAttributes(S, ExDecl, D);
13683   return ExDecl;
13684 }
13685 
13686 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13687                                          Expr *AssertExpr,
13688                                          Expr *AssertMessageExpr,
13689                                          SourceLocation RParenLoc) {
13690   StringLiteral *AssertMessage =
13691       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13692 
13693   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13694     return nullptr;
13695 
13696   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13697                                       AssertMessage, RParenLoc, false);
13698 }
13699 
13700 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13701                                          Expr *AssertExpr,
13702                                          StringLiteral *AssertMessage,
13703                                          SourceLocation RParenLoc,
13704                                          bool Failed) {
13705   assert(AssertExpr != nullptr && "Expected non-null condition");
13706   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13707       !Failed) {
13708     // In a static_assert-declaration, the constant-expression shall be a
13709     // constant expression that can be contextually converted to bool.
13710     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13711     if (Converted.isInvalid())
13712       Failed = true;
13713 
13714     llvm::APSInt Cond;
13715     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13716           diag::err_static_assert_expression_is_not_constant,
13717           /*AllowFold=*/false).isInvalid())
13718       Failed = true;
13719 
13720     if (!Failed && !Cond) {
13721       SmallString<256> MsgBuffer;
13722       llvm::raw_svector_ostream Msg(MsgBuffer);
13723       if (AssertMessage)
13724         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13725 
13726       Expr *InnerCond = nullptr;
13727       std::string InnerCondDescription;
13728       std::tie(InnerCond, InnerCondDescription) =
13729         findFailedBooleanCondition(Converted.get(),
13730                                    /*AllowTopLevelCond=*/false);
13731       if (InnerCond) {
13732         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13733           << InnerCondDescription << !AssertMessage
13734           << Msg.str() << InnerCond->getSourceRange();
13735       } else {
13736         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13737           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13738       }
13739       Failed = true;
13740     }
13741   }
13742 
13743   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13744                                                   /*DiscardedValue*/false,
13745                                                   /*IsConstexpr*/true);
13746   if (FullAssertExpr.isInvalid())
13747     Failed = true;
13748   else
13749     AssertExpr = FullAssertExpr.get();
13750 
13751   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13752                                         AssertExpr, AssertMessage, RParenLoc,
13753                                         Failed);
13754 
13755   CurContext->addDecl(Decl);
13756   return Decl;
13757 }
13758 
13759 /// Perform semantic analysis of the given friend type declaration.
13760 ///
13761 /// \returns A friend declaration that.
13762 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13763                                       SourceLocation FriendLoc,
13764                                       TypeSourceInfo *TSInfo) {
13765   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13766 
13767   QualType T = TSInfo->getType();
13768   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13769 
13770   // C++03 [class.friend]p2:
13771   //   An elaborated-type-specifier shall be used in a friend declaration
13772   //   for a class.*
13773   //
13774   //   * The class-key of the elaborated-type-specifier is required.
13775   if (!CodeSynthesisContexts.empty()) {
13776     // Do not complain about the form of friend template types during any kind
13777     // of code synthesis. For template instantiation, we will have complained
13778     // when the template was defined.
13779   } else {
13780     if (!T->isElaboratedTypeSpecifier()) {
13781       // If we evaluated the type to a record type, suggest putting
13782       // a tag in front.
13783       if (const RecordType *RT = T->getAs<RecordType>()) {
13784         RecordDecl *RD = RT->getDecl();
13785 
13786         SmallString<16> InsertionText(" ");
13787         InsertionText += RD->getKindName();
13788 
13789         Diag(TypeRange.getBegin(),
13790              getLangOpts().CPlusPlus11 ?
13791                diag::warn_cxx98_compat_unelaborated_friend_type :
13792                diag::ext_unelaborated_friend_type)
13793           << (unsigned) RD->getTagKind()
13794           << T
13795           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13796                                         InsertionText);
13797       } else {
13798         Diag(FriendLoc,
13799              getLangOpts().CPlusPlus11 ?
13800                diag::warn_cxx98_compat_nonclass_type_friend :
13801                diag::ext_nonclass_type_friend)
13802           << T
13803           << TypeRange;
13804       }
13805     } else if (T->getAs<EnumType>()) {
13806       Diag(FriendLoc,
13807            getLangOpts().CPlusPlus11 ?
13808              diag::warn_cxx98_compat_enum_friend :
13809              diag::ext_enum_friend)
13810         << T
13811         << TypeRange;
13812     }
13813 
13814     // C++11 [class.friend]p3:
13815     //   A friend declaration that does not declare a function shall have one
13816     //   of the following forms:
13817     //     friend elaborated-type-specifier ;
13818     //     friend simple-type-specifier ;
13819     //     friend typename-specifier ;
13820     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13821       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13822   }
13823 
13824   //   If the type specifier in a friend declaration designates a (possibly
13825   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13826   //   the friend declaration is ignored.
13827   return FriendDecl::Create(Context, CurContext,
13828                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13829                             FriendLoc);
13830 }
13831 
13832 /// Handle a friend tag declaration where the scope specifier was
13833 /// templated.
13834 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13835                                     unsigned TagSpec, SourceLocation TagLoc,
13836                                     CXXScopeSpec &SS,
13837                                     IdentifierInfo *Name,
13838                                     SourceLocation NameLoc,
13839                                     AttributeList *Attr,
13840                                     MultiTemplateParamsArg TempParamLists) {
13841   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13842 
13843   bool IsMemberSpecialization = false;
13844   bool Invalid = false;
13845 
13846   if (TemplateParameterList *TemplateParams =
13847           MatchTemplateParametersToScopeSpecifier(
13848               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13849               IsMemberSpecialization, Invalid)) {
13850     if (TemplateParams->size() > 0) {
13851       // This is a declaration of a class template.
13852       if (Invalid)
13853         return nullptr;
13854 
13855       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13856                                 NameLoc, Attr, TemplateParams, AS_public,
13857                                 /*ModulePrivateLoc=*/SourceLocation(),
13858                                 FriendLoc, TempParamLists.size() - 1,
13859                                 TempParamLists.data()).get();
13860     } else {
13861       // The "template<>" header is extraneous.
13862       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13863         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13864       IsMemberSpecialization = true;
13865     }
13866   }
13867 
13868   if (Invalid) return nullptr;
13869 
13870   bool isAllExplicitSpecializations = true;
13871   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13872     if (TempParamLists[I]->size()) {
13873       isAllExplicitSpecializations = false;
13874       break;
13875     }
13876   }
13877 
13878   // FIXME: don't ignore attributes.
13879 
13880   // If it's explicit specializations all the way down, just forget
13881   // about the template header and build an appropriate non-templated
13882   // friend.  TODO: for source fidelity, remember the headers.
13883   if (isAllExplicitSpecializations) {
13884     if (SS.isEmpty()) {
13885       bool Owned = false;
13886       bool IsDependent = false;
13887       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13888                       Attr, AS_public,
13889                       /*ModulePrivateLoc=*/SourceLocation(),
13890                       MultiTemplateParamsArg(), Owned, IsDependent,
13891                       /*ScopedEnumKWLoc=*/SourceLocation(),
13892                       /*ScopedEnumUsesClassTag=*/false,
13893                       /*UnderlyingType=*/TypeResult(),
13894                       /*IsTypeSpecifier=*/false,
13895                       /*IsTemplateParamOrArg=*/false);
13896     }
13897 
13898     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13899     ElaboratedTypeKeyword Keyword
13900       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13901     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13902                                    *Name, NameLoc);
13903     if (T.isNull())
13904       return nullptr;
13905 
13906     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13907     if (isa<DependentNameType>(T)) {
13908       DependentNameTypeLoc TL =
13909           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13910       TL.setElaboratedKeywordLoc(TagLoc);
13911       TL.setQualifierLoc(QualifierLoc);
13912       TL.setNameLoc(NameLoc);
13913     } else {
13914       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13915       TL.setElaboratedKeywordLoc(TagLoc);
13916       TL.setQualifierLoc(QualifierLoc);
13917       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13918     }
13919 
13920     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13921                                             TSI, FriendLoc, TempParamLists);
13922     Friend->setAccess(AS_public);
13923     CurContext->addDecl(Friend);
13924     return Friend;
13925   }
13926 
13927   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13928 
13929 
13930 
13931   // Handle the case of a templated-scope friend class.  e.g.
13932   //   template <class T> class A<T>::B;
13933   // FIXME: we don't support these right now.
13934   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13935     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13936   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13937   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13938   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13939   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13940   TL.setElaboratedKeywordLoc(TagLoc);
13941   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13942   TL.setNameLoc(NameLoc);
13943 
13944   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13945                                           TSI, FriendLoc, TempParamLists);
13946   Friend->setAccess(AS_public);
13947   Friend->setUnsupportedFriend(true);
13948   CurContext->addDecl(Friend);
13949   return Friend;
13950 }
13951 
13952 
13953 /// Handle a friend type declaration.  This works in tandem with
13954 /// ActOnTag.
13955 ///
13956 /// Notes on friend class templates:
13957 ///
13958 /// We generally treat friend class declarations as if they were
13959 /// declaring a class.  So, for example, the elaborated type specifier
13960 /// in a friend declaration is required to obey the restrictions of a
13961 /// class-head (i.e. no typedefs in the scope chain), template
13962 /// parameters are required to match up with simple template-ids, &c.
13963 /// However, unlike when declaring a template specialization, it's
13964 /// okay to refer to a template specialization without an empty
13965 /// template parameter declaration, e.g.
13966 ///   friend class A<T>::B<unsigned>;
13967 /// We permit this as a special case; if there are any template
13968 /// parameters present at all, require proper matching, i.e.
13969 ///   template <> template \<class T> friend class A<int>::B;
13970 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13971                                 MultiTemplateParamsArg TempParams) {
13972   SourceLocation Loc = DS.getLocStart();
13973 
13974   assert(DS.isFriendSpecified());
13975   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13976 
13977   // Try to convert the decl specifier to a type.  This works for
13978   // friend templates because ActOnTag never produces a ClassTemplateDecl
13979   // for a TUK_Friend.
13980   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
13981   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13982   QualType T = TSI->getType();
13983   if (TheDeclarator.isInvalidType())
13984     return nullptr;
13985 
13986   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13987     return nullptr;
13988 
13989   // This is definitely an error in C++98.  It's probably meant to
13990   // be forbidden in C++0x, too, but the specification is just
13991   // poorly written.
13992   //
13993   // The problem is with declarations like the following:
13994   //   template <T> friend A<T>::foo;
13995   // where deciding whether a class C is a friend or not now hinges
13996   // on whether there exists an instantiation of A that causes
13997   // 'foo' to equal C.  There are restrictions on class-heads
13998   // (which we declare (by fiat) elaborated friend declarations to
13999   // be) that makes this tractable.
14000   //
14001   // FIXME: handle "template <> friend class A<T>;", which
14002   // is possibly well-formed?  Who even knows?
14003   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14004     Diag(Loc, diag::err_tagless_friend_type_template)
14005       << DS.getSourceRange();
14006     return nullptr;
14007   }
14008 
14009   // C++98 [class.friend]p1: A friend of a class is a function
14010   //   or class that is not a member of the class . . .
14011   // This is fixed in DR77, which just barely didn't make the C++03
14012   // deadline.  It's also a very silly restriction that seriously
14013   // affects inner classes and which nobody else seems to implement;
14014   // thus we never diagnose it, not even in -pedantic.
14015   //
14016   // But note that we could warn about it: it's always useless to
14017   // friend one of your own members (it's not, however, worthless to
14018   // friend a member of an arbitrary specialization of your template).
14019 
14020   Decl *D;
14021   if (!TempParams.empty())
14022     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14023                                    TempParams,
14024                                    TSI,
14025                                    DS.getFriendSpecLoc());
14026   else
14027     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14028 
14029   if (!D)
14030     return nullptr;
14031 
14032   D->setAccess(AS_public);
14033   CurContext->addDecl(D);
14034 
14035   return D;
14036 }
14037 
14038 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14039                                         MultiTemplateParamsArg TemplateParams) {
14040   const DeclSpec &DS = D.getDeclSpec();
14041 
14042   assert(DS.isFriendSpecified());
14043   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14044 
14045   SourceLocation Loc = D.getIdentifierLoc();
14046   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14047 
14048   // C++ [class.friend]p1
14049   //   A friend of a class is a function or class....
14050   // Note that this sees through typedefs, which is intended.
14051   // It *doesn't* see through dependent types, which is correct
14052   // according to [temp.arg.type]p3:
14053   //   If a declaration acquires a function type through a
14054   //   type dependent on a template-parameter and this causes
14055   //   a declaration that does not use the syntactic form of a
14056   //   function declarator to have a function type, the program
14057   //   is ill-formed.
14058   if (!TInfo->getType()->isFunctionType()) {
14059     Diag(Loc, diag::err_unexpected_friend);
14060 
14061     // It might be worthwhile to try to recover by creating an
14062     // appropriate declaration.
14063     return nullptr;
14064   }
14065 
14066   // C++ [namespace.memdef]p3
14067   //  - If a friend declaration in a non-local class first declares a
14068   //    class or function, the friend class or function is a member
14069   //    of the innermost enclosing namespace.
14070   //  - The name of the friend is not found by simple name lookup
14071   //    until a matching declaration is provided in that namespace
14072   //    scope (either before or after the class declaration granting
14073   //    friendship).
14074   //  - If a friend function is called, its name may be found by the
14075   //    name lookup that considers functions from namespaces and
14076   //    classes associated with the types of the function arguments.
14077   //  - When looking for a prior declaration of a class or a function
14078   //    declared as a friend, scopes outside the innermost enclosing
14079   //    namespace scope are not considered.
14080 
14081   CXXScopeSpec &SS = D.getCXXScopeSpec();
14082   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14083   DeclarationName Name = NameInfo.getName();
14084   assert(Name);
14085 
14086   // Check for unexpanded parameter packs.
14087   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14088       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14089       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14090     return nullptr;
14091 
14092   // The context we found the declaration in, or in which we should
14093   // create the declaration.
14094   DeclContext *DC;
14095   Scope *DCScope = S;
14096   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14097                         ForExternalRedeclaration);
14098 
14099   // There are five cases here.
14100   //   - There's no scope specifier and we're in a local class. Only look
14101   //     for functions declared in the immediately-enclosing block scope.
14102   // We recover from invalid scope qualifiers as if they just weren't there.
14103   FunctionDecl *FunctionContainingLocalClass = nullptr;
14104   if ((SS.isInvalid() || !SS.isSet()) &&
14105       (FunctionContainingLocalClass =
14106            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14107     // C++11 [class.friend]p11:
14108     //   If a friend declaration appears in a local class and the name
14109     //   specified is an unqualified name, a prior declaration is
14110     //   looked up without considering scopes that are outside the
14111     //   innermost enclosing non-class scope. For a friend function
14112     //   declaration, if there is no prior declaration, the program is
14113     //   ill-formed.
14114 
14115     // Find the innermost enclosing non-class scope. This is the block
14116     // scope containing the local class definition (or for a nested class,
14117     // the outer local class).
14118     DCScope = S->getFnParent();
14119 
14120     // Look up the function name in the scope.
14121     Previous.clear(LookupLocalFriendName);
14122     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14123 
14124     if (!Previous.empty()) {
14125       // All possible previous declarations must have the same context:
14126       // either they were declared at block scope or they are members of
14127       // one of the enclosing local classes.
14128       DC = Previous.getRepresentativeDecl()->getDeclContext();
14129     } else {
14130       // This is ill-formed, but provide the context that we would have
14131       // declared the function in, if we were permitted to, for error recovery.
14132       DC = FunctionContainingLocalClass;
14133     }
14134     adjustContextForLocalExternDecl(DC);
14135 
14136     // C++ [class.friend]p6:
14137     //   A function can be defined in a friend declaration of a class if and
14138     //   only if the class is a non-local class (9.8), the function name is
14139     //   unqualified, and the function has namespace scope.
14140     if (D.isFunctionDefinition()) {
14141       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14142     }
14143 
14144   //   - There's no scope specifier, in which case we just go to the
14145   //     appropriate scope and look for a function or function template
14146   //     there as appropriate.
14147   } else if (SS.isInvalid() || !SS.isSet()) {
14148     // C++11 [namespace.memdef]p3:
14149     //   If the name in a friend declaration is neither qualified nor
14150     //   a template-id and the declaration is a function or an
14151     //   elaborated-type-specifier, the lookup to determine whether
14152     //   the entity has been previously declared shall not consider
14153     //   any scopes outside the innermost enclosing namespace.
14154     bool isTemplateId =
14155         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14156 
14157     // Find the appropriate context according to the above.
14158     DC = CurContext;
14159 
14160     // Skip class contexts.  If someone can cite chapter and verse
14161     // for this behavior, that would be nice --- it's what GCC and
14162     // EDG do, and it seems like a reasonable intent, but the spec
14163     // really only says that checks for unqualified existing
14164     // declarations should stop at the nearest enclosing namespace,
14165     // not that they should only consider the nearest enclosing
14166     // namespace.
14167     while (DC->isRecord())
14168       DC = DC->getParent();
14169 
14170     DeclContext *LookupDC = DC;
14171     while (LookupDC->isTransparentContext())
14172       LookupDC = LookupDC->getParent();
14173 
14174     while (true) {
14175       LookupQualifiedName(Previous, LookupDC);
14176 
14177       if (!Previous.empty()) {
14178         DC = LookupDC;
14179         break;
14180       }
14181 
14182       if (isTemplateId) {
14183         if (isa<TranslationUnitDecl>(LookupDC)) break;
14184       } else {
14185         if (LookupDC->isFileContext()) break;
14186       }
14187       LookupDC = LookupDC->getParent();
14188     }
14189 
14190     DCScope = getScopeForDeclContext(S, DC);
14191 
14192   //   - There's a non-dependent scope specifier, in which case we
14193   //     compute it and do a previous lookup there for a function
14194   //     or function template.
14195   } else if (!SS.getScopeRep()->isDependent()) {
14196     DC = computeDeclContext(SS);
14197     if (!DC) return nullptr;
14198 
14199     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14200 
14201     LookupQualifiedName(Previous, DC);
14202 
14203     // Ignore things found implicitly in the wrong scope.
14204     // TODO: better diagnostics for this case.  Suggesting the right
14205     // qualified scope would be nice...
14206     LookupResult::Filter F = Previous.makeFilter();
14207     while (F.hasNext()) {
14208       NamedDecl *D = F.next();
14209       if (!DC->InEnclosingNamespaceSetOf(
14210               D->getDeclContext()->getRedeclContext()))
14211         F.erase();
14212     }
14213     F.done();
14214 
14215     if (Previous.empty()) {
14216       D.setInvalidType();
14217       Diag(Loc, diag::err_qualified_friend_not_found)
14218           << Name << TInfo->getType();
14219       return nullptr;
14220     }
14221 
14222     // C++ [class.friend]p1: A friend of a class is a function or
14223     //   class that is not a member of the class . . .
14224     if (DC->Equals(CurContext))
14225       Diag(DS.getFriendSpecLoc(),
14226            getLangOpts().CPlusPlus11 ?
14227              diag::warn_cxx98_compat_friend_is_member :
14228              diag::err_friend_is_member);
14229 
14230     if (D.isFunctionDefinition()) {
14231       // C++ [class.friend]p6:
14232       //   A function can be defined in a friend declaration of a class if and
14233       //   only if the class is a non-local class (9.8), the function name is
14234       //   unqualified, and the function has namespace scope.
14235       SemaDiagnosticBuilder DB
14236         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14237 
14238       DB << SS.getScopeRep();
14239       if (DC->isFileContext())
14240         DB << FixItHint::CreateRemoval(SS.getRange());
14241       SS.clear();
14242     }
14243 
14244   //   - There's a scope specifier that does not match any template
14245   //     parameter lists, in which case we use some arbitrary context,
14246   //     create a method or method template, and wait for instantiation.
14247   //   - There's a scope specifier that does match some template
14248   //     parameter lists, which we don't handle right now.
14249   } else {
14250     if (D.isFunctionDefinition()) {
14251       // C++ [class.friend]p6:
14252       //   A function can be defined in a friend declaration of a class if and
14253       //   only if the class is a non-local class (9.8), the function name is
14254       //   unqualified, and the function has namespace scope.
14255       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14256         << SS.getScopeRep();
14257     }
14258 
14259     DC = CurContext;
14260     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14261   }
14262 
14263   if (!DC->isRecord()) {
14264     int DiagArg = -1;
14265     switch (D.getName().getKind()) {
14266     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14267     case UnqualifiedIdKind::IK_ConstructorName:
14268       DiagArg = 0;
14269       break;
14270     case UnqualifiedIdKind::IK_DestructorName:
14271       DiagArg = 1;
14272       break;
14273     case UnqualifiedIdKind::IK_ConversionFunctionId:
14274       DiagArg = 2;
14275       break;
14276     case UnqualifiedIdKind::IK_DeductionGuideName:
14277       DiagArg = 3;
14278       break;
14279     case UnqualifiedIdKind::IK_Identifier:
14280     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14281     case UnqualifiedIdKind::IK_LiteralOperatorId:
14282     case UnqualifiedIdKind::IK_OperatorFunctionId:
14283     case UnqualifiedIdKind::IK_TemplateId:
14284       break;
14285     }
14286     // This implies that it has to be an operator or function.
14287     if (DiagArg >= 0) {
14288       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14289       return nullptr;
14290     }
14291   }
14292 
14293   // FIXME: This is an egregious hack to cope with cases where the scope stack
14294   // does not contain the declaration context, i.e., in an out-of-line
14295   // definition of a class.
14296   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14297   if (!DCScope) {
14298     FakeDCScope.setEntity(DC);
14299     DCScope = &FakeDCScope;
14300   }
14301 
14302   bool AddToScope = true;
14303   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14304                                           TemplateParams, AddToScope);
14305   if (!ND) return nullptr;
14306 
14307   assert(ND->getLexicalDeclContext() == CurContext);
14308 
14309   // If we performed typo correction, we might have added a scope specifier
14310   // and changed the decl context.
14311   DC = ND->getDeclContext();
14312 
14313   // Add the function declaration to the appropriate lookup tables,
14314   // adjusting the redeclarations list as necessary.  We don't
14315   // want to do this yet if the friending class is dependent.
14316   //
14317   // Also update the scope-based lookup if the target context's
14318   // lookup context is in lexical scope.
14319   if (!CurContext->isDependentContext()) {
14320     DC = DC->getRedeclContext();
14321     DC->makeDeclVisibleInContext(ND);
14322     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14323       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14324   }
14325 
14326   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14327                                        D.getIdentifierLoc(), ND,
14328                                        DS.getFriendSpecLoc());
14329   FrD->setAccess(AS_public);
14330   CurContext->addDecl(FrD);
14331 
14332   if (ND->isInvalidDecl()) {
14333     FrD->setInvalidDecl();
14334   } else {
14335     if (DC->isRecord()) CheckFriendAccess(ND);
14336 
14337     FunctionDecl *FD;
14338     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14339       FD = FTD->getTemplatedDecl();
14340     else
14341       FD = cast<FunctionDecl>(ND);
14342 
14343     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14344     // default argument expression, that declaration shall be a definition
14345     // and shall be the only declaration of the function or function
14346     // template in the translation unit.
14347     if (functionDeclHasDefaultArgument(FD)) {
14348       // We can't look at FD->getPreviousDecl() because it may not have been set
14349       // if we're in a dependent context. If the function is known to be a
14350       // redeclaration, we will have narrowed Previous down to the right decl.
14351       if (D.isRedeclaration()) {
14352         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14353         Diag(Previous.getRepresentativeDecl()->getLocation(),
14354              diag::note_previous_declaration);
14355       } else if (!D.isFunctionDefinition())
14356         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14357     }
14358 
14359     // Mark templated-scope function declarations as unsupported.
14360     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14361       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14362         << SS.getScopeRep() << SS.getRange()
14363         << cast<CXXRecordDecl>(CurContext);
14364       FrD->setUnsupportedFriend(true);
14365     }
14366   }
14367 
14368   return ND;
14369 }
14370 
14371 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14372   AdjustDeclIfTemplate(Dcl);
14373 
14374   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14375   if (!Fn) {
14376     Diag(DelLoc, diag::err_deleted_non_function);
14377     return;
14378   }
14379 
14380   // Deleted function does not have a body.
14381   Fn->setWillHaveBody(false);
14382 
14383   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14384     // Don't consider the implicit declaration we generate for explicit
14385     // specializations. FIXME: Do not generate these implicit declarations.
14386     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14387          Prev->getPreviousDecl()) &&
14388         !Prev->isDefined()) {
14389       Diag(DelLoc, diag::err_deleted_decl_not_first);
14390       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14391            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14392                               : diag::note_previous_declaration);
14393     }
14394     // If the declaration wasn't the first, we delete the function anyway for
14395     // recovery.
14396     Fn = Fn->getCanonicalDecl();
14397   }
14398 
14399   // dllimport/dllexport cannot be deleted.
14400   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14401     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14402     Fn->setInvalidDecl();
14403   }
14404 
14405   if (Fn->isDeleted())
14406     return;
14407 
14408   // See if we're deleting a function which is already known to override a
14409   // non-deleted virtual function.
14410   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14411     bool IssuedDiagnostic = false;
14412     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14413       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14414         if (!IssuedDiagnostic) {
14415           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14416           IssuedDiagnostic = true;
14417         }
14418         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14419       }
14420     }
14421     // If this function was implicitly deleted because it was defaulted,
14422     // explain why it was deleted.
14423     if (IssuedDiagnostic && MD->isDefaulted())
14424       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14425                                 /*Diagnose*/true);
14426   }
14427 
14428   // C++11 [basic.start.main]p3:
14429   //   A program that defines main as deleted [...] is ill-formed.
14430   if (Fn->isMain())
14431     Diag(DelLoc, diag::err_deleted_main);
14432 
14433   // C++11 [dcl.fct.def.delete]p4:
14434   //  A deleted function is implicitly inline.
14435   Fn->setImplicitlyInline();
14436   Fn->setDeletedAsWritten();
14437 }
14438 
14439 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14440   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14441 
14442   if (MD) {
14443     if (MD->getParent()->isDependentType()) {
14444       MD->setDefaulted();
14445       MD->setExplicitlyDefaulted();
14446       return;
14447     }
14448 
14449     CXXSpecialMember Member = getSpecialMember(MD);
14450     if (Member == CXXInvalid) {
14451       if (!MD->isInvalidDecl())
14452         Diag(DefaultLoc, diag::err_default_special_members);
14453       return;
14454     }
14455 
14456     MD->setDefaulted();
14457     MD->setExplicitlyDefaulted();
14458 
14459     // Unset that we will have a body for this function. We might not,
14460     // if it turns out to be trivial, and we don't need this marking now
14461     // that we've marked it as defaulted.
14462     MD->setWillHaveBody(false);
14463 
14464     // If this definition appears within the record, do the checking when
14465     // the record is complete.
14466     const FunctionDecl *Primary = MD;
14467     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14468       // Ask the template instantiation pattern that actually had the
14469       // '= default' on it.
14470       Primary = Pattern;
14471 
14472     // If the method was defaulted on its first declaration, we will have
14473     // already performed the checking in CheckCompletedCXXClass. Such a
14474     // declaration doesn't trigger an implicit definition.
14475     if (Primary->getCanonicalDecl()->isDefaulted())
14476       return;
14477 
14478     CheckExplicitlyDefaultedSpecialMember(MD);
14479 
14480     if (!MD->isInvalidDecl())
14481       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14482   } else {
14483     Diag(DefaultLoc, diag::err_default_special_members);
14484   }
14485 }
14486 
14487 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14488   for (Stmt *SubStmt : S->children()) {
14489     if (!SubStmt)
14490       continue;
14491     if (isa<ReturnStmt>(SubStmt))
14492       Self.Diag(SubStmt->getLocStart(),
14493            diag::err_return_in_constructor_handler);
14494     if (!isa<Expr>(SubStmt))
14495       SearchForReturnInStmt(Self, SubStmt);
14496   }
14497 }
14498 
14499 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14500   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14501     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14502     SearchForReturnInStmt(*this, Handler);
14503   }
14504 }
14505 
14506 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14507                                              const CXXMethodDecl *Old) {
14508   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14509   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14510 
14511   if (OldFT->hasExtParameterInfos()) {
14512     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14513       // A parameter of the overriding method should be annotated with noescape
14514       // if the corresponding parameter of the overridden method is annotated.
14515       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14516           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14517         Diag(New->getParamDecl(I)->getLocation(),
14518              diag::warn_overriding_method_missing_noescape);
14519         Diag(Old->getParamDecl(I)->getLocation(),
14520              diag::note_overridden_marked_noescape);
14521       }
14522   }
14523 
14524   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14525 
14526   // If the calling conventions match, everything is fine
14527   if (NewCC == OldCC)
14528     return false;
14529 
14530   // If the calling conventions mismatch because the new function is static,
14531   // suppress the calling convention mismatch error; the error about static
14532   // function override (err_static_overrides_virtual from
14533   // Sema::CheckFunctionDeclaration) is more clear.
14534   if (New->getStorageClass() == SC_Static)
14535     return false;
14536 
14537   Diag(New->getLocation(),
14538        diag::err_conflicting_overriding_cc_attributes)
14539     << New->getDeclName() << New->getType() << Old->getType();
14540   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14541   return true;
14542 }
14543 
14544 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14545                                              const CXXMethodDecl *Old) {
14546   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14547   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14548 
14549   if (Context.hasSameType(NewTy, OldTy) ||
14550       NewTy->isDependentType() || OldTy->isDependentType())
14551     return false;
14552 
14553   // Check if the return types are covariant
14554   QualType NewClassTy, OldClassTy;
14555 
14556   /// Both types must be pointers or references to classes.
14557   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14558     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14559       NewClassTy = NewPT->getPointeeType();
14560       OldClassTy = OldPT->getPointeeType();
14561     }
14562   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14563     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14564       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14565         NewClassTy = NewRT->getPointeeType();
14566         OldClassTy = OldRT->getPointeeType();
14567       }
14568     }
14569   }
14570 
14571   // The return types aren't either both pointers or references to a class type.
14572   if (NewClassTy.isNull()) {
14573     Diag(New->getLocation(),
14574          diag::err_different_return_type_for_overriding_virtual_function)
14575         << New->getDeclName() << NewTy << OldTy
14576         << New->getReturnTypeSourceRange();
14577     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14578         << Old->getReturnTypeSourceRange();
14579 
14580     return true;
14581   }
14582 
14583   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14584     // C++14 [class.virtual]p8:
14585     //   If the class type in the covariant return type of D::f differs from
14586     //   that of B::f, the class type in the return type of D::f shall be
14587     //   complete at the point of declaration of D::f or shall be the class
14588     //   type D.
14589     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14590       if (!RT->isBeingDefined() &&
14591           RequireCompleteType(New->getLocation(), NewClassTy,
14592                               diag::err_covariant_return_incomplete,
14593                               New->getDeclName()))
14594         return true;
14595     }
14596 
14597     // Check if the new class derives from the old class.
14598     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14599       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14600           << New->getDeclName() << NewTy << OldTy
14601           << New->getReturnTypeSourceRange();
14602       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14603           << Old->getReturnTypeSourceRange();
14604       return true;
14605     }
14606 
14607     // Check if we the conversion from derived to base is valid.
14608     if (CheckDerivedToBaseConversion(
14609             NewClassTy, OldClassTy,
14610             diag::err_covariant_return_inaccessible_base,
14611             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14612             New->getLocation(), New->getReturnTypeSourceRange(),
14613             New->getDeclName(), nullptr)) {
14614       // FIXME: this note won't trigger for delayed access control
14615       // diagnostics, and it's impossible to get an undelayed error
14616       // here from access control during the original parse because
14617       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14618       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14619           << Old->getReturnTypeSourceRange();
14620       return true;
14621     }
14622   }
14623 
14624   // The qualifiers of the return types must be the same.
14625   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14626     Diag(New->getLocation(),
14627          diag::err_covariant_return_type_different_qualifications)
14628         << New->getDeclName() << NewTy << OldTy
14629         << New->getReturnTypeSourceRange();
14630     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14631         << Old->getReturnTypeSourceRange();
14632     return true;
14633   }
14634 
14635 
14636   // The new class type must have the same or less qualifiers as the old type.
14637   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14638     Diag(New->getLocation(),
14639          diag::err_covariant_return_type_class_type_more_qualified)
14640         << New->getDeclName() << NewTy << OldTy
14641         << New->getReturnTypeSourceRange();
14642     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14643         << Old->getReturnTypeSourceRange();
14644     return true;
14645   }
14646 
14647   return false;
14648 }
14649 
14650 /// Mark the given method pure.
14651 ///
14652 /// \param Method the method to be marked pure.
14653 ///
14654 /// \param InitRange the source range that covers the "0" initializer.
14655 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14656   SourceLocation EndLoc = InitRange.getEnd();
14657   if (EndLoc.isValid())
14658     Method->setRangeEnd(EndLoc);
14659 
14660   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14661     Method->setPure();
14662     return false;
14663   }
14664 
14665   if (!Method->isInvalidDecl())
14666     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14667       << Method->getDeclName() << InitRange;
14668   return true;
14669 }
14670 
14671 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14672   if (D->getFriendObjectKind())
14673     Diag(D->getLocation(), diag::err_pure_friend);
14674   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14675     CheckPureMethod(M, ZeroLoc);
14676   else
14677     Diag(D->getLocation(), diag::err_illegal_initializer);
14678 }
14679 
14680 /// Determine whether the given declaration is a global variable or
14681 /// static data member.
14682 static bool isNonlocalVariable(const Decl *D) {
14683   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14684     return Var->hasGlobalStorage();
14685 
14686   return false;
14687 }
14688 
14689 /// Invoked when we are about to parse an initializer for the declaration
14690 /// 'Dcl'.
14691 ///
14692 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14693 /// static data member of class X, names should be looked up in the scope of
14694 /// class X. If the declaration had a scope specifier, a scope will have
14695 /// been created and passed in for this purpose. Otherwise, S will be null.
14696 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14697   // If there is no declaration, there was an error parsing it.
14698   if (!D || D->isInvalidDecl())
14699     return;
14700 
14701   // We will always have a nested name specifier here, but this declaration
14702   // might not be out of line if the specifier names the current namespace:
14703   //   extern int n;
14704   //   int ::n = 0;
14705   if (S && D->isOutOfLine())
14706     EnterDeclaratorContext(S, D->getDeclContext());
14707 
14708   // If we are parsing the initializer for a static data member, push a
14709   // new expression evaluation context that is associated with this static
14710   // data member.
14711   if (isNonlocalVariable(D))
14712     PushExpressionEvaluationContext(
14713         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14714 }
14715 
14716 /// Invoked after we are finished parsing an initializer for the declaration D.
14717 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14718   // If there is no declaration, there was an error parsing it.
14719   if (!D || D->isInvalidDecl())
14720     return;
14721 
14722   if (isNonlocalVariable(D))
14723     PopExpressionEvaluationContext();
14724 
14725   if (S && D->isOutOfLine())
14726     ExitDeclaratorContext(S);
14727 }
14728 
14729 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14730 /// C++ if/switch/while/for statement.
14731 /// e.g: "if (int x = f()) {...}"
14732 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14733   // C++ 6.4p2:
14734   // The declarator shall not specify a function or an array.
14735   // The type-specifier-seq shall not contain typedef and shall not declare a
14736   // new class or enumeration.
14737   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14738          "Parser allowed 'typedef' as storage class of condition decl.");
14739 
14740   Decl *Dcl = ActOnDeclarator(S, D);
14741   if (!Dcl)
14742     return true;
14743 
14744   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14745     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14746       << D.getSourceRange();
14747     return true;
14748   }
14749 
14750   return Dcl;
14751 }
14752 
14753 void Sema::LoadExternalVTableUses() {
14754   if (!ExternalSource)
14755     return;
14756 
14757   SmallVector<ExternalVTableUse, 4> VTables;
14758   ExternalSource->ReadUsedVTables(VTables);
14759   SmallVector<VTableUse, 4> NewUses;
14760   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14761     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14762       = VTablesUsed.find(VTables[I].Record);
14763     // Even if a definition wasn't required before, it may be required now.
14764     if (Pos != VTablesUsed.end()) {
14765       if (!Pos->second && VTables[I].DefinitionRequired)
14766         Pos->second = true;
14767       continue;
14768     }
14769 
14770     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14771     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14772   }
14773 
14774   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14775 }
14776 
14777 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14778                           bool DefinitionRequired) {
14779   // Ignore any vtable uses in unevaluated operands or for classes that do
14780   // not have a vtable.
14781   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14782       CurContext->isDependentContext() || isUnevaluatedContext())
14783     return;
14784 
14785   // Try to insert this class into the map.
14786   LoadExternalVTableUses();
14787   Class = Class->getCanonicalDecl();
14788   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14789     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14790   if (!Pos.second) {
14791     // If we already had an entry, check to see if we are promoting this vtable
14792     // to require a definition. If so, we need to reappend to the VTableUses
14793     // list, since we may have already processed the first entry.
14794     if (DefinitionRequired && !Pos.first->second) {
14795       Pos.first->second = true;
14796     } else {
14797       // Otherwise, we can early exit.
14798       return;
14799     }
14800   } else {
14801     // The Microsoft ABI requires that we perform the destructor body
14802     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14803     // the deleting destructor is emitted with the vtable, not with the
14804     // destructor definition as in the Itanium ABI.
14805     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14806       CXXDestructorDecl *DD = Class->getDestructor();
14807       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14808         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14809           // If this is an out-of-line declaration, marking it referenced will
14810           // not do anything. Manually call CheckDestructor to look up operator
14811           // delete().
14812           ContextRAII SavedContext(*this, DD);
14813           CheckDestructor(DD);
14814         } else {
14815           MarkFunctionReferenced(Loc, Class->getDestructor());
14816         }
14817       }
14818     }
14819   }
14820 
14821   // Local classes need to have their virtual members marked
14822   // immediately. For all other classes, we mark their virtual members
14823   // at the end of the translation unit.
14824   if (Class->isLocalClass())
14825     MarkVirtualMembersReferenced(Loc, Class);
14826   else
14827     VTableUses.push_back(std::make_pair(Class, Loc));
14828 }
14829 
14830 bool Sema::DefineUsedVTables() {
14831   LoadExternalVTableUses();
14832   if (VTableUses.empty())
14833     return false;
14834 
14835   // Note: The VTableUses vector could grow as a result of marking
14836   // the members of a class as "used", so we check the size each
14837   // time through the loop and prefer indices (which are stable) to
14838   // iterators (which are not).
14839   bool DefinedAnything = false;
14840   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14841     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14842     if (!Class)
14843       continue;
14844     TemplateSpecializationKind ClassTSK =
14845         Class->getTemplateSpecializationKind();
14846 
14847     SourceLocation Loc = VTableUses[I].second;
14848 
14849     bool DefineVTable = true;
14850 
14851     // If this class has a key function, but that key function is
14852     // defined in another translation unit, we don't need to emit the
14853     // vtable even though we're using it.
14854     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14855     if (KeyFunction && !KeyFunction->hasBody()) {
14856       // The key function is in another translation unit.
14857       DefineVTable = false;
14858       TemplateSpecializationKind TSK =
14859           KeyFunction->getTemplateSpecializationKind();
14860       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14861              TSK != TSK_ImplicitInstantiation &&
14862              "Instantiations don't have key functions");
14863       (void)TSK;
14864     } else if (!KeyFunction) {
14865       // If we have a class with no key function that is the subject
14866       // of an explicit instantiation declaration, suppress the
14867       // vtable; it will live with the explicit instantiation
14868       // definition.
14869       bool IsExplicitInstantiationDeclaration =
14870           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14871       for (auto R : Class->redecls()) {
14872         TemplateSpecializationKind TSK
14873           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14874         if (TSK == TSK_ExplicitInstantiationDeclaration)
14875           IsExplicitInstantiationDeclaration = true;
14876         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14877           IsExplicitInstantiationDeclaration = false;
14878           break;
14879         }
14880       }
14881 
14882       if (IsExplicitInstantiationDeclaration)
14883         DefineVTable = false;
14884     }
14885 
14886     // The exception specifications for all virtual members may be needed even
14887     // if we are not providing an authoritative form of the vtable in this TU.
14888     // We may choose to emit it available_externally anyway.
14889     if (!DefineVTable) {
14890       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14891       continue;
14892     }
14893 
14894     // Mark all of the virtual members of this class as referenced, so
14895     // that we can build a vtable. Then, tell the AST consumer that a
14896     // vtable for this class is required.
14897     DefinedAnything = true;
14898     MarkVirtualMembersReferenced(Loc, Class);
14899     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
14900     if (VTablesUsed[Canonical])
14901       Consumer.HandleVTable(Class);
14902 
14903     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14904     // no key function or the key function is inlined. Don't warn in C++ ABIs
14905     // that lack key functions, since the user won't be able to make one.
14906     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14907         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14908       const FunctionDecl *KeyFunctionDef = nullptr;
14909       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14910                            KeyFunctionDef->isInlined())) {
14911         Diag(Class->getLocation(),
14912              ClassTSK == TSK_ExplicitInstantiationDefinition
14913                  ? diag::warn_weak_template_vtable
14914                  : diag::warn_weak_vtable)
14915             << Class;
14916       }
14917     }
14918   }
14919   VTableUses.clear();
14920 
14921   return DefinedAnything;
14922 }
14923 
14924 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14925                                                  const CXXRecordDecl *RD) {
14926   for (const auto *I : RD->methods())
14927     if (I->isVirtual() && !I->isPure())
14928       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14929 }
14930 
14931 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14932                                         const CXXRecordDecl *RD) {
14933   // Mark all functions which will appear in RD's vtable as used.
14934   CXXFinalOverriderMap FinalOverriders;
14935   RD->getFinalOverriders(FinalOverriders);
14936   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14937                                             E = FinalOverriders.end();
14938        I != E; ++I) {
14939     for (OverridingMethods::const_iterator OI = I->second.begin(),
14940                                            OE = I->second.end();
14941          OI != OE; ++OI) {
14942       assert(OI->second.size() > 0 && "no final overrider");
14943       CXXMethodDecl *Overrider = OI->second.front().Method;
14944 
14945       // C++ [basic.def.odr]p2:
14946       //   [...] A virtual member function is used if it is not pure. [...]
14947       if (!Overrider->isPure())
14948         MarkFunctionReferenced(Loc, Overrider);
14949     }
14950   }
14951 
14952   // Only classes that have virtual bases need a VTT.
14953   if (RD->getNumVBases() == 0)
14954     return;
14955 
14956   for (const auto &I : RD->bases()) {
14957     const CXXRecordDecl *Base =
14958         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14959     if (Base->getNumVBases() == 0)
14960       continue;
14961     MarkVirtualMembersReferenced(Loc, Base);
14962   }
14963 }
14964 
14965 /// SetIvarInitializers - This routine builds initialization ASTs for the
14966 /// Objective-C implementation whose ivars need be initialized.
14967 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14968   if (!getLangOpts().CPlusPlus)
14969     return;
14970   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14971     SmallVector<ObjCIvarDecl*, 8> ivars;
14972     CollectIvarsToConstructOrDestruct(OID, ivars);
14973     if (ivars.empty())
14974       return;
14975     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14976     for (unsigned i = 0; i < ivars.size(); i++) {
14977       FieldDecl *Field = ivars[i];
14978       if (Field->isInvalidDecl())
14979         continue;
14980 
14981       CXXCtorInitializer *Member;
14982       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14983       InitializationKind InitKind =
14984         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14985 
14986       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14987       ExprResult MemberInit =
14988         InitSeq.Perform(*this, InitEntity, InitKind, None);
14989       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14990       // Note, MemberInit could actually come back empty if no initialization
14991       // is required (e.g., because it would call a trivial default constructor)
14992       if (!MemberInit.get() || MemberInit.isInvalid())
14993         continue;
14994 
14995       Member =
14996         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14997                                          SourceLocation(),
14998                                          MemberInit.getAs<Expr>(),
14999                                          SourceLocation());
15000       AllToInit.push_back(Member);
15001 
15002       // Be sure that the destructor is accessible and is marked as referenced.
15003       if (const RecordType *RecordTy =
15004               Context.getBaseElementType(Field->getType())
15005                   ->getAs<RecordType>()) {
15006         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15007         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15008           MarkFunctionReferenced(Field->getLocation(), Destructor);
15009           CheckDestructorAccess(Field->getLocation(), Destructor,
15010                             PDiag(diag::err_access_dtor_ivar)
15011                               << Context.getBaseElementType(Field->getType()));
15012         }
15013       }
15014     }
15015     ObjCImplementation->setIvarInitializers(Context,
15016                                             AllToInit.data(), AllToInit.size());
15017   }
15018 }
15019 
15020 static
15021 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15022                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
15023                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
15024                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
15025                            Sema &S) {
15026   if (Ctor->isInvalidDecl())
15027     return;
15028 
15029   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15030 
15031   // Target may not be determinable yet, for instance if this is a dependent
15032   // call in an uninstantiated template.
15033   if (Target) {
15034     const FunctionDecl *FNTarget = nullptr;
15035     (void)Target->hasBody(FNTarget);
15036     Target = const_cast<CXXConstructorDecl*>(
15037       cast_or_null<CXXConstructorDecl>(FNTarget));
15038   }
15039 
15040   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15041                      // Avoid dereferencing a null pointer here.
15042                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15043 
15044   if (!Current.insert(Canonical).second)
15045     return;
15046 
15047   // We know that beyond here, we aren't chaining into a cycle.
15048   if (!Target || !Target->isDelegatingConstructor() ||
15049       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15050     Valid.insert(Current.begin(), Current.end());
15051     Current.clear();
15052   // We've hit a cycle.
15053   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15054              Current.count(TCanonical)) {
15055     // If we haven't diagnosed this cycle yet, do so now.
15056     if (!Invalid.count(TCanonical)) {
15057       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15058              diag::warn_delegating_ctor_cycle)
15059         << Ctor;
15060 
15061       // Don't add a note for a function delegating directly to itself.
15062       if (TCanonical != Canonical)
15063         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15064 
15065       CXXConstructorDecl *C = Target;
15066       while (C->getCanonicalDecl() != Canonical) {
15067         const FunctionDecl *FNTarget = nullptr;
15068         (void)C->getTargetConstructor()->hasBody(FNTarget);
15069         assert(FNTarget && "Ctor cycle through bodiless function");
15070 
15071         C = const_cast<CXXConstructorDecl*>(
15072           cast<CXXConstructorDecl>(FNTarget));
15073         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15074       }
15075     }
15076 
15077     Invalid.insert(Current.begin(), Current.end());
15078     Current.clear();
15079   } else {
15080     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15081   }
15082 }
15083 
15084 
15085 void Sema::CheckDelegatingCtorCycles() {
15086   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15087 
15088   for (DelegatingCtorDeclsType::iterator
15089          I = DelegatingCtorDecls.begin(ExternalSource),
15090          E = DelegatingCtorDecls.end();
15091        I != E; ++I)
15092     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15093 
15094   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
15095                                                          CE = Invalid.end();
15096        CI != CE; ++CI)
15097     (*CI)->setInvalidDecl();
15098 }
15099 
15100 namespace {
15101   /// AST visitor that finds references to the 'this' expression.
15102   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15103     Sema &S;
15104 
15105   public:
15106     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15107 
15108     bool VisitCXXThisExpr(CXXThisExpr *E) {
15109       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15110         << E->isImplicit();
15111       return false;
15112     }
15113   };
15114 }
15115 
15116 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15117   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15118   if (!TSInfo)
15119     return false;
15120 
15121   TypeLoc TL = TSInfo->getTypeLoc();
15122   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15123   if (!ProtoTL)
15124     return false;
15125 
15126   // C++11 [expr.prim.general]p3:
15127   //   [The expression this] shall not appear before the optional
15128   //   cv-qualifier-seq and it shall not appear within the declaration of a
15129   //   static member function (although its type and value category are defined
15130   //   within a static member function as they are within a non-static member
15131   //   function). [ Note: this is because declaration matching does not occur
15132   //  until the complete declarator is known. - end note ]
15133   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15134   FindCXXThisExpr Finder(*this);
15135 
15136   // If the return type came after the cv-qualifier-seq, check it now.
15137   if (Proto->hasTrailingReturn() &&
15138       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15139     return true;
15140 
15141   // Check the exception specification.
15142   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15143     return true;
15144 
15145   return checkThisInStaticMemberFunctionAttributes(Method);
15146 }
15147 
15148 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15149   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15150   if (!TSInfo)
15151     return false;
15152 
15153   TypeLoc TL = TSInfo->getTypeLoc();
15154   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15155   if (!ProtoTL)
15156     return false;
15157 
15158   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15159   FindCXXThisExpr Finder(*this);
15160 
15161   switch (Proto->getExceptionSpecType()) {
15162   case EST_Unparsed:
15163   case EST_Uninstantiated:
15164   case EST_Unevaluated:
15165   case EST_BasicNoexcept:
15166   case EST_DynamicNone:
15167   case EST_MSAny:
15168   case EST_None:
15169     break;
15170 
15171   case EST_DependentNoexcept:
15172   case EST_NoexceptFalse:
15173   case EST_NoexceptTrue:
15174     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15175       return true;
15176     LLVM_FALLTHROUGH;
15177 
15178   case EST_Dynamic:
15179     for (const auto &E : Proto->exceptions()) {
15180       if (!Finder.TraverseType(E))
15181         return true;
15182     }
15183     break;
15184   }
15185 
15186   return false;
15187 }
15188 
15189 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15190   FindCXXThisExpr Finder(*this);
15191 
15192   // Check attributes.
15193   for (const auto *A : Method->attrs()) {
15194     // FIXME: This should be emitted by tblgen.
15195     Expr *Arg = nullptr;
15196     ArrayRef<Expr *> Args;
15197     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15198       Arg = G->getArg();
15199     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15200       Arg = G->getArg();
15201     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15202       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15203     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15204       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15205     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15206       Arg = ETLF->getSuccessValue();
15207       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15208     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15209       Arg = STLF->getSuccessValue();
15210       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15211     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15212       Arg = LR->getArg();
15213     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15214       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15215     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15216       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15217     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15218       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15219     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15220       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15221     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15222       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15223 
15224     if (Arg && !Finder.TraverseStmt(Arg))
15225       return true;
15226 
15227     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15228       if (!Finder.TraverseStmt(Args[I]))
15229         return true;
15230     }
15231   }
15232 
15233   return false;
15234 }
15235 
15236 void Sema::checkExceptionSpecification(
15237     bool IsTopLevel, ExceptionSpecificationType EST,
15238     ArrayRef<ParsedType> DynamicExceptions,
15239     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15240     SmallVectorImpl<QualType> &Exceptions,
15241     FunctionProtoType::ExceptionSpecInfo &ESI) {
15242   Exceptions.clear();
15243   ESI.Type = EST;
15244   if (EST == EST_Dynamic) {
15245     Exceptions.reserve(DynamicExceptions.size());
15246     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15247       // FIXME: Preserve type source info.
15248       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15249 
15250       if (IsTopLevel) {
15251         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15252         collectUnexpandedParameterPacks(ET, Unexpanded);
15253         if (!Unexpanded.empty()) {
15254           DiagnoseUnexpandedParameterPacks(
15255               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15256               Unexpanded);
15257           continue;
15258         }
15259       }
15260 
15261       // Check that the type is valid for an exception spec, and
15262       // drop it if not.
15263       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15264         Exceptions.push_back(ET);
15265     }
15266     ESI.Exceptions = Exceptions;
15267     return;
15268   }
15269 
15270   if (isComputedNoexcept(EST)) {
15271     assert((NoexceptExpr->isTypeDependent() ||
15272             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15273             Context.BoolTy) &&
15274            "Parser should have made sure that the expression is boolean");
15275     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15276       ESI.Type = EST_BasicNoexcept;
15277       return;
15278     }
15279 
15280     ESI.NoexceptExpr = NoexceptExpr;
15281     return;
15282   }
15283 }
15284 
15285 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15286              ExceptionSpecificationType EST,
15287              SourceRange SpecificationRange,
15288              ArrayRef<ParsedType> DynamicExceptions,
15289              ArrayRef<SourceRange> DynamicExceptionRanges,
15290              Expr *NoexceptExpr) {
15291   if (!MethodD)
15292     return;
15293 
15294   // Dig out the method we're referring to.
15295   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15296     MethodD = FunTmpl->getTemplatedDecl();
15297 
15298   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15299   if (!Method)
15300     return;
15301 
15302   // Check the exception specification.
15303   llvm::SmallVector<QualType, 4> Exceptions;
15304   FunctionProtoType::ExceptionSpecInfo ESI;
15305   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15306                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15307                               ESI);
15308 
15309   // Update the exception specification on the function type.
15310   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15311 
15312   if (Method->isStatic())
15313     checkThisInStaticMemberFunctionExceptionSpec(Method);
15314 
15315   if (Method->isVirtual()) {
15316     // Check overrides, which we previously had to delay.
15317     for (const CXXMethodDecl *O : Method->overridden_methods())
15318       CheckOverridingFunctionExceptionSpec(Method, O);
15319   }
15320 }
15321 
15322 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15323 ///
15324 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15325                                        SourceLocation DeclStart,
15326                                        Declarator &D, Expr *BitWidth,
15327                                        InClassInitStyle InitStyle,
15328                                        AccessSpecifier AS,
15329                                        AttributeList *MSPropertyAttr) {
15330   IdentifierInfo *II = D.getIdentifier();
15331   if (!II) {
15332     Diag(DeclStart, diag::err_anonymous_property);
15333     return nullptr;
15334   }
15335   SourceLocation Loc = D.getIdentifierLoc();
15336 
15337   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15338   QualType T = TInfo->getType();
15339   if (getLangOpts().CPlusPlus) {
15340     CheckExtraCXXDefaultArguments(D);
15341 
15342     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15343                                         UPPC_DataMemberType)) {
15344       D.setInvalidType();
15345       T = Context.IntTy;
15346       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15347     }
15348   }
15349 
15350   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15351 
15352   if (D.getDeclSpec().isInlineSpecified())
15353     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15354         << getLangOpts().CPlusPlus17;
15355   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15356     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15357          diag::err_invalid_thread)
15358       << DeclSpec::getSpecifierName(TSCS);
15359 
15360   // Check to see if this name was declared as a member previously
15361   NamedDecl *PrevDecl = nullptr;
15362   LookupResult Previous(*this, II, Loc, LookupMemberName,
15363                         ForVisibleRedeclaration);
15364   LookupName(Previous, S);
15365   switch (Previous.getResultKind()) {
15366   case LookupResult::Found:
15367   case LookupResult::FoundUnresolvedValue:
15368     PrevDecl = Previous.getAsSingle<NamedDecl>();
15369     break;
15370 
15371   case LookupResult::FoundOverloaded:
15372     PrevDecl = Previous.getRepresentativeDecl();
15373     break;
15374 
15375   case LookupResult::NotFound:
15376   case LookupResult::NotFoundInCurrentInstantiation:
15377   case LookupResult::Ambiguous:
15378     break;
15379   }
15380 
15381   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15382     // Maybe we will complain about the shadowed template parameter.
15383     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15384     // Just pretend that we didn't see the previous declaration.
15385     PrevDecl = nullptr;
15386   }
15387 
15388   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15389     PrevDecl = nullptr;
15390 
15391   SourceLocation TSSL = D.getLocStart();
15392   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15393   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15394       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15395   ProcessDeclAttributes(TUScope, NewPD, D);
15396   NewPD->setAccess(AS);
15397 
15398   if (NewPD->isInvalidDecl())
15399     Record->setInvalidDecl();
15400 
15401   if (D.getDeclSpec().isModulePrivateSpecified())
15402     NewPD->setModulePrivate();
15403 
15404   if (NewPD->isInvalidDecl() && PrevDecl) {
15405     // Don't introduce NewFD into scope; there's already something
15406     // with the same name in the same scope.
15407   } else if (II) {
15408     PushOnScopeChains(NewPD, S);
15409   } else
15410     Record->addDecl(NewPD);
15411 
15412   return NewPD;
15413 }
15414