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 /// Get the class that is directly named by the current context. This is the
2063 /// class for which an unqualified-id in this scope could name a constructor
2064 /// or destructor.
2065 ///
2066 /// If the scope specifier denotes a class, this will be that class.
2067 /// If the scope specifier is empty, this will be the class whose
2068 /// member-specification we are currently within. Otherwise, there
2069 /// is no such class.
2070 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2071   assert(getLangOpts().CPlusPlus && "No class names in C!");
2072 
2073   if (SS && SS->isInvalid())
2074     return nullptr;
2075 
2076   if (SS && SS->isNotEmpty()) {
2077     DeclContext *DC = computeDeclContext(*SS, true);
2078     return dyn_cast_or_null<CXXRecordDecl>(DC);
2079   }
2080 
2081   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2082 }
2083 
2084 /// isCurrentClassName - Determine whether the identifier II is the
2085 /// name of the class type currently being defined. In the case of
2086 /// nested classes, this will only return true if II is the name of
2087 /// the innermost class.
2088 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2089                               const CXXScopeSpec *SS) {
2090   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2091   return CurDecl && &II == CurDecl->getIdentifier();
2092 }
2093 
2094 /// Determine whether the identifier II is a typo for the name of
2095 /// the class type currently being defined. If so, update it to the identifier
2096 /// that should have been used.
2097 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2098   assert(getLangOpts().CPlusPlus && "No class names in C!");
2099 
2100   if (!getLangOpts().SpellChecking)
2101     return false;
2102 
2103   CXXRecordDecl *CurDecl;
2104   if (SS && SS->isSet() && !SS->isInvalid()) {
2105     DeclContext *DC = computeDeclContext(*SS, true);
2106     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2107   } else
2108     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2109 
2110   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2111       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2112           < II->getLength()) {
2113     II = CurDecl->getIdentifier();
2114     return true;
2115   }
2116 
2117   return false;
2118 }
2119 
2120 /// Determine whether the given class is a base class of the given
2121 /// class, including looking at dependent bases.
2122 static bool findCircularInheritance(const CXXRecordDecl *Class,
2123                                     const CXXRecordDecl *Current) {
2124   SmallVector<const CXXRecordDecl*, 8> Queue;
2125 
2126   Class = Class->getCanonicalDecl();
2127   while (true) {
2128     for (const auto &I : Current->bases()) {
2129       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2130       if (!Base)
2131         continue;
2132 
2133       Base = Base->getDefinition();
2134       if (!Base)
2135         continue;
2136 
2137       if (Base->getCanonicalDecl() == Class)
2138         return true;
2139 
2140       Queue.push_back(Base);
2141     }
2142 
2143     if (Queue.empty())
2144       return false;
2145 
2146     Current = Queue.pop_back_val();
2147   }
2148 
2149   return false;
2150 }
2151 
2152 /// Check the validity of a C++ base class specifier.
2153 ///
2154 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2155 /// and returns NULL otherwise.
2156 CXXBaseSpecifier *
2157 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2158                          SourceRange SpecifierRange,
2159                          bool Virtual, AccessSpecifier Access,
2160                          TypeSourceInfo *TInfo,
2161                          SourceLocation EllipsisLoc) {
2162   QualType BaseType = TInfo->getType();
2163 
2164   // C++ [class.union]p1:
2165   //   A union shall not have base classes.
2166   if (Class->isUnion()) {
2167     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2168       << SpecifierRange;
2169     return nullptr;
2170   }
2171 
2172   if (EllipsisLoc.isValid() &&
2173       !TInfo->getType()->containsUnexpandedParameterPack()) {
2174     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2175       << TInfo->getTypeLoc().getSourceRange();
2176     EllipsisLoc = SourceLocation();
2177   }
2178 
2179   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2180 
2181   if (BaseType->isDependentType()) {
2182     // Make sure that we don't have circular inheritance among our dependent
2183     // bases. For non-dependent bases, the check for completeness below handles
2184     // this.
2185     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2186       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2187           ((BaseDecl = BaseDecl->getDefinition()) &&
2188            findCircularInheritance(Class, BaseDecl))) {
2189         Diag(BaseLoc, diag::err_circular_inheritance)
2190           << BaseType << Context.getTypeDeclType(Class);
2191 
2192         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2193           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2194             << BaseType;
2195 
2196         return nullptr;
2197       }
2198     }
2199 
2200     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2201                                           Class->getTagKind() == TTK_Class,
2202                                           Access, TInfo, EllipsisLoc);
2203   }
2204 
2205   // Base specifiers must be record types.
2206   if (!BaseType->isRecordType()) {
2207     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2208     return nullptr;
2209   }
2210 
2211   // C++ [class.union]p1:
2212   //   A union shall not be used as a base class.
2213   if (BaseType->isUnionType()) {
2214     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2215     return nullptr;
2216   }
2217 
2218   // For the MS ABI, propagate DLL attributes to base class templates.
2219   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2220     if (Attr *ClassAttr = getDLLAttr(Class)) {
2221       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2222               BaseType->getAsCXXRecordDecl())) {
2223         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2224                                             BaseLoc);
2225       }
2226     }
2227   }
2228 
2229   // C++ [class.derived]p2:
2230   //   The class-name in a base-specifier shall not be an incompletely
2231   //   defined class.
2232   if (RequireCompleteType(BaseLoc, BaseType,
2233                           diag::err_incomplete_base_class, SpecifierRange)) {
2234     Class->setInvalidDecl();
2235     return nullptr;
2236   }
2237 
2238   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2239   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2240   assert(BaseDecl && "Record type has no declaration");
2241   BaseDecl = BaseDecl->getDefinition();
2242   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2243   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2244   assert(CXXBaseDecl && "Base type is not a C++ type");
2245 
2246   // A class which contains a flexible array member is not suitable for use as a
2247   // base class:
2248   //   - If the layout determines that a base comes before another base,
2249   //     the flexible array member would index into the subsequent base.
2250   //   - If the layout determines that base comes before the derived class,
2251   //     the flexible array member would index into the derived class.
2252   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2253     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2254       << CXXBaseDecl->getDeclName();
2255     return nullptr;
2256   }
2257 
2258   // C++ [class]p3:
2259   //   If a class is marked final and it appears as a base-type-specifier in
2260   //   base-clause, the program is ill-formed.
2261   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2262     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2263       << CXXBaseDecl->getDeclName()
2264       << FA->isSpelledAsSealed();
2265     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2266         << CXXBaseDecl->getDeclName() << FA->getRange();
2267     return nullptr;
2268   }
2269 
2270   if (BaseDecl->isInvalidDecl())
2271     Class->setInvalidDecl();
2272 
2273   // Create the base specifier.
2274   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2275                                         Class->getTagKind() == TTK_Class,
2276                                         Access, TInfo, EllipsisLoc);
2277 }
2278 
2279 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2280 /// one entry in the base class list of a class specifier, for
2281 /// example:
2282 ///    class foo : public bar, virtual private baz {
2283 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2284 BaseResult
2285 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2286                          ParsedAttributes &Attributes,
2287                          bool Virtual, AccessSpecifier Access,
2288                          ParsedType basetype, SourceLocation BaseLoc,
2289                          SourceLocation EllipsisLoc) {
2290   if (!classdecl)
2291     return true;
2292 
2293   AdjustDeclIfTemplate(classdecl);
2294   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2295   if (!Class)
2296     return true;
2297 
2298   // We haven't yet attached the base specifiers.
2299   Class->setIsParsingBaseSpecifiers();
2300 
2301   // We do not support any C++11 attributes on base-specifiers yet.
2302   // Diagnose any attributes we see.
2303   if (!Attributes.empty()) {
2304     for (AttributeList *Attr = Attributes.getList(); Attr;
2305          Attr = Attr->getNext()) {
2306       if (Attr->isInvalid() ||
2307           Attr->getKind() == AttributeList::IgnoredAttribute)
2308         continue;
2309       Diag(Attr->getLoc(),
2310            Attr->getKind() == AttributeList::UnknownAttribute
2311              ? diag::warn_unknown_attribute_ignored
2312              : diag::err_base_specifier_attribute)
2313         << Attr->getName();
2314     }
2315   }
2316 
2317   TypeSourceInfo *TInfo = nullptr;
2318   GetTypeFromParser(basetype, &TInfo);
2319 
2320   if (EllipsisLoc.isInvalid() &&
2321       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2322                                       UPPC_BaseType))
2323     return true;
2324 
2325   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2326                                                       Virtual, Access, TInfo,
2327                                                       EllipsisLoc))
2328     return BaseSpec;
2329   else
2330     Class->setInvalidDecl();
2331 
2332   return true;
2333 }
2334 
2335 /// Use small set to collect indirect bases.  As this is only used
2336 /// locally, there's no need to abstract the small size parameter.
2337 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2338 
2339 /// Recursively add the bases of Type.  Don't add Type itself.
2340 static void
2341 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2342                   const QualType &Type)
2343 {
2344   // Even though the incoming type is a base, it might not be
2345   // a class -- it could be a template parm, for instance.
2346   if (auto Rec = Type->getAs<RecordType>()) {
2347     auto Decl = Rec->getAsCXXRecordDecl();
2348 
2349     // Iterate over its bases.
2350     for (const auto &BaseSpec : Decl->bases()) {
2351       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2352         .getUnqualifiedType();
2353       if (Set.insert(Base).second)
2354         // If we've not already seen it, recurse.
2355         NoteIndirectBases(Context, Set, Base);
2356     }
2357   }
2358 }
2359 
2360 /// Performs the actual work of attaching the given base class
2361 /// specifiers to a C++ class.
2362 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2363                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2364  if (Bases.empty())
2365     return false;
2366 
2367   // Used to keep track of which base types we have already seen, so
2368   // that we can properly diagnose redundant direct base types. Note
2369   // that the key is always the unqualified canonical type of the base
2370   // class.
2371   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2372 
2373   // Used to track indirect bases so we can see if a direct base is
2374   // ambiguous.
2375   IndirectBaseSet IndirectBaseTypes;
2376 
2377   // Copy non-redundant base specifiers into permanent storage.
2378   unsigned NumGoodBases = 0;
2379   bool Invalid = false;
2380   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2381     QualType NewBaseType
2382       = Context.getCanonicalType(Bases[idx]->getType());
2383     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2384 
2385     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2386     if (KnownBase) {
2387       // C++ [class.mi]p3:
2388       //   A class shall not be specified as a direct base class of a
2389       //   derived class more than once.
2390       Diag(Bases[idx]->getLocStart(),
2391            diag::err_duplicate_base_class)
2392         << KnownBase->getType()
2393         << Bases[idx]->getSourceRange();
2394 
2395       // Delete the duplicate base class specifier; we're going to
2396       // overwrite its pointer later.
2397       Context.Deallocate(Bases[idx]);
2398 
2399       Invalid = true;
2400     } else {
2401       // Okay, add this new base class.
2402       KnownBase = Bases[idx];
2403       Bases[NumGoodBases++] = Bases[idx];
2404 
2405       // Note this base's direct & indirect bases, if there could be ambiguity.
2406       if (Bases.size() > 1)
2407         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2408 
2409       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2410         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2411         if (Class->isInterface() &&
2412               (!RD->isInterfaceLike() ||
2413                KnownBase->getAccessSpecifier() != AS_public)) {
2414           // The Microsoft extension __interface does not permit bases that
2415           // are not themselves public interfaces.
2416           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2417             << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2418             << RD->getSourceRange();
2419           Invalid = true;
2420         }
2421         if (RD->hasAttr<WeakAttr>())
2422           Class->addAttr(WeakAttr::CreateImplicit(Context));
2423       }
2424     }
2425   }
2426 
2427   // Attach the remaining base class specifiers to the derived class.
2428   Class->setBases(Bases.data(), NumGoodBases);
2429 
2430   // Check that the only base classes that are duplicate are virtual.
2431   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2432     // Check whether this direct base is inaccessible due to ambiguity.
2433     QualType BaseType = Bases[idx]->getType();
2434 
2435     // Skip all dependent types in templates being used as base specifiers.
2436     // Checks below assume that the base specifier is a CXXRecord.
2437     if (BaseType->isDependentType())
2438       continue;
2439 
2440     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2441       .getUnqualifiedType();
2442 
2443     if (IndirectBaseTypes.count(CanonicalBase)) {
2444       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2445                          /*DetectVirtual=*/true);
2446       bool found
2447         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2448       assert(found);
2449       (void)found;
2450 
2451       if (Paths.isAmbiguous(CanonicalBase))
2452         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2453           << BaseType << getAmbiguousPathsDisplayString(Paths)
2454           << Bases[idx]->getSourceRange();
2455       else
2456         assert(Bases[idx]->isVirtual());
2457     }
2458 
2459     // Delete the base class specifier, since its data has been copied
2460     // into the CXXRecordDecl.
2461     Context.Deallocate(Bases[idx]);
2462   }
2463 
2464   return Invalid;
2465 }
2466 
2467 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2468 /// class, after checking whether there are any duplicate base
2469 /// classes.
2470 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2471                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2472   if (!ClassDecl || Bases.empty())
2473     return;
2474 
2475   AdjustDeclIfTemplate(ClassDecl);
2476   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2477 }
2478 
2479 /// Determine whether the type \p Derived is a C++ class that is
2480 /// derived from the type \p Base.
2481 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2482   if (!getLangOpts().CPlusPlus)
2483     return false;
2484 
2485   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2486   if (!DerivedRD)
2487     return false;
2488 
2489   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2490   if (!BaseRD)
2491     return false;
2492 
2493   // If either the base or the derived type is invalid, don't try to
2494   // check whether one is derived from the other.
2495   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2496     return false;
2497 
2498   // FIXME: In a modules build, do we need the entire path to be visible for us
2499   // to be able to use the inheritance relationship?
2500   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2501     return false;
2502 
2503   return DerivedRD->isDerivedFrom(BaseRD);
2504 }
2505 
2506 /// Determine whether the type \p Derived is a C++ class that is
2507 /// derived from the type \p Base.
2508 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2509                          CXXBasePaths &Paths) {
2510   if (!getLangOpts().CPlusPlus)
2511     return false;
2512 
2513   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2514   if (!DerivedRD)
2515     return false;
2516 
2517   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2518   if (!BaseRD)
2519     return false;
2520 
2521   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2522     return false;
2523 
2524   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2525 }
2526 
2527 static void BuildBasePathArray(const CXXBasePath &Path,
2528                                CXXCastPath &BasePathArray) {
2529   // We first go backward and check if we have a virtual base.
2530   // FIXME: It would be better if CXXBasePath had the base specifier for
2531   // the nearest virtual base.
2532   unsigned Start = 0;
2533   for (unsigned I = Path.size(); I != 0; --I) {
2534     if (Path[I - 1].Base->isVirtual()) {
2535       Start = I - 1;
2536       break;
2537     }
2538   }
2539 
2540   // Now add all bases.
2541   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2542     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2543 }
2544 
2545 
2546 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2547                               CXXCastPath &BasePathArray) {
2548   assert(BasePathArray.empty() && "Base path array must be empty!");
2549   assert(Paths.isRecordingPaths() && "Must record paths!");
2550   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2551 }
2552 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2553 /// conversion (where Derived and Base are class types) is
2554 /// well-formed, meaning that the conversion is unambiguous (and
2555 /// that all of the base classes are accessible). Returns true
2556 /// and emits a diagnostic if the code is ill-formed, returns false
2557 /// otherwise. Loc is the location where this routine should point to
2558 /// if there is an error, and Range is the source range to highlight
2559 /// if there is an error.
2560 ///
2561 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2562 /// diagnostic for the respective type of error will be suppressed, but the
2563 /// check for ill-formed code will still be performed.
2564 bool
2565 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2566                                    unsigned InaccessibleBaseID,
2567                                    unsigned AmbigiousBaseConvID,
2568                                    SourceLocation Loc, SourceRange Range,
2569                                    DeclarationName Name,
2570                                    CXXCastPath *BasePath,
2571                                    bool IgnoreAccess) {
2572   // First, determine whether the path from Derived to Base is
2573   // ambiguous. This is slightly more expensive than checking whether
2574   // the Derived to Base conversion exists, because here we need to
2575   // explore multiple paths to determine if there is an ambiguity.
2576   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2577                      /*DetectVirtual=*/false);
2578   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2579   if (!DerivationOkay)
2580     return true;
2581 
2582   const CXXBasePath *Path = nullptr;
2583   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2584     Path = &Paths.front();
2585 
2586   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2587   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2588   // user to access such bases.
2589   if (!Path && getLangOpts().MSVCCompat) {
2590     for (const CXXBasePath &PossiblePath : Paths) {
2591       if (PossiblePath.size() == 1) {
2592         Path = &PossiblePath;
2593         if (AmbigiousBaseConvID)
2594           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2595               << Base << Derived << Range;
2596         break;
2597       }
2598     }
2599   }
2600 
2601   if (Path) {
2602     if (!IgnoreAccess) {
2603       // Check that the base class can be accessed.
2604       switch (
2605           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2606       case AR_inaccessible:
2607         return true;
2608       case AR_accessible:
2609       case AR_dependent:
2610       case AR_delayed:
2611         break;
2612       }
2613     }
2614 
2615     // Build a base path if necessary.
2616     if (BasePath)
2617       ::BuildBasePathArray(*Path, *BasePath);
2618     return false;
2619   }
2620 
2621   if (AmbigiousBaseConvID) {
2622     // We know that the derived-to-base conversion is ambiguous, and
2623     // we're going to produce a diagnostic. Perform the derived-to-base
2624     // search just one more time to compute all of the possible paths so
2625     // that we can print them out. This is more expensive than any of
2626     // the previous derived-to-base checks we've done, but at this point
2627     // performance isn't as much of an issue.
2628     Paths.clear();
2629     Paths.setRecordingPaths(true);
2630     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2631     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2632     (void)StillOkay;
2633 
2634     // Build up a textual representation of the ambiguous paths, e.g.,
2635     // D -> B -> A, that will be used to illustrate the ambiguous
2636     // conversions in the diagnostic. We only print one of the paths
2637     // to each base class subobject.
2638     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2639 
2640     Diag(Loc, AmbigiousBaseConvID)
2641     << Derived << Base << PathDisplayStr << Range << Name;
2642   }
2643   return true;
2644 }
2645 
2646 bool
2647 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2648                                    SourceLocation Loc, SourceRange Range,
2649                                    CXXCastPath *BasePath,
2650                                    bool IgnoreAccess) {
2651   return CheckDerivedToBaseConversion(
2652       Derived, Base, diag::err_upcast_to_inaccessible_base,
2653       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2654       BasePath, IgnoreAccess);
2655 }
2656 
2657 
2658 /// Builds a string representing ambiguous paths from a
2659 /// specific derived class to different subobjects of the same base
2660 /// class.
2661 ///
2662 /// This function builds a string that can be used in error messages
2663 /// to show the different paths that one can take through the
2664 /// inheritance hierarchy to go from the derived class to different
2665 /// subobjects of a base class. The result looks something like this:
2666 /// @code
2667 /// struct D -> struct B -> struct A
2668 /// struct D -> struct C -> struct A
2669 /// @endcode
2670 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2671   std::string PathDisplayStr;
2672   std::set<unsigned> DisplayedPaths;
2673   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2674        Path != Paths.end(); ++Path) {
2675     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2676       // We haven't displayed a path to this particular base
2677       // class subobject yet.
2678       PathDisplayStr += "\n    ";
2679       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2680       for (CXXBasePath::const_iterator Element = Path->begin();
2681            Element != Path->end(); ++Element)
2682         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2683     }
2684   }
2685 
2686   return PathDisplayStr;
2687 }
2688 
2689 //===----------------------------------------------------------------------===//
2690 // C++ class member Handling
2691 //===----------------------------------------------------------------------===//
2692 
2693 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2694 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2695                                 SourceLocation ASLoc,
2696                                 SourceLocation ColonLoc,
2697                                 AttributeList *Attrs) {
2698   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2699   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2700                                                   ASLoc, ColonLoc);
2701   CurContext->addHiddenDecl(ASDecl);
2702   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2703 }
2704 
2705 /// CheckOverrideControl - Check C++11 override control semantics.
2706 void Sema::CheckOverrideControl(NamedDecl *D) {
2707   if (D->isInvalidDecl())
2708     return;
2709 
2710   // We only care about "override" and "final" declarations.
2711   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2712     return;
2713 
2714   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2715 
2716   // We can't check dependent instance methods.
2717   if (MD && MD->isInstance() &&
2718       (MD->getParent()->hasAnyDependentBases() ||
2719        MD->getType()->isDependentType()))
2720     return;
2721 
2722   if (MD && !MD->isVirtual()) {
2723     // If we have a non-virtual method, check if if hides a virtual method.
2724     // (In that case, it's most likely the method has the wrong type.)
2725     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2726     FindHiddenVirtualMethods(MD, OverloadedMethods);
2727 
2728     if (!OverloadedMethods.empty()) {
2729       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2730         Diag(OA->getLocation(),
2731              diag::override_keyword_hides_virtual_member_function)
2732           << "override" << (OverloadedMethods.size() > 1);
2733       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2734         Diag(FA->getLocation(),
2735              diag::override_keyword_hides_virtual_member_function)
2736           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2737           << (OverloadedMethods.size() > 1);
2738       }
2739       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2740       MD->setInvalidDecl();
2741       return;
2742     }
2743     // Fall through into the general case diagnostic.
2744     // FIXME: We might want to attempt typo correction here.
2745   }
2746 
2747   if (!MD || !MD->isVirtual()) {
2748     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2749       Diag(OA->getLocation(),
2750            diag::override_keyword_only_allowed_on_virtual_member_functions)
2751         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2752       D->dropAttr<OverrideAttr>();
2753     }
2754     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2755       Diag(FA->getLocation(),
2756            diag::override_keyword_only_allowed_on_virtual_member_functions)
2757         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2758         << FixItHint::CreateRemoval(FA->getLocation());
2759       D->dropAttr<FinalAttr>();
2760     }
2761     return;
2762   }
2763 
2764   // C++11 [class.virtual]p5:
2765   //   If a function is marked with the virt-specifier override and
2766   //   does not override a member function of a base class, the program is
2767   //   ill-formed.
2768   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2769   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2770     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2771       << MD->getDeclName();
2772 }
2773 
2774 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2775   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2776     return;
2777   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2778   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2779     return;
2780 
2781   SourceLocation Loc = MD->getLocation();
2782   SourceLocation SpellingLoc = Loc;
2783   if (getSourceManager().isMacroArgExpansion(Loc))
2784     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2785   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2786   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2787       return;
2788 
2789   if (MD->size_overridden_methods() > 0) {
2790     unsigned DiagID = isa<CXXDestructorDecl>(MD)
2791                           ? diag::warn_destructor_marked_not_override_overriding
2792                           : diag::warn_function_marked_not_override_overriding;
2793     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2794     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2795     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2796   }
2797 }
2798 
2799 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2800 /// function overrides a virtual member function marked 'final', according to
2801 /// C++11 [class.virtual]p4.
2802 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2803                                                   const CXXMethodDecl *Old) {
2804   FinalAttr *FA = Old->getAttr<FinalAttr>();
2805   if (!FA)
2806     return false;
2807 
2808   Diag(New->getLocation(), diag::err_final_function_overridden)
2809     << New->getDeclName()
2810     << FA->isSpelledAsSealed();
2811   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2812   return true;
2813 }
2814 
2815 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2816   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2817   // FIXME: Destruction of ObjC lifetime types has side-effects.
2818   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2819     return !RD->isCompleteDefinition() ||
2820            !RD->hasTrivialDefaultConstructor() ||
2821            !RD->hasTrivialDestructor();
2822   return false;
2823 }
2824 
2825 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2826   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2827     if (it->isDeclspecPropertyAttribute())
2828       return it;
2829   return nullptr;
2830 }
2831 
2832 // Check if there is a field shadowing.
2833 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2834                                       DeclarationName FieldName,
2835                                       const CXXRecordDecl *RD) {
2836   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2837     return;
2838 
2839   // To record a shadowed field in a base
2840   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2841   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2842                            CXXBasePath &Path) {
2843     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2844     // Record an ambiguous path directly
2845     if (Bases.find(Base) != Bases.end())
2846       return true;
2847     for (const auto Field : Base->lookup(FieldName)) {
2848       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2849           Field->getAccess() != AS_private) {
2850         assert(Field->getAccess() != AS_none);
2851         assert(Bases.find(Base) == Bases.end());
2852         Bases[Base] = Field;
2853         return true;
2854       }
2855     }
2856     return false;
2857   };
2858 
2859   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2860                      /*DetectVirtual=*/true);
2861   if (!RD->lookupInBases(FieldShadowed, Paths))
2862     return;
2863 
2864   for (const auto &P : Paths) {
2865     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2866     auto It = Bases.find(Base);
2867     // Skip duplicated bases
2868     if (It == Bases.end())
2869       continue;
2870     auto BaseField = It->second;
2871     assert(BaseField->getAccess() != AS_private);
2872     if (AS_none !=
2873         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2874       Diag(Loc, diag::warn_shadow_field)
2875         << FieldName << RD << Base;
2876       Diag(BaseField->getLocation(), diag::note_shadow_field);
2877       Bases.erase(It);
2878     }
2879   }
2880 }
2881 
2882 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2883 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2884 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2885 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2886 /// present (but parsing it has been deferred).
2887 NamedDecl *
2888 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2889                                MultiTemplateParamsArg TemplateParameterLists,
2890                                Expr *BW, const VirtSpecifiers &VS,
2891                                InClassInitStyle InitStyle) {
2892   const DeclSpec &DS = D.getDeclSpec();
2893   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2894   DeclarationName Name = NameInfo.getName();
2895   SourceLocation Loc = NameInfo.getLoc();
2896 
2897   // For anonymous bitfields, the location should point to the type.
2898   if (Loc.isInvalid())
2899     Loc = D.getLocStart();
2900 
2901   Expr *BitWidth = static_cast<Expr*>(BW);
2902 
2903   assert(isa<CXXRecordDecl>(CurContext));
2904   assert(!DS.isFriendSpecified());
2905 
2906   bool isFunc = D.isDeclarationOfFunction();
2907   AttributeList *MSPropertyAttr =
2908       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2909 
2910   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2911     // The Microsoft extension __interface only permits public member functions
2912     // and prohibits constructors, destructors, operators, non-public member
2913     // functions, static methods and data members.
2914     unsigned InvalidDecl;
2915     bool ShowDeclName = true;
2916     if (!isFunc &&
2917         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2918       InvalidDecl = 0;
2919     else if (!isFunc)
2920       InvalidDecl = 1;
2921     else if (AS != AS_public)
2922       InvalidDecl = 2;
2923     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2924       InvalidDecl = 3;
2925     else switch (Name.getNameKind()) {
2926       case DeclarationName::CXXConstructorName:
2927         InvalidDecl = 4;
2928         ShowDeclName = false;
2929         break;
2930 
2931       case DeclarationName::CXXDestructorName:
2932         InvalidDecl = 5;
2933         ShowDeclName = false;
2934         break;
2935 
2936       case DeclarationName::CXXOperatorName:
2937       case DeclarationName::CXXConversionFunctionName:
2938         InvalidDecl = 6;
2939         break;
2940 
2941       default:
2942         InvalidDecl = 0;
2943         break;
2944     }
2945 
2946     if (InvalidDecl) {
2947       if (ShowDeclName)
2948         Diag(Loc, diag::err_invalid_member_in_interface)
2949           << (InvalidDecl-1) << Name;
2950       else
2951         Diag(Loc, diag::err_invalid_member_in_interface)
2952           << (InvalidDecl-1) << "";
2953       return nullptr;
2954     }
2955   }
2956 
2957   // C++ 9.2p6: A member shall not be declared to have automatic storage
2958   // duration (auto, register) or with the extern storage-class-specifier.
2959   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2960   // data members and cannot be applied to names declared const or static,
2961   // and cannot be applied to reference members.
2962   switch (DS.getStorageClassSpec()) {
2963   case DeclSpec::SCS_unspecified:
2964   case DeclSpec::SCS_typedef:
2965   case DeclSpec::SCS_static:
2966     break;
2967   case DeclSpec::SCS_mutable:
2968     if (isFunc) {
2969       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2970 
2971       // FIXME: It would be nicer if the keyword was ignored only for this
2972       // declarator. Otherwise we could get follow-up errors.
2973       D.getMutableDeclSpec().ClearStorageClassSpecs();
2974     }
2975     break;
2976   default:
2977     Diag(DS.getStorageClassSpecLoc(),
2978          diag::err_storageclass_invalid_for_member);
2979     D.getMutableDeclSpec().ClearStorageClassSpecs();
2980     break;
2981   }
2982 
2983   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2984                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2985                       !isFunc);
2986 
2987   if (DS.isConstexprSpecified() && isInstField) {
2988     SemaDiagnosticBuilder B =
2989         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2990     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2991     if (InitStyle == ICIS_NoInit) {
2992       B << 0 << 0;
2993       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2994         B << FixItHint::CreateRemoval(ConstexprLoc);
2995       else {
2996         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2997         D.getMutableDeclSpec().ClearConstexprSpec();
2998         const char *PrevSpec;
2999         unsigned DiagID;
3000         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3001             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3002         (void)Failed;
3003         assert(!Failed && "Making a constexpr member const shouldn't fail");
3004       }
3005     } else {
3006       B << 1;
3007       const char *PrevSpec;
3008       unsigned DiagID;
3009       if (D.getMutableDeclSpec().SetStorageClassSpec(
3010           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3011           Context.getPrintingPolicy())) {
3012         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3013                "This is the only DeclSpec that should fail to be applied");
3014         B << 1;
3015       } else {
3016         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3017         isInstField = false;
3018       }
3019     }
3020   }
3021 
3022   NamedDecl *Member;
3023   if (isInstField) {
3024     CXXScopeSpec &SS = D.getCXXScopeSpec();
3025 
3026     // Data members must have identifiers for names.
3027     if (!Name.isIdentifier()) {
3028       Diag(Loc, diag::err_bad_variable_name)
3029         << Name;
3030       return nullptr;
3031     }
3032 
3033     IdentifierInfo *II = Name.getAsIdentifierInfo();
3034 
3035     // Member field could not be with "template" keyword.
3036     // So TemplateParameterLists should be empty in this case.
3037     if (TemplateParameterLists.size()) {
3038       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3039       if (TemplateParams->size()) {
3040         // There is no such thing as a member field template.
3041         Diag(D.getIdentifierLoc(), diag::err_template_member)
3042             << II
3043             << SourceRange(TemplateParams->getTemplateLoc(),
3044                 TemplateParams->getRAngleLoc());
3045       } else {
3046         // There is an extraneous 'template<>' for this member.
3047         Diag(TemplateParams->getTemplateLoc(),
3048             diag::err_template_member_noparams)
3049             << II
3050             << SourceRange(TemplateParams->getTemplateLoc(),
3051                 TemplateParams->getRAngleLoc());
3052       }
3053       return nullptr;
3054     }
3055 
3056     if (SS.isSet() && !SS.isInvalid()) {
3057       // The user provided a superfluous scope specifier inside a class
3058       // definition:
3059       //
3060       // class X {
3061       //   int X::member;
3062       // };
3063       if (DeclContext *DC = computeDeclContext(SS, false))
3064         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3065                                      D.getName().getKind() ==
3066                                          UnqualifiedIdKind::IK_TemplateId);
3067       else
3068         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3069           << Name << SS.getRange();
3070 
3071       SS.clear();
3072     }
3073 
3074     if (MSPropertyAttr) {
3075       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3076                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3077       if (!Member)
3078         return nullptr;
3079       isInstField = false;
3080     } else {
3081       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3082                                 BitWidth, InitStyle, AS);
3083       if (!Member)
3084         return nullptr;
3085     }
3086 
3087     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3088   } else {
3089     Member = HandleDeclarator(S, D, TemplateParameterLists);
3090     if (!Member)
3091       return nullptr;
3092 
3093     // Non-instance-fields can't have a bitfield.
3094     if (BitWidth) {
3095       if (Member->isInvalidDecl()) {
3096         // don't emit another diagnostic.
3097       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3098         // C++ 9.6p3: A bit-field shall not be a static member.
3099         // "static member 'A' cannot be a bit-field"
3100         Diag(Loc, diag::err_static_not_bitfield)
3101           << Name << BitWidth->getSourceRange();
3102       } else if (isa<TypedefDecl>(Member)) {
3103         // "typedef member 'x' cannot be a bit-field"
3104         Diag(Loc, diag::err_typedef_not_bitfield)
3105           << Name << BitWidth->getSourceRange();
3106       } else {
3107         // A function typedef ("typedef int f(); f a;").
3108         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3109         Diag(Loc, diag::err_not_integral_type_bitfield)
3110           << Name << cast<ValueDecl>(Member)->getType()
3111           << BitWidth->getSourceRange();
3112       }
3113 
3114       BitWidth = nullptr;
3115       Member->setInvalidDecl();
3116     }
3117 
3118     NamedDecl *NonTemplateMember = Member;
3119     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3120       NonTemplateMember = FunTmpl->getTemplatedDecl();
3121     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3122       NonTemplateMember = VarTmpl->getTemplatedDecl();
3123 
3124     Member->setAccess(AS);
3125 
3126     // If we have declared a member function template or static data member
3127     // template, set the access of the templated declaration as well.
3128     if (NonTemplateMember != Member)
3129       NonTemplateMember->setAccess(AS);
3130 
3131     // C++ [temp.deduct.guide]p3:
3132     //   A deduction guide [...] for a member class template [shall be
3133     //   declared] with the same access [as the template].
3134     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3135       auto *TD = DG->getDeducedTemplate();
3136       if (AS != TD->getAccess()) {
3137         Diag(DG->getLocStart(), diag::err_deduction_guide_wrong_access);
3138         Diag(TD->getLocStart(), diag::note_deduction_guide_template_access)
3139           << TD->getAccess();
3140         const AccessSpecDecl *LastAccessSpec = nullptr;
3141         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3142           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3143             LastAccessSpec = AccessSpec;
3144         }
3145         assert(LastAccessSpec && "differing access with no access specifier");
3146         Diag(LastAccessSpec->getLocStart(), diag::note_deduction_guide_access)
3147           << AS;
3148       }
3149     }
3150   }
3151 
3152   if (VS.isOverrideSpecified())
3153     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3154   if (VS.isFinalSpecified())
3155     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3156                                             VS.isFinalSpelledSealed()));
3157 
3158   if (VS.getLastLocation().isValid()) {
3159     // Update the end location of a method that has a virt-specifiers.
3160     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3161       MD->setRangeEnd(VS.getLastLocation());
3162   }
3163 
3164   CheckOverrideControl(Member);
3165 
3166   assert((Name || isInstField) && "No identifier for non-field ?");
3167 
3168   if (isInstField) {
3169     FieldDecl *FD = cast<FieldDecl>(Member);
3170     FieldCollector->Add(FD);
3171 
3172     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3173       // Remember all explicit private FieldDecls that have a name, no side
3174       // effects and are not part of a dependent type declaration.
3175       if (!FD->isImplicit() && FD->getDeclName() &&
3176           FD->getAccess() == AS_private &&
3177           !FD->hasAttr<UnusedAttr>() &&
3178           !FD->getParent()->isDependentContext() &&
3179           !InitializationHasSideEffects(*FD))
3180         UnusedPrivateFields.insert(FD);
3181     }
3182   }
3183 
3184   return Member;
3185 }
3186 
3187 namespace {
3188   class UninitializedFieldVisitor
3189       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3190     Sema &S;
3191     // List of Decls to generate a warning on.  Also remove Decls that become
3192     // initialized.
3193     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3194     // List of base classes of the record.  Classes are removed after their
3195     // initializers.
3196     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3197     // Vector of decls to be removed from the Decl set prior to visiting the
3198     // nodes.  These Decls may have been initialized in the prior initializer.
3199     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3200     // If non-null, add a note to the warning pointing back to the constructor.
3201     const CXXConstructorDecl *Constructor;
3202     // Variables to hold state when processing an initializer list.  When
3203     // InitList is true, special case initialization of FieldDecls matching
3204     // InitListFieldDecl.
3205     bool InitList;
3206     FieldDecl *InitListFieldDecl;
3207     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3208 
3209   public:
3210     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3211     UninitializedFieldVisitor(Sema &S,
3212                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3213                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3214       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3215         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3216 
3217     // Returns true if the use of ME is not an uninitialized use.
3218     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3219                                          bool CheckReferenceOnly) {
3220       llvm::SmallVector<FieldDecl*, 4> Fields;
3221       bool ReferenceField = false;
3222       while (ME) {
3223         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3224         if (!FD)
3225           return false;
3226         Fields.push_back(FD);
3227         if (FD->getType()->isReferenceType())
3228           ReferenceField = true;
3229         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3230       }
3231 
3232       // Binding a reference to an unintialized field is not an
3233       // uninitialized use.
3234       if (CheckReferenceOnly && !ReferenceField)
3235         return true;
3236 
3237       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3238       // Discard the first field since it is the field decl that is being
3239       // initialized.
3240       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3241         UsedFieldIndex.push_back((*I)->getFieldIndex());
3242       }
3243 
3244       for (auto UsedIter = UsedFieldIndex.begin(),
3245                 UsedEnd = UsedFieldIndex.end(),
3246                 OrigIter = InitFieldIndex.begin(),
3247                 OrigEnd = InitFieldIndex.end();
3248            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3249         if (*UsedIter < *OrigIter)
3250           return true;
3251         if (*UsedIter > *OrigIter)
3252           break;
3253       }
3254 
3255       return false;
3256     }
3257 
3258     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3259                           bool AddressOf) {
3260       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3261         return;
3262 
3263       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3264       // or union.
3265       MemberExpr *FieldME = ME;
3266 
3267       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3268 
3269       Expr *Base = ME;
3270       while (MemberExpr *SubME =
3271                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3272 
3273         if (isa<VarDecl>(SubME->getMemberDecl()))
3274           return;
3275 
3276         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3277           if (!FD->isAnonymousStructOrUnion())
3278             FieldME = SubME;
3279 
3280         if (!FieldME->getType().isPODType(S.Context))
3281           AllPODFields = false;
3282 
3283         Base = SubME->getBase();
3284       }
3285 
3286       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3287         return;
3288 
3289       if (AddressOf && AllPODFields)
3290         return;
3291 
3292       ValueDecl* FoundVD = FieldME->getMemberDecl();
3293 
3294       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3295         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3296           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3297         }
3298 
3299         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3300           QualType T = BaseCast->getType();
3301           if (T->isPointerType() &&
3302               BaseClasses.count(T->getPointeeType())) {
3303             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3304                 << T->getPointeeType() << FoundVD;
3305           }
3306         }
3307       }
3308 
3309       if (!Decls.count(FoundVD))
3310         return;
3311 
3312       const bool IsReference = FoundVD->getType()->isReferenceType();
3313 
3314       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3315         // Special checking for initializer lists.
3316         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3317           return;
3318         }
3319       } else {
3320         // Prevent double warnings on use of unbounded references.
3321         if (CheckReferenceOnly && !IsReference)
3322           return;
3323       }
3324 
3325       unsigned diag = IsReference
3326           ? diag::warn_reference_field_is_uninit
3327           : diag::warn_field_is_uninit;
3328       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3329       if (Constructor)
3330         S.Diag(Constructor->getLocation(),
3331                diag::note_uninit_in_this_constructor)
3332           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3333 
3334     }
3335 
3336     void HandleValue(Expr *E, bool AddressOf) {
3337       E = E->IgnoreParens();
3338 
3339       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3340         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3341                          AddressOf /*AddressOf*/);
3342         return;
3343       }
3344 
3345       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3346         Visit(CO->getCond());
3347         HandleValue(CO->getTrueExpr(), AddressOf);
3348         HandleValue(CO->getFalseExpr(), AddressOf);
3349         return;
3350       }
3351 
3352       if (BinaryConditionalOperator *BCO =
3353               dyn_cast<BinaryConditionalOperator>(E)) {
3354         Visit(BCO->getCond());
3355         HandleValue(BCO->getFalseExpr(), AddressOf);
3356         return;
3357       }
3358 
3359       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3360         HandleValue(OVE->getSourceExpr(), AddressOf);
3361         return;
3362       }
3363 
3364       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3365         switch (BO->getOpcode()) {
3366         default:
3367           break;
3368         case(BO_PtrMemD):
3369         case(BO_PtrMemI):
3370           HandleValue(BO->getLHS(), AddressOf);
3371           Visit(BO->getRHS());
3372           return;
3373         case(BO_Comma):
3374           Visit(BO->getLHS());
3375           HandleValue(BO->getRHS(), AddressOf);
3376           return;
3377         }
3378       }
3379 
3380       Visit(E);
3381     }
3382 
3383     void CheckInitListExpr(InitListExpr *ILE) {
3384       InitFieldIndex.push_back(0);
3385       for (auto Child : ILE->children()) {
3386         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3387           CheckInitListExpr(SubList);
3388         } else {
3389           Visit(Child);
3390         }
3391         ++InitFieldIndex.back();
3392       }
3393       InitFieldIndex.pop_back();
3394     }
3395 
3396     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3397                           FieldDecl *Field, const Type *BaseClass) {
3398       // Remove Decls that may have been initialized in the previous
3399       // initializer.
3400       for (ValueDecl* VD : DeclsToRemove)
3401         Decls.erase(VD);
3402       DeclsToRemove.clear();
3403 
3404       Constructor = FieldConstructor;
3405       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3406 
3407       if (ILE && Field) {
3408         InitList = true;
3409         InitListFieldDecl = Field;
3410         InitFieldIndex.clear();
3411         CheckInitListExpr(ILE);
3412       } else {
3413         InitList = false;
3414         Visit(E);
3415       }
3416 
3417       if (Field)
3418         Decls.erase(Field);
3419       if (BaseClass)
3420         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3421     }
3422 
3423     void VisitMemberExpr(MemberExpr *ME) {
3424       // All uses of unbounded reference fields will warn.
3425       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3426     }
3427 
3428     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3429       if (E->getCastKind() == CK_LValueToRValue) {
3430         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3431         return;
3432       }
3433 
3434       Inherited::VisitImplicitCastExpr(E);
3435     }
3436 
3437     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3438       if (E->getConstructor()->isCopyConstructor()) {
3439         Expr *ArgExpr = E->getArg(0);
3440         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3441           if (ILE->getNumInits() == 1)
3442             ArgExpr = ILE->getInit(0);
3443         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3444           if (ICE->getCastKind() == CK_NoOp)
3445             ArgExpr = ICE->getSubExpr();
3446         HandleValue(ArgExpr, false /*AddressOf*/);
3447         return;
3448       }
3449       Inherited::VisitCXXConstructExpr(E);
3450     }
3451 
3452     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3453       Expr *Callee = E->getCallee();
3454       if (isa<MemberExpr>(Callee)) {
3455         HandleValue(Callee, false /*AddressOf*/);
3456         for (auto Arg : E->arguments())
3457           Visit(Arg);
3458         return;
3459       }
3460 
3461       Inherited::VisitCXXMemberCallExpr(E);
3462     }
3463 
3464     void VisitCallExpr(CallExpr *E) {
3465       // Treat std::move as a use.
3466       if (E->isCallToStdMove()) {
3467         HandleValue(E->getArg(0), /*AddressOf=*/false);
3468         return;
3469       }
3470 
3471       Inherited::VisitCallExpr(E);
3472     }
3473 
3474     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3475       Expr *Callee = E->getCallee();
3476 
3477       if (isa<UnresolvedLookupExpr>(Callee))
3478         return Inherited::VisitCXXOperatorCallExpr(E);
3479 
3480       Visit(Callee);
3481       for (auto Arg : E->arguments())
3482         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3483     }
3484 
3485     void VisitBinaryOperator(BinaryOperator *E) {
3486       // If a field assignment is detected, remove the field from the
3487       // uninitiailized field set.
3488       if (E->getOpcode() == BO_Assign)
3489         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3490           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3491             if (!FD->getType()->isReferenceType())
3492               DeclsToRemove.push_back(FD);
3493 
3494       if (E->isCompoundAssignmentOp()) {
3495         HandleValue(E->getLHS(), false /*AddressOf*/);
3496         Visit(E->getRHS());
3497         return;
3498       }
3499 
3500       Inherited::VisitBinaryOperator(E);
3501     }
3502 
3503     void VisitUnaryOperator(UnaryOperator *E) {
3504       if (E->isIncrementDecrementOp()) {
3505         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3506         return;
3507       }
3508       if (E->getOpcode() == UO_AddrOf) {
3509         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3510           HandleValue(ME->getBase(), true /*AddressOf*/);
3511           return;
3512         }
3513       }
3514 
3515       Inherited::VisitUnaryOperator(E);
3516     }
3517   };
3518 
3519   // Diagnose value-uses of fields to initialize themselves, e.g.
3520   //   foo(foo)
3521   // where foo is not also a parameter to the constructor.
3522   // Also diagnose across field uninitialized use such as
3523   //   x(y), y(x)
3524   // TODO: implement -Wuninitialized and fold this into that framework.
3525   static void DiagnoseUninitializedFields(
3526       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3527 
3528     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3529                                            Constructor->getLocation())) {
3530       return;
3531     }
3532 
3533     if (Constructor->isInvalidDecl())
3534       return;
3535 
3536     const CXXRecordDecl *RD = Constructor->getParent();
3537 
3538     if (RD->getDescribedClassTemplate())
3539       return;
3540 
3541     // Holds fields that are uninitialized.
3542     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3543 
3544     // At the beginning, all fields are uninitialized.
3545     for (auto *I : RD->decls()) {
3546       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3547         UninitializedFields.insert(FD);
3548       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3549         UninitializedFields.insert(IFD->getAnonField());
3550       }
3551     }
3552 
3553     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3554     for (auto I : RD->bases())
3555       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3556 
3557     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3558       return;
3559 
3560     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3561                                                    UninitializedFields,
3562                                                    UninitializedBaseClasses);
3563 
3564     for (const auto *FieldInit : Constructor->inits()) {
3565       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3566         break;
3567 
3568       Expr *InitExpr = FieldInit->getInit();
3569       if (!InitExpr)
3570         continue;
3571 
3572       if (CXXDefaultInitExpr *Default =
3573               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3574         InitExpr = Default->getExpr();
3575         if (!InitExpr)
3576           continue;
3577         // In class initializers will point to the constructor.
3578         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3579                                               FieldInit->getAnyMember(),
3580                                               FieldInit->getBaseClass());
3581       } else {
3582         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3583                                               FieldInit->getAnyMember(),
3584                                               FieldInit->getBaseClass());
3585       }
3586     }
3587   }
3588 } // namespace
3589 
3590 /// Enter a new C++ default initializer scope. After calling this, the
3591 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3592 /// parsing or instantiating the initializer failed.
3593 void Sema::ActOnStartCXXInClassMemberInitializer() {
3594   // Create a synthetic function scope to represent the call to the constructor
3595   // that notionally surrounds a use of this initializer.
3596   PushFunctionScope();
3597 }
3598 
3599 /// This is invoked after parsing an in-class initializer for a
3600 /// non-static C++ class member, and after instantiating an in-class initializer
3601 /// in a class template. Such actions are deferred until the class is complete.
3602 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3603                                                   SourceLocation InitLoc,
3604                                                   Expr *InitExpr) {
3605   // Pop the notional constructor scope we created earlier.
3606   PopFunctionScopeInfo(nullptr, D);
3607 
3608   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3609   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3610          "must set init style when field is created");
3611 
3612   if (!InitExpr) {
3613     D->setInvalidDecl();
3614     if (FD)
3615       FD->removeInClassInitializer();
3616     return;
3617   }
3618 
3619   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3620     FD->setInvalidDecl();
3621     FD->removeInClassInitializer();
3622     return;
3623   }
3624 
3625   ExprResult Init = InitExpr;
3626   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3627     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3628     InitializationKind Kind =
3629         FD->getInClassInitStyle() == ICIS_ListInit
3630             ? InitializationKind::CreateDirectList(InitExpr->getLocStart(),
3631                                                    InitExpr->getLocStart(),
3632                                                    InitExpr->getLocEnd())
3633             : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3634     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3635     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3636     if (Init.isInvalid()) {
3637       FD->setInvalidDecl();
3638       return;
3639     }
3640   }
3641 
3642   // C++11 [class.base.init]p7:
3643   //   The initialization of each base and member constitutes a
3644   //   full-expression.
3645   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3646   if (Init.isInvalid()) {
3647     FD->setInvalidDecl();
3648     return;
3649   }
3650 
3651   InitExpr = Init.get();
3652 
3653   FD->setInClassInitializer(InitExpr);
3654 }
3655 
3656 /// Find the direct and/or virtual base specifiers that
3657 /// correspond to the given base type, for use in base initialization
3658 /// within a constructor.
3659 static bool FindBaseInitializer(Sema &SemaRef,
3660                                 CXXRecordDecl *ClassDecl,
3661                                 QualType BaseType,
3662                                 const CXXBaseSpecifier *&DirectBaseSpec,
3663                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3664   // First, check for a direct base class.
3665   DirectBaseSpec = nullptr;
3666   for (const auto &Base : ClassDecl->bases()) {
3667     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3668       // We found a direct base of this type. That's what we're
3669       // initializing.
3670       DirectBaseSpec = &Base;
3671       break;
3672     }
3673   }
3674 
3675   // Check for a virtual base class.
3676   // FIXME: We might be able to short-circuit this if we know in advance that
3677   // there are no virtual bases.
3678   VirtualBaseSpec = nullptr;
3679   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3680     // We haven't found a base yet; search the class hierarchy for a
3681     // virtual base class.
3682     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3683                        /*DetectVirtual=*/false);
3684     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3685                               SemaRef.Context.getTypeDeclType(ClassDecl),
3686                               BaseType, Paths)) {
3687       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3688            Path != Paths.end(); ++Path) {
3689         if (Path->back().Base->isVirtual()) {
3690           VirtualBaseSpec = Path->back().Base;
3691           break;
3692         }
3693       }
3694     }
3695   }
3696 
3697   return DirectBaseSpec || VirtualBaseSpec;
3698 }
3699 
3700 /// Handle a C++ member initializer using braced-init-list syntax.
3701 MemInitResult
3702 Sema::ActOnMemInitializer(Decl *ConstructorD,
3703                           Scope *S,
3704                           CXXScopeSpec &SS,
3705                           IdentifierInfo *MemberOrBase,
3706                           ParsedType TemplateTypeTy,
3707                           const DeclSpec &DS,
3708                           SourceLocation IdLoc,
3709                           Expr *InitList,
3710                           SourceLocation EllipsisLoc) {
3711   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3712                              DS, IdLoc, InitList,
3713                              EllipsisLoc);
3714 }
3715 
3716 /// Handle a C++ member initializer using parentheses syntax.
3717 MemInitResult
3718 Sema::ActOnMemInitializer(Decl *ConstructorD,
3719                           Scope *S,
3720                           CXXScopeSpec &SS,
3721                           IdentifierInfo *MemberOrBase,
3722                           ParsedType TemplateTypeTy,
3723                           const DeclSpec &DS,
3724                           SourceLocation IdLoc,
3725                           SourceLocation LParenLoc,
3726                           ArrayRef<Expr *> Args,
3727                           SourceLocation RParenLoc,
3728                           SourceLocation EllipsisLoc) {
3729   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3730                                            Args, RParenLoc);
3731   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3732                              DS, IdLoc, List, EllipsisLoc);
3733 }
3734 
3735 namespace {
3736 
3737 // Callback to only accept typo corrections that can be a valid C++ member
3738 // intializer: either a non-static field member or a base class.
3739 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3740 public:
3741   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3742       : ClassDecl(ClassDecl) {}
3743 
3744   bool ValidateCandidate(const TypoCorrection &candidate) override {
3745     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3746       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3747         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3748       return isa<TypeDecl>(ND);
3749     }
3750     return false;
3751   }
3752 
3753 private:
3754   CXXRecordDecl *ClassDecl;
3755 };
3756 
3757 }
3758 
3759 /// Handle a C++ member initializer.
3760 MemInitResult
3761 Sema::BuildMemInitializer(Decl *ConstructorD,
3762                           Scope *S,
3763                           CXXScopeSpec &SS,
3764                           IdentifierInfo *MemberOrBase,
3765                           ParsedType TemplateTypeTy,
3766                           const DeclSpec &DS,
3767                           SourceLocation IdLoc,
3768                           Expr *Init,
3769                           SourceLocation EllipsisLoc) {
3770   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3771   if (!Res.isUsable())
3772     return true;
3773   Init = Res.get();
3774 
3775   if (!ConstructorD)
3776     return true;
3777 
3778   AdjustDeclIfTemplate(ConstructorD);
3779 
3780   CXXConstructorDecl *Constructor
3781     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3782   if (!Constructor) {
3783     // The user wrote a constructor initializer on a function that is
3784     // not a C++ constructor. Ignore the error for now, because we may
3785     // have more member initializers coming; we'll diagnose it just
3786     // once in ActOnMemInitializers.
3787     return true;
3788   }
3789 
3790   CXXRecordDecl *ClassDecl = Constructor->getParent();
3791 
3792   // C++ [class.base.init]p2:
3793   //   Names in a mem-initializer-id are looked up in the scope of the
3794   //   constructor's class and, if not found in that scope, are looked
3795   //   up in the scope containing the constructor's definition.
3796   //   [Note: if the constructor's class contains a member with the
3797   //   same name as a direct or virtual base class of the class, a
3798   //   mem-initializer-id naming the member or base class and composed
3799   //   of a single identifier refers to the class member. A
3800   //   mem-initializer-id for the hidden base class may be specified
3801   //   using a qualified name. ]
3802   if (!SS.getScopeRep() && !TemplateTypeTy) {
3803     // Look for a member, first.
3804     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3805     if (!Result.empty()) {
3806       ValueDecl *Member;
3807       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3808           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3809         if (EllipsisLoc.isValid())
3810           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3811             << MemberOrBase
3812             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3813 
3814         return BuildMemberInitializer(Member, Init, IdLoc);
3815       }
3816     }
3817   }
3818   // It didn't name a member, so see if it names a class.
3819   QualType BaseType;
3820   TypeSourceInfo *TInfo = nullptr;
3821 
3822   if (TemplateTypeTy) {
3823     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3824   } else if (DS.getTypeSpecType() == TST_decltype) {
3825     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3826   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3827     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3828     return true;
3829   } else {
3830     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3831     LookupParsedName(R, S, &SS);
3832 
3833     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3834     if (!TyD) {
3835       if (R.isAmbiguous()) return true;
3836 
3837       // We don't want access-control diagnostics here.
3838       R.suppressDiagnostics();
3839 
3840       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3841         bool NotUnknownSpecialization = false;
3842         DeclContext *DC = computeDeclContext(SS, false);
3843         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3844           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3845 
3846         if (!NotUnknownSpecialization) {
3847           // When the scope specifier can refer to a member of an unknown
3848           // specialization, we take it as a type name.
3849           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3850                                        SS.getWithLocInContext(Context),
3851                                        *MemberOrBase, IdLoc);
3852           if (BaseType.isNull())
3853             return true;
3854 
3855           TInfo = Context.CreateTypeSourceInfo(BaseType);
3856           DependentNameTypeLoc TL =
3857               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3858           if (!TL.isNull()) {
3859             TL.setNameLoc(IdLoc);
3860             TL.setElaboratedKeywordLoc(SourceLocation());
3861             TL.setQualifierLoc(SS.getWithLocInContext(Context));
3862           }
3863 
3864           R.clear();
3865           R.setLookupName(MemberOrBase);
3866         }
3867       }
3868 
3869       // If no results were found, try to correct typos.
3870       TypoCorrection Corr;
3871       if (R.empty() && BaseType.isNull() &&
3872           (Corr = CorrectTypo(
3873                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3874                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3875                CTK_ErrorRecovery, ClassDecl))) {
3876         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3877           // We have found a non-static data member with a similar
3878           // name to what was typed; complain and initialize that
3879           // member.
3880           diagnoseTypo(Corr,
3881                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3882                          << MemberOrBase << true);
3883           return BuildMemberInitializer(Member, Init, IdLoc);
3884         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3885           const CXXBaseSpecifier *DirectBaseSpec;
3886           const CXXBaseSpecifier *VirtualBaseSpec;
3887           if (FindBaseInitializer(*this, ClassDecl,
3888                                   Context.getTypeDeclType(Type),
3889                                   DirectBaseSpec, VirtualBaseSpec)) {
3890             // We have found a direct or virtual base class with a
3891             // similar name to what was typed; complain and initialize
3892             // that base class.
3893             diagnoseTypo(Corr,
3894                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3895                            << MemberOrBase << false,
3896                          PDiag() /*Suppress note, we provide our own.*/);
3897 
3898             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3899                                                               : VirtualBaseSpec;
3900             Diag(BaseSpec->getLocStart(),
3901                  diag::note_base_class_specified_here)
3902               << BaseSpec->getType()
3903               << BaseSpec->getSourceRange();
3904 
3905             TyD = Type;
3906           }
3907         }
3908       }
3909 
3910       if (!TyD && BaseType.isNull()) {
3911         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3912           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3913         return true;
3914       }
3915     }
3916 
3917     if (BaseType.isNull()) {
3918       BaseType = Context.getTypeDeclType(TyD);
3919       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3920       if (SS.isSet()) {
3921         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3922                                              BaseType);
3923         TInfo = Context.CreateTypeSourceInfo(BaseType);
3924         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3925         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3926         TL.setElaboratedKeywordLoc(SourceLocation());
3927         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3928       }
3929     }
3930   }
3931 
3932   if (!TInfo)
3933     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3934 
3935   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3936 }
3937 
3938 /// Checks a member initializer expression for cases where reference (or
3939 /// pointer) members are bound to by-value parameters (or their addresses).
3940 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3941                                                Expr *Init,
3942                                                SourceLocation IdLoc) {
3943   QualType MemberTy = Member->getType();
3944 
3945   // We only handle pointers and references currently.
3946   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3947   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3948     return;
3949 
3950   const bool IsPointer = MemberTy->isPointerType();
3951   if (IsPointer) {
3952     if (const UnaryOperator *Op
3953           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3954       // The only case we're worried about with pointers requires taking the
3955       // address.
3956       if (Op->getOpcode() != UO_AddrOf)
3957         return;
3958 
3959       Init = Op->getSubExpr();
3960     } else {
3961       // We only handle address-of expression initializers for pointers.
3962       return;
3963     }
3964   }
3965 
3966   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3967     // We only warn when referring to a non-reference parameter declaration.
3968     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3969     if (!Parameter || Parameter->getType()->isReferenceType())
3970       return;
3971 
3972     S.Diag(Init->getExprLoc(),
3973            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3974                      : diag::warn_bind_ref_member_to_parameter)
3975       << Member << Parameter << Init->getSourceRange();
3976   } else {
3977     // Other initializers are fine.
3978     return;
3979   }
3980 
3981   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3982     << (unsigned)IsPointer;
3983 }
3984 
3985 MemInitResult
3986 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3987                              SourceLocation IdLoc) {
3988   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3989   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3990   assert((DirectMember || IndirectMember) &&
3991          "Member must be a FieldDecl or IndirectFieldDecl");
3992 
3993   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3994     return true;
3995 
3996   if (Member->isInvalidDecl())
3997     return true;
3998 
3999   MultiExprArg Args;
4000   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4001     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4002   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4003     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4004   } else {
4005     // Template instantiation doesn't reconstruct ParenListExprs for us.
4006     Args = Init;
4007   }
4008 
4009   SourceRange InitRange = Init->getSourceRange();
4010 
4011   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4012     // Can't check initialization for a member of dependent type or when
4013     // any of the arguments are type-dependent expressions.
4014     DiscardCleanupsInEvaluationContext();
4015   } else {
4016     bool InitList = false;
4017     if (isa<InitListExpr>(Init)) {
4018       InitList = true;
4019       Args = Init;
4020     }
4021 
4022     // Initialize the member.
4023     InitializedEntity MemberEntity =
4024       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4025                    : InitializedEntity::InitializeMember(IndirectMember,
4026                                                          nullptr);
4027     InitializationKind Kind =
4028         InitList ? InitializationKind::CreateDirectList(
4029                        IdLoc, Init->getLocStart(), Init->getLocEnd())
4030                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4031                                                     InitRange.getEnd());
4032 
4033     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4034     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4035                                             nullptr);
4036     if (MemberInit.isInvalid())
4037       return true;
4038 
4039     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
4040 
4041     // C++11 [class.base.init]p7:
4042     //   The initialization of each base and member constitutes a
4043     //   full-expression.
4044     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4045     if (MemberInit.isInvalid())
4046       return true;
4047 
4048     Init = MemberInit.get();
4049   }
4050 
4051   if (DirectMember) {
4052     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4053                                             InitRange.getBegin(), Init,
4054                                             InitRange.getEnd());
4055   } else {
4056     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4057                                             InitRange.getBegin(), Init,
4058                                             InitRange.getEnd());
4059   }
4060 }
4061 
4062 MemInitResult
4063 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4064                                  CXXRecordDecl *ClassDecl) {
4065   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4066   if (!LangOpts.CPlusPlus11)
4067     return Diag(NameLoc, diag::err_delegating_ctor)
4068       << TInfo->getTypeLoc().getLocalSourceRange();
4069   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4070 
4071   bool InitList = true;
4072   MultiExprArg Args = Init;
4073   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4074     InitList = false;
4075     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4076   }
4077 
4078   SourceRange InitRange = Init->getSourceRange();
4079   // Initialize the object.
4080   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4081                                      QualType(ClassDecl->getTypeForDecl(), 0));
4082   InitializationKind Kind =
4083       InitList ? InitializationKind::CreateDirectList(
4084                      NameLoc, Init->getLocStart(), Init->getLocEnd())
4085                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4086                                                   InitRange.getEnd());
4087   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4088   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4089                                               Args, nullptr);
4090   if (DelegationInit.isInvalid())
4091     return true;
4092 
4093   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4094          "Delegating constructor with no target?");
4095 
4096   // C++11 [class.base.init]p7:
4097   //   The initialization of each base and member constitutes a
4098   //   full-expression.
4099   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4100                                        InitRange.getBegin());
4101   if (DelegationInit.isInvalid())
4102     return true;
4103 
4104   // If we are in a dependent context, template instantiation will
4105   // perform this type-checking again. Just save the arguments that we
4106   // received in a ParenListExpr.
4107   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4108   // of the information that we have about the base
4109   // initializer. However, deconstructing the ASTs is a dicey process,
4110   // and this approach is far more likely to get the corner cases right.
4111   if (CurContext->isDependentContext())
4112     DelegationInit = Init;
4113 
4114   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4115                                           DelegationInit.getAs<Expr>(),
4116                                           InitRange.getEnd());
4117 }
4118 
4119 MemInitResult
4120 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4121                            Expr *Init, CXXRecordDecl *ClassDecl,
4122                            SourceLocation EllipsisLoc) {
4123   SourceLocation BaseLoc
4124     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4125 
4126   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4127     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4128              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4129 
4130   // C++ [class.base.init]p2:
4131   //   [...] Unless the mem-initializer-id names a nonstatic data
4132   //   member of the constructor's class or a direct or virtual base
4133   //   of that class, the mem-initializer is ill-formed. A
4134   //   mem-initializer-list can initialize a base class using any
4135   //   name that denotes that base class type.
4136   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4137 
4138   SourceRange InitRange = Init->getSourceRange();
4139   if (EllipsisLoc.isValid()) {
4140     // This is a pack expansion.
4141     if (!BaseType->containsUnexpandedParameterPack())  {
4142       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4143         << SourceRange(BaseLoc, InitRange.getEnd());
4144 
4145       EllipsisLoc = SourceLocation();
4146     }
4147   } else {
4148     // Check for any unexpanded parameter packs.
4149     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4150       return true;
4151 
4152     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4153       return true;
4154   }
4155 
4156   // Check for direct and virtual base classes.
4157   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4158   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4159   if (!Dependent) {
4160     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4161                                        BaseType))
4162       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4163 
4164     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4165                         VirtualBaseSpec);
4166 
4167     // C++ [base.class.init]p2:
4168     // Unless the mem-initializer-id names a nonstatic data member of the
4169     // constructor's class or a direct or virtual base of that class, the
4170     // mem-initializer is ill-formed.
4171     if (!DirectBaseSpec && !VirtualBaseSpec) {
4172       // If the class has any dependent bases, then it's possible that
4173       // one of those types will resolve to the same type as
4174       // BaseType. Therefore, just treat this as a dependent base
4175       // class initialization.  FIXME: Should we try to check the
4176       // initialization anyway? It seems odd.
4177       if (ClassDecl->hasAnyDependentBases())
4178         Dependent = true;
4179       else
4180         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4181           << BaseType << Context.getTypeDeclType(ClassDecl)
4182           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4183     }
4184   }
4185 
4186   if (Dependent) {
4187     DiscardCleanupsInEvaluationContext();
4188 
4189     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4190                                             /*IsVirtual=*/false,
4191                                             InitRange.getBegin(), Init,
4192                                             InitRange.getEnd(), EllipsisLoc);
4193   }
4194 
4195   // C++ [base.class.init]p2:
4196   //   If a mem-initializer-id is ambiguous because it designates both
4197   //   a direct non-virtual base class and an inherited virtual base
4198   //   class, the mem-initializer is ill-formed.
4199   if (DirectBaseSpec && VirtualBaseSpec)
4200     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4201       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4202 
4203   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4204   if (!BaseSpec)
4205     BaseSpec = VirtualBaseSpec;
4206 
4207   // Initialize the base.
4208   bool InitList = true;
4209   MultiExprArg Args = Init;
4210   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4211     InitList = false;
4212     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4213   }
4214 
4215   InitializedEntity BaseEntity =
4216     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4217   InitializationKind Kind =
4218       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4219                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4220                                                   InitRange.getEnd());
4221   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4222   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4223   if (BaseInit.isInvalid())
4224     return true;
4225 
4226   // C++11 [class.base.init]p7:
4227   //   The initialization of each base and member constitutes a
4228   //   full-expression.
4229   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4230   if (BaseInit.isInvalid())
4231     return true;
4232 
4233   // If we are in a dependent context, template instantiation will
4234   // perform this type-checking again. Just save the arguments that we
4235   // received in a ParenListExpr.
4236   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4237   // of the information that we have about the base
4238   // initializer. However, deconstructing the ASTs is a dicey process,
4239   // and this approach is far more likely to get the corner cases right.
4240   if (CurContext->isDependentContext())
4241     BaseInit = Init;
4242 
4243   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4244                                           BaseSpec->isVirtual(),
4245                                           InitRange.getBegin(),
4246                                           BaseInit.getAs<Expr>(),
4247                                           InitRange.getEnd(), EllipsisLoc);
4248 }
4249 
4250 // Create a static_cast\<T&&>(expr).
4251 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4252   if (T.isNull()) T = E->getType();
4253   QualType TargetType = SemaRef.BuildReferenceType(
4254       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4255   SourceLocation ExprLoc = E->getLocStart();
4256   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4257       TargetType, ExprLoc);
4258 
4259   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4260                                    SourceRange(ExprLoc, ExprLoc),
4261                                    E->getSourceRange()).get();
4262 }
4263 
4264 /// ImplicitInitializerKind - How an implicit base or member initializer should
4265 /// initialize its base or member.
4266 enum ImplicitInitializerKind {
4267   IIK_Default,
4268   IIK_Copy,
4269   IIK_Move,
4270   IIK_Inherit
4271 };
4272 
4273 static bool
4274 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4275                              ImplicitInitializerKind ImplicitInitKind,
4276                              CXXBaseSpecifier *BaseSpec,
4277                              bool IsInheritedVirtualBase,
4278                              CXXCtorInitializer *&CXXBaseInit) {
4279   InitializedEntity InitEntity
4280     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4281                                         IsInheritedVirtualBase);
4282 
4283   ExprResult BaseInit;
4284 
4285   switch (ImplicitInitKind) {
4286   case IIK_Inherit:
4287   case IIK_Default: {
4288     InitializationKind InitKind
4289       = InitializationKind::CreateDefault(Constructor->getLocation());
4290     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4291     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4292     break;
4293   }
4294 
4295   case IIK_Move:
4296   case IIK_Copy: {
4297     bool Moving = ImplicitInitKind == IIK_Move;
4298     ParmVarDecl *Param = Constructor->getParamDecl(0);
4299     QualType ParamType = Param->getType().getNonReferenceType();
4300 
4301     Expr *CopyCtorArg =
4302       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4303                           SourceLocation(), Param, false,
4304                           Constructor->getLocation(), ParamType,
4305                           VK_LValue, nullptr);
4306 
4307     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4308 
4309     // Cast to the base class to avoid ambiguities.
4310     QualType ArgTy =
4311       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4312                                        ParamType.getQualifiers());
4313 
4314     if (Moving) {
4315       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4316     }
4317 
4318     CXXCastPath BasePath;
4319     BasePath.push_back(BaseSpec);
4320     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4321                                             CK_UncheckedDerivedToBase,
4322                                             Moving ? VK_XValue : VK_LValue,
4323                                             &BasePath).get();
4324 
4325     InitializationKind InitKind
4326       = InitializationKind::CreateDirect(Constructor->getLocation(),
4327                                          SourceLocation(), SourceLocation());
4328     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4329     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4330     break;
4331   }
4332   }
4333 
4334   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4335   if (BaseInit.isInvalid())
4336     return true;
4337 
4338   CXXBaseInit =
4339     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4340                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4341                                                         SourceLocation()),
4342                                              BaseSpec->isVirtual(),
4343                                              SourceLocation(),
4344                                              BaseInit.getAs<Expr>(),
4345                                              SourceLocation(),
4346                                              SourceLocation());
4347 
4348   return false;
4349 }
4350 
4351 static bool RefersToRValueRef(Expr *MemRef) {
4352   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4353   return Referenced->getType()->isRValueReferenceType();
4354 }
4355 
4356 static bool
4357 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4358                                ImplicitInitializerKind ImplicitInitKind,
4359                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4360                                CXXCtorInitializer *&CXXMemberInit) {
4361   if (Field->isInvalidDecl())
4362     return true;
4363 
4364   SourceLocation Loc = Constructor->getLocation();
4365 
4366   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4367     bool Moving = ImplicitInitKind == IIK_Move;
4368     ParmVarDecl *Param = Constructor->getParamDecl(0);
4369     QualType ParamType = Param->getType().getNonReferenceType();
4370 
4371     // Suppress copying zero-width bitfields.
4372     if (Field->isZeroLengthBitField(SemaRef.Context))
4373       return false;
4374 
4375     Expr *MemberExprBase =
4376       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4377                           SourceLocation(), Param, false,
4378                           Loc, ParamType, VK_LValue, nullptr);
4379 
4380     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4381 
4382     if (Moving) {
4383       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4384     }
4385 
4386     // Build a reference to this field within the parameter.
4387     CXXScopeSpec SS;
4388     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4389                               Sema::LookupMemberName);
4390     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4391                                   : cast<ValueDecl>(Field), AS_public);
4392     MemberLookup.resolveKind();
4393     ExprResult CtorArg
4394       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4395                                          ParamType, Loc,
4396                                          /*IsArrow=*/false,
4397                                          SS,
4398                                          /*TemplateKWLoc=*/SourceLocation(),
4399                                          /*FirstQualifierInScope=*/nullptr,
4400                                          MemberLookup,
4401                                          /*TemplateArgs=*/nullptr,
4402                                          /*S*/nullptr);
4403     if (CtorArg.isInvalid())
4404       return true;
4405 
4406     // C++11 [class.copy]p15:
4407     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4408     //     with static_cast<T&&>(x.m);
4409     if (RefersToRValueRef(CtorArg.get())) {
4410       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4411     }
4412 
4413     InitializedEntity Entity =
4414         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4415                                                        /*Implicit*/ true)
4416                  : InitializedEntity::InitializeMember(Field, nullptr,
4417                                                        /*Implicit*/ true);
4418 
4419     // Direct-initialize to use the copy constructor.
4420     InitializationKind InitKind =
4421       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4422 
4423     Expr *CtorArgE = CtorArg.getAs<Expr>();
4424     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4425     ExprResult MemberInit =
4426         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4427     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4428     if (MemberInit.isInvalid())
4429       return true;
4430 
4431     if (Indirect)
4432       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4433           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4434     else
4435       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4436           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4437     return false;
4438   }
4439 
4440   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4441          "Unhandled implicit init kind!");
4442 
4443   QualType FieldBaseElementType =
4444     SemaRef.Context.getBaseElementType(Field->getType());
4445 
4446   if (FieldBaseElementType->isRecordType()) {
4447     InitializedEntity InitEntity =
4448         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4449                                                        /*Implicit*/ true)
4450                  : InitializedEntity::InitializeMember(Field, nullptr,
4451                                                        /*Implicit*/ true);
4452     InitializationKind InitKind =
4453       InitializationKind::CreateDefault(Loc);
4454 
4455     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4456     ExprResult MemberInit =
4457       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4458 
4459     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4460     if (MemberInit.isInvalid())
4461       return true;
4462 
4463     if (Indirect)
4464       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4465                                                                Indirect, Loc,
4466                                                                Loc,
4467                                                                MemberInit.get(),
4468                                                                Loc);
4469     else
4470       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4471                                                                Field, Loc, Loc,
4472                                                                MemberInit.get(),
4473                                                                Loc);
4474     return false;
4475   }
4476 
4477   if (!Field->getParent()->isUnion()) {
4478     if (FieldBaseElementType->isReferenceType()) {
4479       SemaRef.Diag(Constructor->getLocation(),
4480                    diag::err_uninitialized_member_in_ctor)
4481       << (int)Constructor->isImplicit()
4482       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4483       << 0 << Field->getDeclName();
4484       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4485       return true;
4486     }
4487 
4488     if (FieldBaseElementType.isConstQualified()) {
4489       SemaRef.Diag(Constructor->getLocation(),
4490                    diag::err_uninitialized_member_in_ctor)
4491       << (int)Constructor->isImplicit()
4492       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4493       << 1 << Field->getDeclName();
4494       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4495       return true;
4496     }
4497   }
4498 
4499   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4500     // ARC and Weak:
4501     //   Default-initialize Objective-C pointers to NULL.
4502     CXXMemberInit
4503       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4504                                                  Loc, Loc,
4505                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4506                                                  Loc);
4507     return false;
4508   }
4509 
4510   // Nothing to initialize.
4511   CXXMemberInit = nullptr;
4512   return false;
4513 }
4514 
4515 namespace {
4516 struct BaseAndFieldInfo {
4517   Sema &S;
4518   CXXConstructorDecl *Ctor;
4519   bool AnyErrorsInInits;
4520   ImplicitInitializerKind IIK;
4521   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4522   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4523   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4524 
4525   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4526     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4527     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4528     if (Ctor->getInheritedConstructor())
4529       IIK = IIK_Inherit;
4530     else if (Generated && Ctor->isCopyConstructor())
4531       IIK = IIK_Copy;
4532     else if (Generated && Ctor->isMoveConstructor())
4533       IIK = IIK_Move;
4534     else
4535       IIK = IIK_Default;
4536   }
4537 
4538   bool isImplicitCopyOrMove() const {
4539     switch (IIK) {
4540     case IIK_Copy:
4541     case IIK_Move:
4542       return true;
4543 
4544     case IIK_Default:
4545     case IIK_Inherit:
4546       return false;
4547     }
4548 
4549     llvm_unreachable("Invalid ImplicitInitializerKind!");
4550   }
4551 
4552   bool addFieldInitializer(CXXCtorInitializer *Init) {
4553     AllToInit.push_back(Init);
4554 
4555     // Check whether this initializer makes the field "used".
4556     if (Init->getInit()->HasSideEffects(S.Context))
4557       S.UnusedPrivateFields.remove(Init->getAnyMember());
4558 
4559     return false;
4560   }
4561 
4562   bool isInactiveUnionMember(FieldDecl *Field) {
4563     RecordDecl *Record = Field->getParent();
4564     if (!Record->isUnion())
4565       return false;
4566 
4567     if (FieldDecl *Active =
4568             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4569       return Active != Field->getCanonicalDecl();
4570 
4571     // In an implicit copy or move constructor, ignore any in-class initializer.
4572     if (isImplicitCopyOrMove())
4573       return true;
4574 
4575     // If there's no explicit initialization, the field is active only if it
4576     // has an in-class initializer...
4577     if (Field->hasInClassInitializer())
4578       return false;
4579     // ... or it's an anonymous struct or union whose class has an in-class
4580     // initializer.
4581     if (!Field->isAnonymousStructOrUnion())
4582       return true;
4583     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4584     return !FieldRD->hasInClassInitializer();
4585   }
4586 
4587   /// Determine whether the given field is, or is within, a union member
4588   /// that is inactive (because there was an initializer given for a different
4589   /// member of the union, or because the union was not initialized at all).
4590   bool isWithinInactiveUnionMember(FieldDecl *Field,
4591                                    IndirectFieldDecl *Indirect) {
4592     if (!Indirect)
4593       return isInactiveUnionMember(Field);
4594 
4595     for (auto *C : Indirect->chain()) {
4596       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4597       if (Field && isInactiveUnionMember(Field))
4598         return true;
4599     }
4600     return false;
4601   }
4602 };
4603 }
4604 
4605 /// Determine whether the given type is an incomplete or zero-lenfgth
4606 /// array type.
4607 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4608   if (T->isIncompleteArrayType())
4609     return true;
4610 
4611   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4612     if (!ArrayT->getSize())
4613       return true;
4614 
4615     T = ArrayT->getElementType();
4616   }
4617 
4618   return false;
4619 }
4620 
4621 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4622                                     FieldDecl *Field,
4623                                     IndirectFieldDecl *Indirect = nullptr) {
4624   if (Field->isInvalidDecl())
4625     return false;
4626 
4627   // Overwhelmingly common case: we have a direct initializer for this field.
4628   if (CXXCtorInitializer *Init =
4629           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4630     return Info.addFieldInitializer(Init);
4631 
4632   // C++11 [class.base.init]p8:
4633   //   if the entity is a non-static data member that has a
4634   //   brace-or-equal-initializer and either
4635   //   -- the constructor's class is a union and no other variant member of that
4636   //      union is designated by a mem-initializer-id or
4637   //   -- the constructor's class is not a union, and, if the entity is a member
4638   //      of an anonymous union, no other member of that union is designated by
4639   //      a mem-initializer-id,
4640   //   the entity is initialized as specified in [dcl.init].
4641   //
4642   // We also apply the same rules to handle anonymous structs within anonymous
4643   // unions.
4644   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4645     return false;
4646 
4647   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4648     ExprResult DIE =
4649         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4650     if (DIE.isInvalid())
4651       return true;
4652     CXXCtorInitializer *Init;
4653     if (Indirect)
4654       Init = new (SemaRef.Context)
4655           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4656                              SourceLocation(), DIE.get(), SourceLocation());
4657     else
4658       Init = new (SemaRef.Context)
4659           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4660                              SourceLocation(), DIE.get(), SourceLocation());
4661     return Info.addFieldInitializer(Init);
4662   }
4663 
4664   // Don't initialize incomplete or zero-length arrays.
4665   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4666     return false;
4667 
4668   // Don't try to build an implicit initializer if there were semantic
4669   // errors in any of the initializers (and therefore we might be
4670   // missing some that the user actually wrote).
4671   if (Info.AnyErrorsInInits)
4672     return false;
4673 
4674   CXXCtorInitializer *Init = nullptr;
4675   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4676                                      Indirect, Init))
4677     return true;
4678 
4679   if (!Init)
4680     return false;
4681 
4682   return Info.addFieldInitializer(Init);
4683 }
4684 
4685 bool
4686 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4687                                CXXCtorInitializer *Initializer) {
4688   assert(Initializer->isDelegatingInitializer());
4689   Constructor->setNumCtorInitializers(1);
4690   CXXCtorInitializer **initializer =
4691     new (Context) CXXCtorInitializer*[1];
4692   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4693   Constructor->setCtorInitializers(initializer);
4694 
4695   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4696     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4697     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4698   }
4699 
4700   DelegatingCtorDecls.push_back(Constructor);
4701 
4702   DiagnoseUninitializedFields(*this, Constructor);
4703 
4704   return false;
4705 }
4706 
4707 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4708                                ArrayRef<CXXCtorInitializer *> Initializers) {
4709   if (Constructor->isDependentContext()) {
4710     // Just store the initializers as written, they will be checked during
4711     // instantiation.
4712     if (!Initializers.empty()) {
4713       Constructor->setNumCtorInitializers(Initializers.size());
4714       CXXCtorInitializer **baseOrMemberInitializers =
4715         new (Context) CXXCtorInitializer*[Initializers.size()];
4716       memcpy(baseOrMemberInitializers, Initializers.data(),
4717              Initializers.size() * sizeof(CXXCtorInitializer*));
4718       Constructor->setCtorInitializers(baseOrMemberInitializers);
4719     }
4720 
4721     // Let template instantiation know whether we had errors.
4722     if (AnyErrors)
4723       Constructor->setInvalidDecl();
4724 
4725     return false;
4726   }
4727 
4728   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4729 
4730   // We need to build the initializer AST according to order of construction
4731   // and not what user specified in the Initializers list.
4732   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4733   if (!ClassDecl)
4734     return true;
4735 
4736   bool HadError = false;
4737 
4738   for (unsigned i = 0; i < Initializers.size(); i++) {
4739     CXXCtorInitializer *Member = Initializers[i];
4740 
4741     if (Member->isBaseInitializer())
4742       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4743     else {
4744       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4745 
4746       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4747         for (auto *C : F->chain()) {
4748           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4749           if (FD && FD->getParent()->isUnion())
4750             Info.ActiveUnionMember.insert(std::make_pair(
4751                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4752         }
4753       } else if (FieldDecl *FD = Member->getMember()) {
4754         if (FD->getParent()->isUnion())
4755           Info.ActiveUnionMember.insert(std::make_pair(
4756               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4757       }
4758     }
4759   }
4760 
4761   // Keep track of the direct virtual bases.
4762   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4763   for (auto &I : ClassDecl->bases()) {
4764     if (I.isVirtual())
4765       DirectVBases.insert(&I);
4766   }
4767 
4768   // Push virtual bases before others.
4769   for (auto &VBase : ClassDecl->vbases()) {
4770     if (CXXCtorInitializer *Value
4771         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4772       // [class.base.init]p7, per DR257:
4773       //   A mem-initializer where the mem-initializer-id names a virtual base
4774       //   class is ignored during execution of a constructor of any class that
4775       //   is not the most derived class.
4776       if (ClassDecl->isAbstract()) {
4777         // FIXME: Provide a fixit to remove the base specifier. This requires
4778         // tracking the location of the associated comma for a base specifier.
4779         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4780           << VBase.getType() << ClassDecl;
4781         DiagnoseAbstractType(ClassDecl);
4782       }
4783 
4784       Info.AllToInit.push_back(Value);
4785     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4786       // [class.base.init]p8, per DR257:
4787       //   If a given [...] base class is not named by a mem-initializer-id
4788       //   [...] and the entity is not a virtual base class of an abstract
4789       //   class, then [...] the entity is default-initialized.
4790       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4791       CXXCtorInitializer *CXXBaseInit;
4792       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4793                                        &VBase, IsInheritedVirtualBase,
4794                                        CXXBaseInit)) {
4795         HadError = true;
4796         continue;
4797       }
4798 
4799       Info.AllToInit.push_back(CXXBaseInit);
4800     }
4801   }
4802 
4803   // Non-virtual bases.
4804   for (auto &Base : ClassDecl->bases()) {
4805     // Virtuals are in the virtual base list and already constructed.
4806     if (Base.isVirtual())
4807       continue;
4808 
4809     if (CXXCtorInitializer *Value
4810           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4811       Info.AllToInit.push_back(Value);
4812     } else if (!AnyErrors) {
4813       CXXCtorInitializer *CXXBaseInit;
4814       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4815                                        &Base, /*IsInheritedVirtualBase=*/false,
4816                                        CXXBaseInit)) {
4817         HadError = true;
4818         continue;
4819       }
4820 
4821       Info.AllToInit.push_back(CXXBaseInit);
4822     }
4823   }
4824 
4825   // Fields.
4826   for (auto *Mem : ClassDecl->decls()) {
4827     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4828       // C++ [class.bit]p2:
4829       //   A declaration for a bit-field that omits the identifier declares an
4830       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4831       //   initialized.
4832       if (F->isUnnamedBitfield())
4833         continue;
4834 
4835       // If we're not generating the implicit copy/move constructor, then we'll
4836       // handle anonymous struct/union fields based on their individual
4837       // indirect fields.
4838       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4839         continue;
4840 
4841       if (CollectFieldInitializer(*this, Info, F))
4842         HadError = true;
4843       continue;
4844     }
4845 
4846     // Beyond this point, we only consider default initialization.
4847     if (Info.isImplicitCopyOrMove())
4848       continue;
4849 
4850     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4851       if (F->getType()->isIncompleteArrayType()) {
4852         assert(ClassDecl->hasFlexibleArrayMember() &&
4853                "Incomplete array type is not valid");
4854         continue;
4855       }
4856 
4857       // Initialize each field of an anonymous struct individually.
4858       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4859         HadError = true;
4860 
4861       continue;
4862     }
4863   }
4864 
4865   unsigned NumInitializers = Info.AllToInit.size();
4866   if (NumInitializers > 0) {
4867     Constructor->setNumCtorInitializers(NumInitializers);
4868     CXXCtorInitializer **baseOrMemberInitializers =
4869       new (Context) CXXCtorInitializer*[NumInitializers];
4870     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4871            NumInitializers * sizeof(CXXCtorInitializer*));
4872     Constructor->setCtorInitializers(baseOrMemberInitializers);
4873 
4874     // Constructors implicitly reference the base and member
4875     // destructors.
4876     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4877                                            Constructor->getParent());
4878   }
4879 
4880   return HadError;
4881 }
4882 
4883 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4884   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4885     const RecordDecl *RD = RT->getDecl();
4886     if (RD->isAnonymousStructOrUnion()) {
4887       for (auto *Field : RD->fields())
4888         PopulateKeysForFields(Field, IdealInits);
4889       return;
4890     }
4891   }
4892   IdealInits.push_back(Field->getCanonicalDecl());
4893 }
4894 
4895 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4896   return Context.getCanonicalType(BaseType).getTypePtr();
4897 }
4898 
4899 static const void *GetKeyForMember(ASTContext &Context,
4900                                    CXXCtorInitializer *Member) {
4901   if (!Member->isAnyMemberInitializer())
4902     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4903 
4904   return Member->getAnyMember()->getCanonicalDecl();
4905 }
4906 
4907 static void DiagnoseBaseOrMemInitializerOrder(
4908     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4909     ArrayRef<CXXCtorInitializer *> Inits) {
4910   if (Constructor->getDeclContext()->isDependentContext())
4911     return;
4912 
4913   // Don't check initializers order unless the warning is enabled at the
4914   // location of at least one initializer.
4915   bool ShouldCheckOrder = false;
4916   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4917     CXXCtorInitializer *Init = Inits[InitIndex];
4918     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4919                                  Init->getSourceLocation())) {
4920       ShouldCheckOrder = true;
4921       break;
4922     }
4923   }
4924   if (!ShouldCheckOrder)
4925     return;
4926 
4927   // Build the list of bases and members in the order that they'll
4928   // actually be initialized.  The explicit initializers should be in
4929   // this same order but may be missing things.
4930   SmallVector<const void*, 32> IdealInitKeys;
4931 
4932   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4933 
4934   // 1. Virtual bases.
4935   for (const auto &VBase : ClassDecl->vbases())
4936     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4937 
4938   // 2. Non-virtual bases.
4939   for (const auto &Base : ClassDecl->bases()) {
4940     if (Base.isVirtual())
4941       continue;
4942     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4943   }
4944 
4945   // 3. Direct fields.
4946   for (auto *Field : ClassDecl->fields()) {
4947     if (Field->isUnnamedBitfield())
4948       continue;
4949 
4950     PopulateKeysForFields(Field, IdealInitKeys);
4951   }
4952 
4953   unsigned NumIdealInits = IdealInitKeys.size();
4954   unsigned IdealIndex = 0;
4955 
4956   CXXCtorInitializer *PrevInit = nullptr;
4957   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4958     CXXCtorInitializer *Init = Inits[InitIndex];
4959     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4960 
4961     // Scan forward to try to find this initializer in the idealized
4962     // initializers list.
4963     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4964       if (InitKey == IdealInitKeys[IdealIndex])
4965         break;
4966 
4967     // If we didn't find this initializer, it must be because we
4968     // scanned past it on a previous iteration.  That can only
4969     // happen if we're out of order;  emit a warning.
4970     if (IdealIndex == NumIdealInits && PrevInit) {
4971       Sema::SemaDiagnosticBuilder D =
4972         SemaRef.Diag(PrevInit->getSourceLocation(),
4973                      diag::warn_initializer_out_of_order);
4974 
4975       if (PrevInit->isAnyMemberInitializer())
4976         D << 0 << PrevInit->getAnyMember()->getDeclName();
4977       else
4978         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4979 
4980       if (Init->isAnyMemberInitializer())
4981         D << 0 << Init->getAnyMember()->getDeclName();
4982       else
4983         D << 1 << Init->getTypeSourceInfo()->getType();
4984 
4985       // Move back to the initializer's location in the ideal list.
4986       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4987         if (InitKey == IdealInitKeys[IdealIndex])
4988           break;
4989 
4990       assert(IdealIndex < NumIdealInits &&
4991              "initializer not found in initializer list");
4992     }
4993 
4994     PrevInit = Init;
4995   }
4996 }
4997 
4998 namespace {
4999 bool CheckRedundantInit(Sema &S,
5000                         CXXCtorInitializer *Init,
5001                         CXXCtorInitializer *&PrevInit) {
5002   if (!PrevInit) {
5003     PrevInit = Init;
5004     return false;
5005   }
5006 
5007   if (FieldDecl *Field = Init->getAnyMember())
5008     S.Diag(Init->getSourceLocation(),
5009            diag::err_multiple_mem_initialization)
5010       << Field->getDeclName()
5011       << Init->getSourceRange();
5012   else {
5013     const Type *BaseClass = Init->getBaseClass();
5014     assert(BaseClass && "neither field nor base");
5015     S.Diag(Init->getSourceLocation(),
5016            diag::err_multiple_base_initialization)
5017       << QualType(BaseClass, 0)
5018       << Init->getSourceRange();
5019   }
5020   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5021     << 0 << PrevInit->getSourceRange();
5022 
5023   return true;
5024 }
5025 
5026 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5027 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5028 
5029 bool CheckRedundantUnionInit(Sema &S,
5030                              CXXCtorInitializer *Init,
5031                              RedundantUnionMap &Unions) {
5032   FieldDecl *Field = Init->getAnyMember();
5033   RecordDecl *Parent = Field->getParent();
5034   NamedDecl *Child = Field;
5035 
5036   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5037     if (Parent->isUnion()) {
5038       UnionEntry &En = Unions[Parent];
5039       if (En.first && En.first != Child) {
5040         S.Diag(Init->getSourceLocation(),
5041                diag::err_multiple_mem_union_initialization)
5042           << Field->getDeclName()
5043           << Init->getSourceRange();
5044         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5045           << 0 << En.second->getSourceRange();
5046         return true;
5047       }
5048       if (!En.first) {
5049         En.first = Child;
5050         En.second = Init;
5051       }
5052       if (!Parent->isAnonymousStructOrUnion())
5053         return false;
5054     }
5055 
5056     Child = Parent;
5057     Parent = cast<RecordDecl>(Parent->getDeclContext());
5058   }
5059 
5060   return false;
5061 }
5062 }
5063 
5064 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5065 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5066                                 SourceLocation ColonLoc,
5067                                 ArrayRef<CXXCtorInitializer*> MemInits,
5068                                 bool AnyErrors) {
5069   if (!ConstructorDecl)
5070     return;
5071 
5072   AdjustDeclIfTemplate(ConstructorDecl);
5073 
5074   CXXConstructorDecl *Constructor
5075     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5076 
5077   if (!Constructor) {
5078     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5079     return;
5080   }
5081 
5082   // Mapping for the duplicate initializers check.
5083   // For member initializers, this is keyed with a FieldDecl*.
5084   // For base initializers, this is keyed with a Type*.
5085   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5086 
5087   // Mapping for the inconsistent anonymous-union initializers check.
5088   RedundantUnionMap MemberUnions;
5089 
5090   bool HadError = false;
5091   for (unsigned i = 0; i < MemInits.size(); i++) {
5092     CXXCtorInitializer *Init = MemInits[i];
5093 
5094     // Set the source order index.
5095     Init->setSourceOrder(i);
5096 
5097     if (Init->isAnyMemberInitializer()) {
5098       const void *Key = GetKeyForMember(Context, Init);
5099       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5100           CheckRedundantUnionInit(*this, Init, MemberUnions))
5101         HadError = true;
5102     } else if (Init->isBaseInitializer()) {
5103       const void *Key = GetKeyForMember(Context, Init);
5104       if (CheckRedundantInit(*this, Init, Members[Key]))
5105         HadError = true;
5106     } else {
5107       assert(Init->isDelegatingInitializer());
5108       // This must be the only initializer
5109       if (MemInits.size() != 1) {
5110         Diag(Init->getSourceLocation(),
5111              diag::err_delegating_initializer_alone)
5112           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5113         // We will treat this as being the only initializer.
5114       }
5115       SetDelegatingInitializer(Constructor, MemInits[i]);
5116       // Return immediately as the initializer is set.
5117       return;
5118     }
5119   }
5120 
5121   if (HadError)
5122     return;
5123 
5124   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5125 
5126   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5127 
5128   DiagnoseUninitializedFields(*this, Constructor);
5129 }
5130 
5131 void
5132 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5133                                              CXXRecordDecl *ClassDecl) {
5134   // Ignore dependent contexts. Also ignore unions, since their members never
5135   // have destructors implicitly called.
5136   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5137     return;
5138 
5139   // FIXME: all the access-control diagnostics are positioned on the
5140   // field/base declaration.  That's probably good; that said, the
5141   // user might reasonably want to know why the destructor is being
5142   // emitted, and we currently don't say.
5143 
5144   // Non-static data members.
5145   for (auto *Field : ClassDecl->fields()) {
5146     if (Field->isInvalidDecl())
5147       continue;
5148 
5149     // Don't destroy incomplete or zero-length arrays.
5150     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5151       continue;
5152 
5153     QualType FieldType = Context.getBaseElementType(Field->getType());
5154 
5155     const RecordType* RT = FieldType->getAs<RecordType>();
5156     if (!RT)
5157       continue;
5158 
5159     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5160     if (FieldClassDecl->isInvalidDecl())
5161       continue;
5162     if (FieldClassDecl->hasIrrelevantDestructor())
5163       continue;
5164     // The destructor for an implicit anonymous union member is never invoked.
5165     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5166       continue;
5167 
5168     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5169     assert(Dtor && "No dtor found for FieldClassDecl!");
5170     CheckDestructorAccess(Field->getLocation(), Dtor,
5171                           PDiag(diag::err_access_dtor_field)
5172                             << Field->getDeclName()
5173                             << FieldType);
5174 
5175     MarkFunctionReferenced(Location, Dtor);
5176     DiagnoseUseOfDecl(Dtor, Location);
5177   }
5178 
5179   // We only potentially invoke the destructors of potentially constructed
5180   // subobjects.
5181   bool VisitVirtualBases = !ClassDecl->isAbstract();
5182 
5183   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5184 
5185   // Bases.
5186   for (const auto &Base : ClassDecl->bases()) {
5187     // Bases are always records in a well-formed non-dependent class.
5188     const RecordType *RT = Base.getType()->getAs<RecordType>();
5189 
5190     // Remember direct virtual bases.
5191     if (Base.isVirtual()) {
5192       if (!VisitVirtualBases)
5193         continue;
5194       DirectVirtualBases.insert(RT);
5195     }
5196 
5197     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5198     // If our base class is invalid, we probably can't get its dtor anyway.
5199     if (BaseClassDecl->isInvalidDecl())
5200       continue;
5201     if (BaseClassDecl->hasIrrelevantDestructor())
5202       continue;
5203 
5204     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5205     assert(Dtor && "No dtor found for BaseClassDecl!");
5206 
5207     // FIXME: caret should be on the start of the class name
5208     CheckDestructorAccess(Base.getLocStart(), Dtor,
5209                           PDiag(diag::err_access_dtor_base)
5210                             << Base.getType()
5211                             << Base.getSourceRange(),
5212                           Context.getTypeDeclType(ClassDecl));
5213 
5214     MarkFunctionReferenced(Location, Dtor);
5215     DiagnoseUseOfDecl(Dtor, Location);
5216   }
5217 
5218   if (!VisitVirtualBases)
5219     return;
5220 
5221   // Virtual bases.
5222   for (const auto &VBase : ClassDecl->vbases()) {
5223     // Bases are always records in a well-formed non-dependent class.
5224     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5225 
5226     // Ignore direct virtual bases.
5227     if (DirectVirtualBases.count(RT))
5228       continue;
5229 
5230     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5231     // If our base class is invalid, we probably can't get its dtor anyway.
5232     if (BaseClassDecl->isInvalidDecl())
5233       continue;
5234     if (BaseClassDecl->hasIrrelevantDestructor())
5235       continue;
5236 
5237     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5238     assert(Dtor && "No dtor found for BaseClassDecl!");
5239     if (CheckDestructorAccess(
5240             ClassDecl->getLocation(), Dtor,
5241             PDiag(diag::err_access_dtor_vbase)
5242                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5243             Context.getTypeDeclType(ClassDecl)) ==
5244         AR_accessible) {
5245       CheckDerivedToBaseConversion(
5246           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5247           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5248           SourceRange(), DeclarationName(), nullptr);
5249     }
5250 
5251     MarkFunctionReferenced(Location, Dtor);
5252     DiagnoseUseOfDecl(Dtor, Location);
5253   }
5254 }
5255 
5256 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5257   if (!CDtorDecl)
5258     return;
5259 
5260   if (CXXConstructorDecl *Constructor
5261       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5262     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5263     DiagnoseUninitializedFields(*this, Constructor);
5264   }
5265 }
5266 
5267 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5268   if (!getLangOpts().CPlusPlus)
5269     return false;
5270 
5271   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5272   if (!RD)
5273     return false;
5274 
5275   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5276   // class template specialization here, but doing so breaks a lot of code.
5277 
5278   // We can't answer whether something is abstract until it has a
5279   // definition. If it's currently being defined, we'll walk back
5280   // over all the declarations when we have a full definition.
5281   const CXXRecordDecl *Def = RD->getDefinition();
5282   if (!Def || Def->isBeingDefined())
5283     return false;
5284 
5285   return RD->isAbstract();
5286 }
5287 
5288 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5289                                   TypeDiagnoser &Diagnoser) {
5290   if (!isAbstractType(Loc, T))
5291     return false;
5292 
5293   T = Context.getBaseElementType(T);
5294   Diagnoser.diagnose(*this, Loc, T);
5295   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5296   return true;
5297 }
5298 
5299 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5300   // Check if we've already emitted the list of pure virtual functions
5301   // for this class.
5302   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5303     return;
5304 
5305   // If the diagnostic is suppressed, don't emit the notes. We're only
5306   // going to emit them once, so try to attach them to a diagnostic we're
5307   // actually going to show.
5308   if (Diags.isLastDiagnosticIgnored())
5309     return;
5310 
5311   CXXFinalOverriderMap FinalOverriders;
5312   RD->getFinalOverriders(FinalOverriders);
5313 
5314   // Keep a set of seen pure methods so we won't diagnose the same method
5315   // more than once.
5316   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5317 
5318   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5319                                    MEnd = FinalOverriders.end();
5320        M != MEnd;
5321        ++M) {
5322     for (OverridingMethods::iterator SO = M->second.begin(),
5323                                   SOEnd = M->second.end();
5324          SO != SOEnd; ++SO) {
5325       // C++ [class.abstract]p4:
5326       //   A class is abstract if it contains or inherits at least one
5327       //   pure virtual function for which the final overrider is pure
5328       //   virtual.
5329 
5330       //
5331       if (SO->second.size() != 1)
5332         continue;
5333 
5334       if (!SO->second.front().Method->isPure())
5335         continue;
5336 
5337       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5338         continue;
5339 
5340       Diag(SO->second.front().Method->getLocation(),
5341            diag::note_pure_virtual_function)
5342         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5343     }
5344   }
5345 
5346   if (!PureVirtualClassDiagSet)
5347     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5348   PureVirtualClassDiagSet->insert(RD);
5349 }
5350 
5351 namespace {
5352 struct AbstractUsageInfo {
5353   Sema &S;
5354   CXXRecordDecl *Record;
5355   CanQualType AbstractType;
5356   bool Invalid;
5357 
5358   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5359     : S(S), Record(Record),
5360       AbstractType(S.Context.getCanonicalType(
5361                    S.Context.getTypeDeclType(Record))),
5362       Invalid(false) {}
5363 
5364   void DiagnoseAbstractType() {
5365     if (Invalid) return;
5366     S.DiagnoseAbstractType(Record);
5367     Invalid = true;
5368   }
5369 
5370   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5371 };
5372 
5373 struct CheckAbstractUsage {
5374   AbstractUsageInfo &Info;
5375   const NamedDecl *Ctx;
5376 
5377   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5378     : Info(Info), Ctx(Ctx) {}
5379 
5380   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5381     switch (TL.getTypeLocClass()) {
5382 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5383 #define TYPELOC(CLASS, PARENT) \
5384     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5385 #include "clang/AST/TypeLocNodes.def"
5386     }
5387   }
5388 
5389   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5390     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5391     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5392       if (!TL.getParam(I))
5393         continue;
5394 
5395       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5396       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5397     }
5398   }
5399 
5400   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5401     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5402   }
5403 
5404   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5405     // Visit the type parameters from a permissive context.
5406     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5407       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5408       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5409         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5410           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5411       // TODO: other template argument types?
5412     }
5413   }
5414 
5415   // Visit pointee types from a permissive context.
5416 #define CheckPolymorphic(Type) \
5417   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5418     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5419   }
5420   CheckPolymorphic(PointerTypeLoc)
5421   CheckPolymorphic(ReferenceTypeLoc)
5422   CheckPolymorphic(MemberPointerTypeLoc)
5423   CheckPolymorphic(BlockPointerTypeLoc)
5424   CheckPolymorphic(AtomicTypeLoc)
5425 
5426   /// Handle all the types we haven't given a more specific
5427   /// implementation for above.
5428   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5429     // Every other kind of type that we haven't called out already
5430     // that has an inner type is either (1) sugar or (2) contains that
5431     // inner type in some way as a subobject.
5432     if (TypeLoc Next = TL.getNextTypeLoc())
5433       return Visit(Next, Sel);
5434 
5435     // If there's no inner type and we're in a permissive context,
5436     // don't diagnose.
5437     if (Sel == Sema::AbstractNone) return;
5438 
5439     // Check whether the type matches the abstract type.
5440     QualType T = TL.getType();
5441     if (T->isArrayType()) {
5442       Sel = Sema::AbstractArrayType;
5443       T = Info.S.Context.getBaseElementType(T);
5444     }
5445     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5446     if (CT != Info.AbstractType) return;
5447 
5448     // It matched; do some magic.
5449     if (Sel == Sema::AbstractArrayType) {
5450       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5451         << T << TL.getSourceRange();
5452     } else {
5453       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5454         << Sel << T << TL.getSourceRange();
5455     }
5456     Info.DiagnoseAbstractType();
5457   }
5458 };
5459 
5460 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5461                                   Sema::AbstractDiagSelID Sel) {
5462   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5463 }
5464 
5465 }
5466 
5467 /// Check for invalid uses of an abstract type in a method declaration.
5468 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5469                                     CXXMethodDecl *MD) {
5470   // No need to do the check on definitions, which require that
5471   // the return/param types be complete.
5472   if (MD->doesThisDeclarationHaveABody())
5473     return;
5474 
5475   // For safety's sake, just ignore it if we don't have type source
5476   // information.  This should never happen for non-implicit methods,
5477   // but...
5478   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5479     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5480 }
5481 
5482 /// Check for invalid uses of an abstract type within a class definition.
5483 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5484                                     CXXRecordDecl *RD) {
5485   for (auto *D : RD->decls()) {
5486     if (D->isImplicit()) continue;
5487 
5488     // Methods and method templates.
5489     if (isa<CXXMethodDecl>(D)) {
5490       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5491     } else if (isa<FunctionTemplateDecl>(D)) {
5492       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5493       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5494 
5495     // Fields and static variables.
5496     } else if (isa<FieldDecl>(D)) {
5497       FieldDecl *FD = cast<FieldDecl>(D);
5498       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5499         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5500     } else if (isa<VarDecl>(D)) {
5501       VarDecl *VD = cast<VarDecl>(D);
5502       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5503         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5504 
5505     // Nested classes and class templates.
5506     } else if (isa<CXXRecordDecl>(D)) {
5507       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5508     } else if (isa<ClassTemplateDecl>(D)) {
5509       CheckAbstractClassUsage(Info,
5510                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5511     }
5512   }
5513 }
5514 
5515 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5516   Attr *ClassAttr = getDLLAttr(Class);
5517   if (!ClassAttr)
5518     return;
5519 
5520   assert(ClassAttr->getKind() == attr::DLLExport);
5521 
5522   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5523 
5524   if (TSK == TSK_ExplicitInstantiationDeclaration)
5525     // Don't go any further if this is just an explicit instantiation
5526     // declaration.
5527     return;
5528 
5529   for (Decl *Member : Class->decls()) {
5530     // Defined static variables that are members of an exported base
5531     // class must be marked export too.
5532     auto *VD = dyn_cast<VarDecl>(Member);
5533     if (VD && Member->getAttr<DLLExportAttr>() &&
5534         VD->getStorageClass() == SC_Static &&
5535         TSK == TSK_ImplicitInstantiation)
5536       S.MarkVariableReferenced(VD->getLocation(), VD);
5537 
5538     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5539     if (!MD)
5540       continue;
5541 
5542     if (Member->getAttr<DLLExportAttr>()) {
5543       if (MD->isUserProvided()) {
5544         // Instantiate non-default class member functions ...
5545 
5546         // .. except for certain kinds of template specializations.
5547         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5548           continue;
5549 
5550         S.MarkFunctionReferenced(Class->getLocation(), MD);
5551 
5552         // The function will be passed to the consumer when its definition is
5553         // encountered.
5554       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5555                  MD->isCopyAssignmentOperator() ||
5556                  MD->isMoveAssignmentOperator()) {
5557         // Synthesize and instantiate non-trivial implicit methods, explicitly
5558         // defaulted methods, and the copy and move assignment operators. The
5559         // latter are exported even if they are trivial, because the address of
5560         // an operator can be taken and should compare equal across libraries.
5561         DiagnosticErrorTrap Trap(S.Diags);
5562         S.MarkFunctionReferenced(Class->getLocation(), MD);
5563         if (Trap.hasErrorOccurred()) {
5564           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5565               << Class << !S.getLangOpts().CPlusPlus11;
5566           break;
5567         }
5568 
5569         // There is no later point when we will see the definition of this
5570         // function, so pass it to the consumer now.
5571         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5572       }
5573     }
5574   }
5575 }
5576 
5577 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5578                                                         CXXRecordDecl *Class) {
5579   // Only the MS ABI has default constructor closures, so we don't need to do
5580   // this semantic checking anywhere else.
5581   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5582     return;
5583 
5584   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5585   for (Decl *Member : Class->decls()) {
5586     // Look for exported default constructors.
5587     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5588     if (!CD || !CD->isDefaultConstructor())
5589       continue;
5590     auto *Attr = CD->getAttr<DLLExportAttr>();
5591     if (!Attr)
5592       continue;
5593 
5594     // If the class is non-dependent, mark the default arguments as ODR-used so
5595     // that we can properly codegen the constructor closure.
5596     if (!Class->isDependentContext()) {
5597       for (ParmVarDecl *PD : CD->parameters()) {
5598         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5599         S.DiscardCleanupsInEvaluationContext();
5600       }
5601     }
5602 
5603     if (LastExportedDefaultCtor) {
5604       S.Diag(LastExportedDefaultCtor->getLocation(),
5605              diag::err_attribute_dll_ambiguous_default_ctor)
5606           << Class;
5607       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5608           << CD->getDeclName();
5609       return;
5610     }
5611     LastExportedDefaultCtor = CD;
5612   }
5613 }
5614 
5615 /// Check class-level dllimport/dllexport attribute.
5616 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5617   Attr *ClassAttr = getDLLAttr(Class);
5618 
5619   // MSVC inherits DLL attributes to partial class template specializations.
5620   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5621     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5622       if (Attr *TemplateAttr =
5623               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5624         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5625         A->setInherited(true);
5626         ClassAttr = A;
5627       }
5628     }
5629   }
5630 
5631   if (!ClassAttr)
5632     return;
5633 
5634   if (!Class->isExternallyVisible()) {
5635     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5636         << Class << ClassAttr;
5637     return;
5638   }
5639 
5640   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5641       !ClassAttr->isInherited()) {
5642     // Diagnose dll attributes on members of class with dll attribute.
5643     for (Decl *Member : Class->decls()) {
5644       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5645         continue;
5646       InheritableAttr *MemberAttr = getDLLAttr(Member);
5647       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5648         continue;
5649 
5650       Diag(MemberAttr->getLocation(),
5651              diag::err_attribute_dll_member_of_dll_class)
5652           << MemberAttr << ClassAttr;
5653       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5654       Member->setInvalidDecl();
5655     }
5656   }
5657 
5658   if (Class->getDescribedClassTemplate())
5659     // Don't inherit dll attribute until the template is instantiated.
5660     return;
5661 
5662   // The class is either imported or exported.
5663   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5664 
5665   // Check if this was a dllimport attribute propagated from a derived class to
5666   // a base class template specialization. We don't apply these attributes to
5667   // static data members.
5668   const bool PropagatedImport =
5669       !ClassExported &&
5670       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5671 
5672   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5673 
5674   // Ignore explicit dllexport on explicit class template instantiation declarations.
5675   if (ClassExported && !ClassAttr->isInherited() &&
5676       TSK == TSK_ExplicitInstantiationDeclaration) {
5677     Class->dropAttr<DLLExportAttr>();
5678     return;
5679   }
5680 
5681   // Force declaration of implicit members so they can inherit the attribute.
5682   ForceDeclarationOfImplicitMembers(Class);
5683 
5684   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5685   // seem to be true in practice?
5686 
5687   for (Decl *Member : Class->decls()) {
5688     VarDecl *VD = dyn_cast<VarDecl>(Member);
5689     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5690 
5691     // Only methods and static fields inherit the attributes.
5692     if (!VD && !MD)
5693       continue;
5694 
5695     if (MD) {
5696       // Don't process deleted methods.
5697       if (MD->isDeleted())
5698         continue;
5699 
5700       if (MD->isInlined()) {
5701         // MinGW does not import or export inline methods.
5702         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5703             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5704           continue;
5705 
5706         // MSVC versions before 2015 don't export the move assignment operators
5707         // and move constructor, so don't attempt to import/export them if
5708         // we have a definition.
5709         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5710         if ((MD->isMoveAssignmentOperator() ||
5711              (Ctor && Ctor->isMoveConstructor())) &&
5712             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5713           continue;
5714 
5715         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5716         // operator is exported anyway.
5717         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5718             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5719           continue;
5720       }
5721     }
5722 
5723     // Don't apply dllimport attributes to static data members of class template
5724     // instantiations when the attribute is propagated from a derived class.
5725     if (VD && PropagatedImport)
5726       continue;
5727 
5728     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5729       continue;
5730 
5731     if (!getDLLAttr(Member)) {
5732       auto *NewAttr =
5733           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5734       NewAttr->setInherited(true);
5735       Member->addAttr(NewAttr);
5736 
5737       if (MD) {
5738         // Propagate DLLAttr to friend re-declarations of MD that have already
5739         // been constructed.
5740         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5741              FD = FD->getPreviousDecl()) {
5742           if (FD->getFriendObjectKind() == Decl::FOK_None)
5743             continue;
5744           assert(!getDLLAttr(FD) &&
5745                  "friend re-decl should not already have a DLLAttr");
5746           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5747           NewAttr->setInherited(true);
5748           FD->addAttr(NewAttr);
5749         }
5750       }
5751     }
5752   }
5753 
5754   if (ClassExported)
5755     DelayedDllExportClasses.push_back(Class);
5756 }
5757 
5758 /// Perform propagation of DLL attributes from a derived class to a
5759 /// templated base class for MS compatibility.
5760 void Sema::propagateDLLAttrToBaseClassTemplate(
5761     CXXRecordDecl *Class, Attr *ClassAttr,
5762     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5763   if (getDLLAttr(
5764           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5765     // If the base class template has a DLL attribute, don't try to change it.
5766     return;
5767   }
5768 
5769   auto TSK = BaseTemplateSpec->getSpecializationKind();
5770   if (!getDLLAttr(BaseTemplateSpec) &&
5771       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5772        TSK == TSK_ImplicitInstantiation)) {
5773     // The template hasn't been instantiated yet (or it has, but only as an
5774     // explicit instantiation declaration or implicit instantiation, which means
5775     // we haven't codegenned any members yet), so propagate the attribute.
5776     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5777     NewAttr->setInherited(true);
5778     BaseTemplateSpec->addAttr(NewAttr);
5779 
5780     // If this was an import, mark that we propagated it from a derived class to
5781     // a base class template specialization.
5782     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5783       ImportAttr->setPropagatedToBaseTemplate();
5784 
5785     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5786     // needs to be run again to work see the new attribute. Otherwise this will
5787     // get run whenever the template is instantiated.
5788     if (TSK != TSK_Undeclared)
5789       checkClassLevelDLLAttribute(BaseTemplateSpec);
5790 
5791     return;
5792   }
5793 
5794   if (getDLLAttr(BaseTemplateSpec)) {
5795     // The template has already been specialized or instantiated with an
5796     // attribute, explicitly or through propagation. We should not try to change
5797     // it.
5798     return;
5799   }
5800 
5801   // The template was previously instantiated or explicitly specialized without
5802   // a dll attribute, It's too late for us to add an attribute, so warn that
5803   // this is unsupported.
5804   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5805       << BaseTemplateSpec->isExplicitSpecialization();
5806   Diag(ClassAttr->getLocation(), diag::note_attribute);
5807   if (BaseTemplateSpec->isExplicitSpecialization()) {
5808     Diag(BaseTemplateSpec->getLocation(),
5809            diag::note_template_class_explicit_specialization_was_here)
5810         << BaseTemplateSpec;
5811   } else {
5812     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5813            diag::note_template_class_instantiation_was_here)
5814         << BaseTemplateSpec;
5815   }
5816 }
5817 
5818 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5819                                         SourceLocation DefaultLoc) {
5820   switch (S.getSpecialMember(MD)) {
5821   case Sema::CXXDefaultConstructor:
5822     S.DefineImplicitDefaultConstructor(DefaultLoc,
5823                                        cast<CXXConstructorDecl>(MD));
5824     break;
5825   case Sema::CXXCopyConstructor:
5826     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5827     break;
5828   case Sema::CXXCopyAssignment:
5829     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5830     break;
5831   case Sema::CXXDestructor:
5832     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5833     break;
5834   case Sema::CXXMoveConstructor:
5835     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5836     break;
5837   case Sema::CXXMoveAssignment:
5838     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5839     break;
5840   case Sema::CXXInvalid:
5841     llvm_unreachable("Invalid special member.");
5842   }
5843 }
5844 
5845 /// Determine whether a type is permitted to be passed or returned in
5846 /// registers, per C++ [class.temporary]p3.
5847 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5848                                TargetInfo::CallingConvKind CCK) {
5849   if (D->isDependentType() || D->isInvalidDecl())
5850     return false;
5851 
5852   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5853   // The PS4 platform ABI follows the behavior of Clang 3.2.
5854   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5855     return !D->hasNonTrivialDestructorForCall() &&
5856            !D->hasNonTrivialCopyConstructorForCall();
5857 
5858   if (CCK == TargetInfo::CCK_MicrosoftX86_64) {
5859     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5860     bool DtorIsTrivialForCall = false;
5861 
5862     // If a class has at least one non-deleted, trivial copy constructor, it
5863     // is passed according to the C ABI. Otherwise, it is passed indirectly.
5864     //
5865     // Note: This permits classes with non-trivial copy or move ctors to be
5866     // passed in registers, so long as they *also* have a trivial copy ctor,
5867     // which is non-conforming.
5868     if (D->needsImplicitCopyConstructor()) {
5869       if (!D->defaultedCopyConstructorIsDeleted()) {
5870         if (D->hasTrivialCopyConstructor())
5871           CopyCtorIsTrivial = true;
5872         if (D->hasTrivialCopyConstructorForCall())
5873           CopyCtorIsTrivialForCall = true;
5874       }
5875     } else {
5876       for (const CXXConstructorDecl *CD : D->ctors()) {
5877         if (CD->isCopyConstructor() && !CD->isDeleted()) {
5878           if (CD->isTrivial())
5879             CopyCtorIsTrivial = true;
5880           if (CD->isTrivialForCall())
5881             CopyCtorIsTrivialForCall = true;
5882         }
5883       }
5884     }
5885 
5886     if (D->needsImplicitDestructor()) {
5887       if (!D->defaultedDestructorIsDeleted() &&
5888           D->hasTrivialDestructorForCall())
5889         DtorIsTrivialForCall = true;
5890     } else if (const auto *DD = D->getDestructor()) {
5891       if (!DD->isDeleted() && DD->isTrivialForCall())
5892         DtorIsTrivialForCall = true;
5893     }
5894 
5895     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5896     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5897       return true;
5898 
5899     // If a class has a destructor, we'd really like to pass it indirectly
5900     // because it allows us to elide copies.  Unfortunately, MSVC makes that
5901     // impossible for small types, which it will pass in a single register or
5902     // stack slot. Most objects with dtors are large-ish, so handle that early.
5903     // We can't call out all large objects as being indirect because there are
5904     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5905     // how we pass large POD types.
5906 
5907     // Note: This permits small classes with nontrivial destructors to be
5908     // passed in registers, which is non-conforming.
5909     if (CopyCtorIsTrivial &&
5910         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5911       return true;
5912     return false;
5913   }
5914 
5915   // Per C++ [class.temporary]p3, the relevant condition is:
5916   //   each copy constructor, move constructor, and destructor of X is
5917   //   either trivial or deleted, and X has at least one non-deleted copy
5918   //   or move constructor
5919   bool HasNonDeletedCopyOrMove = false;
5920 
5921   if (D->needsImplicitCopyConstructor() &&
5922       !D->defaultedCopyConstructorIsDeleted()) {
5923     if (!D->hasTrivialCopyConstructorForCall())
5924       return false;
5925     HasNonDeletedCopyOrMove = true;
5926   }
5927 
5928   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5929       !D->defaultedMoveConstructorIsDeleted()) {
5930     if (!D->hasTrivialMoveConstructorForCall())
5931       return false;
5932     HasNonDeletedCopyOrMove = true;
5933   }
5934 
5935   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5936       !D->hasTrivialDestructorForCall())
5937     return false;
5938 
5939   for (const CXXMethodDecl *MD : D->methods()) {
5940     if (MD->isDeleted())
5941       continue;
5942 
5943     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5944     if (CD && CD->isCopyOrMoveConstructor())
5945       HasNonDeletedCopyOrMove = true;
5946     else if (!isa<CXXDestructorDecl>(MD))
5947       continue;
5948 
5949     if (!MD->isTrivialForCall())
5950       return false;
5951   }
5952 
5953   return HasNonDeletedCopyOrMove;
5954 }
5955 
5956 /// Perform semantic checks on a class definition that has been
5957 /// completing, introducing implicitly-declared members, checking for
5958 /// abstract types, etc.
5959 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5960   if (!Record)
5961     return;
5962 
5963   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5964     AbstractUsageInfo Info(*this, Record);
5965     CheckAbstractClassUsage(Info, Record);
5966   }
5967 
5968   // If this is not an aggregate type and has no user-declared constructor,
5969   // complain about any non-static data members of reference or const scalar
5970   // type, since they will never get initializers.
5971   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5972       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5973       !Record->isLambda()) {
5974     bool Complained = false;
5975     for (const auto *F : Record->fields()) {
5976       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5977         continue;
5978 
5979       if (F->getType()->isReferenceType() ||
5980           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5981         if (!Complained) {
5982           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5983             << Record->getTagKind() << Record;
5984           Complained = true;
5985         }
5986 
5987         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5988           << F->getType()->isReferenceType()
5989           << F->getDeclName();
5990       }
5991     }
5992   }
5993 
5994   if (Record->getIdentifier()) {
5995     // C++ [class.mem]p13:
5996     //   If T is the name of a class, then each of the following shall have a
5997     //   name different from T:
5998     //     - every member of every anonymous union that is a member of class T.
5999     //
6000     // C++ [class.mem]p14:
6001     //   In addition, if class T has a user-declared constructor (12.1), every
6002     //   non-static data member of class T shall have a name different from T.
6003     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6004     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6005          ++I) {
6006       NamedDecl *D = (*I)->getUnderlyingDecl();
6007       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6008            Record->hasUserDeclaredConstructor()) ||
6009           isa<IndirectFieldDecl>(D)) {
6010         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6011           << D->getDeclName();
6012         break;
6013       }
6014     }
6015   }
6016 
6017   // Warn if the class has virtual methods but non-virtual public destructor.
6018   if (Record->isPolymorphic() && !Record->isDependentType()) {
6019     CXXDestructorDecl *dtor = Record->getDestructor();
6020     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6021         !Record->hasAttr<FinalAttr>())
6022       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6023            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6024   }
6025 
6026   if (Record->isAbstract()) {
6027     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6028       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6029         << FA->isSpelledAsSealed();
6030       DiagnoseAbstractType(Record);
6031     }
6032   }
6033 
6034   // See if trivial_abi has to be dropped.
6035   if (Record->hasAttr<TrivialABIAttr>())
6036     checkIllFormedTrivialABIStruct(*Record);
6037 
6038   // Set HasTrivialSpecialMemberForCall if the record has attribute
6039   // "trivial_abi".
6040   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6041 
6042   if (HasTrivialABI)
6043     Record->setHasTrivialSpecialMemberForCall();
6044 
6045   bool HasMethodWithOverrideControl = false,
6046        HasOverridingMethodWithoutOverrideControl = false;
6047   if (!Record->isDependentType()) {
6048     for (auto *M : Record->methods()) {
6049       // See if a method overloads virtual methods in a base
6050       // class without overriding any.
6051       if (!M->isStatic())
6052         DiagnoseHiddenVirtualMethods(M);
6053       if (M->hasAttr<OverrideAttr>())
6054         HasMethodWithOverrideControl = true;
6055       else if (M->size_overridden_methods() > 0)
6056         HasOverridingMethodWithoutOverrideControl = true;
6057       // Check whether the explicitly-defaulted special members are valid.
6058       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6059         CheckExplicitlyDefaultedSpecialMember(M);
6060 
6061       // For an explicitly defaulted or deleted special member, we defer
6062       // determining triviality until the class is complete. That time is now!
6063       CXXSpecialMember CSM = getSpecialMember(M);
6064       if (!M->isImplicit() && !M->isUserProvided()) {
6065         if (CSM != CXXInvalid) {
6066           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6067           // Inform the class that we've finished declaring this member.
6068           Record->finishedDefaultedOrDeletedMember(M);
6069           M->setTrivialForCall(
6070               HasTrivialABI ||
6071               SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6072           Record->setTrivialForCallFlags(M);
6073         }
6074       }
6075 
6076       // Set triviality for the purpose of calls if this is a user-provided
6077       // copy/move constructor or destructor.
6078       if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6079            CSM == CXXDestructor) && M->isUserProvided()) {
6080         M->setTrivialForCall(HasTrivialABI);
6081         Record->setTrivialForCallFlags(M);
6082       }
6083 
6084       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6085           M->hasAttr<DLLExportAttr>()) {
6086         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6087             M->isTrivial() &&
6088             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6089              CSM == CXXDestructor))
6090           M->dropAttr<DLLExportAttr>();
6091 
6092         if (M->hasAttr<DLLExportAttr>()) {
6093           DefineImplicitSpecialMember(*this, M, M->getLocation());
6094           ActOnFinishInlineFunctionDef(M);
6095         }
6096       }
6097     }
6098   }
6099 
6100   if (HasMethodWithOverrideControl &&
6101       HasOverridingMethodWithoutOverrideControl) {
6102     // At least one method has the 'override' control declared.
6103     // Diagnose all other overridden methods which do not have 'override' specified on them.
6104     for (auto *M : Record->methods())
6105       DiagnoseAbsenceOfOverrideControl(M);
6106   }
6107 
6108   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6109   // whether this class uses any C++ features that are implemented
6110   // completely differently in MSVC, and if so, emit a diagnostic.
6111   // That diagnostic defaults to an error, but we allow projects to
6112   // map it down to a warning (or ignore it).  It's a fairly common
6113   // practice among users of the ms_struct pragma to mass-annotate
6114   // headers, sweeping up a bunch of types that the project doesn't
6115   // really rely on MSVC-compatible layout for.  We must therefore
6116   // support "ms_struct except for C++ stuff" as a secondary ABI.
6117   if (Record->isMsStruct(Context) &&
6118       (Record->isPolymorphic() || Record->getNumBases())) {
6119     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6120   }
6121 
6122   checkClassLevelDLLAttribute(Record);
6123 
6124   bool ClangABICompat4 =
6125       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6126   TargetInfo::CallingConvKind CCK =
6127       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6128   bool CanPass = canPassInRegisters(*this, Record, CCK);
6129 
6130   // Do not change ArgPassingRestrictions if it has already been set to
6131   // APK_CanNeverPassInRegs.
6132   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6133     Record->setArgPassingRestrictions(CanPass
6134                                           ? RecordDecl::APK_CanPassInRegs
6135                                           : RecordDecl::APK_CannotPassInRegs);
6136 
6137   // If canPassInRegisters returns true despite the record having a non-trivial
6138   // destructor, the record is destructed in the callee. This happens only when
6139   // the record or one of its subobjects has a field annotated with trivial_abi
6140   // or a field qualified with ObjC __strong/__weak.
6141   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6142     Record->setParamDestroyedInCallee(true);
6143   else if (Record->hasNonTrivialDestructor())
6144     Record->setParamDestroyedInCallee(CanPass);
6145 
6146   if (getLangOpts().ForceEmitVTables) {
6147     // If we want to emit all the vtables, we need to mark it as used.  This
6148     // is especially required for cases like vtable assumption loads.
6149     MarkVTableUsed(Record->getInnerLocStart(), Record);
6150   }
6151 }
6152 
6153 /// Look up the special member function that would be called by a special
6154 /// member function for a subobject of class type.
6155 ///
6156 /// \param Class The class type of the subobject.
6157 /// \param CSM The kind of special member function.
6158 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6159 /// \param ConstRHS True if this is a copy operation with a const object
6160 ///        on its RHS, that is, if the argument to the outer special member
6161 ///        function is 'const' and this is not a field marked 'mutable'.
6162 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6163     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6164     unsigned FieldQuals, bool ConstRHS) {
6165   unsigned LHSQuals = 0;
6166   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6167     LHSQuals = FieldQuals;
6168 
6169   unsigned RHSQuals = FieldQuals;
6170   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6171     RHSQuals = 0;
6172   else if (ConstRHS)
6173     RHSQuals |= Qualifiers::Const;
6174 
6175   return S.LookupSpecialMember(Class, CSM,
6176                                RHSQuals & Qualifiers::Const,
6177                                RHSQuals & Qualifiers::Volatile,
6178                                false,
6179                                LHSQuals & Qualifiers::Const,
6180                                LHSQuals & Qualifiers::Volatile);
6181 }
6182 
6183 class Sema::InheritedConstructorInfo {
6184   Sema &S;
6185   SourceLocation UseLoc;
6186 
6187   /// A mapping from the base classes through which the constructor was
6188   /// inherited to the using shadow declaration in that base class (or a null
6189   /// pointer if the constructor was declared in that base class).
6190   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6191       InheritedFromBases;
6192 
6193 public:
6194   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6195                            ConstructorUsingShadowDecl *Shadow)
6196       : S(S), UseLoc(UseLoc) {
6197     bool DiagnosedMultipleConstructedBases = false;
6198     CXXRecordDecl *ConstructedBase = nullptr;
6199     UsingDecl *ConstructedBaseUsing = nullptr;
6200 
6201     // Find the set of such base class subobjects and check that there's a
6202     // unique constructed subobject.
6203     for (auto *D : Shadow->redecls()) {
6204       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6205       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6206       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6207 
6208       InheritedFromBases.insert(
6209           std::make_pair(DNominatedBase->getCanonicalDecl(),
6210                          DShadow->getNominatedBaseClassShadowDecl()));
6211       if (DShadow->constructsVirtualBase())
6212         InheritedFromBases.insert(
6213             std::make_pair(DConstructedBase->getCanonicalDecl(),
6214                            DShadow->getConstructedBaseClassShadowDecl()));
6215       else
6216         assert(DNominatedBase == DConstructedBase);
6217 
6218       // [class.inhctor.init]p2:
6219       //   If the constructor was inherited from multiple base class subobjects
6220       //   of type B, the program is ill-formed.
6221       if (!ConstructedBase) {
6222         ConstructedBase = DConstructedBase;
6223         ConstructedBaseUsing = D->getUsingDecl();
6224       } else if (ConstructedBase != DConstructedBase &&
6225                  !Shadow->isInvalidDecl()) {
6226         if (!DiagnosedMultipleConstructedBases) {
6227           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6228               << Shadow->getTargetDecl();
6229           S.Diag(ConstructedBaseUsing->getLocation(),
6230                diag::note_ambiguous_inherited_constructor_using)
6231               << ConstructedBase;
6232           DiagnosedMultipleConstructedBases = true;
6233         }
6234         S.Diag(D->getUsingDecl()->getLocation(),
6235                diag::note_ambiguous_inherited_constructor_using)
6236             << DConstructedBase;
6237       }
6238     }
6239 
6240     if (DiagnosedMultipleConstructedBases)
6241       Shadow->setInvalidDecl();
6242   }
6243 
6244   /// Find the constructor to use for inherited construction of a base class,
6245   /// and whether that base class constructor inherits the constructor from a
6246   /// virtual base class (in which case it won't actually invoke it).
6247   std::pair<CXXConstructorDecl *, bool>
6248   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6249     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6250     if (It == InheritedFromBases.end())
6251       return std::make_pair(nullptr, false);
6252 
6253     // This is an intermediary class.
6254     if (It->second)
6255       return std::make_pair(
6256           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6257           It->second->constructsVirtualBase());
6258 
6259     // This is the base class from which the constructor was inherited.
6260     return std::make_pair(Ctor, false);
6261   }
6262 };
6263 
6264 /// Is the special member function which would be selected to perform the
6265 /// specified operation on the specified class type a constexpr constructor?
6266 static bool
6267 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6268                          Sema::CXXSpecialMember CSM, unsigned Quals,
6269                          bool ConstRHS,
6270                          CXXConstructorDecl *InheritedCtor = nullptr,
6271                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6272   // If we're inheriting a constructor, see if we need to call it for this base
6273   // class.
6274   if (InheritedCtor) {
6275     assert(CSM == Sema::CXXDefaultConstructor);
6276     auto BaseCtor =
6277         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6278     if (BaseCtor)
6279       return BaseCtor->isConstexpr();
6280   }
6281 
6282   if (CSM == Sema::CXXDefaultConstructor)
6283     return ClassDecl->hasConstexprDefaultConstructor();
6284 
6285   Sema::SpecialMemberOverloadResult SMOR =
6286       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6287   if (!SMOR.getMethod())
6288     // A constructor we wouldn't select can't be "involved in initializing"
6289     // anything.
6290     return true;
6291   return SMOR.getMethod()->isConstexpr();
6292 }
6293 
6294 /// Determine whether the specified special member function would be constexpr
6295 /// if it were implicitly defined.
6296 static bool defaultedSpecialMemberIsConstexpr(
6297     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6298     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6299     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6300   if (!S.getLangOpts().CPlusPlus11)
6301     return false;
6302 
6303   // C++11 [dcl.constexpr]p4:
6304   // In the definition of a constexpr constructor [...]
6305   bool Ctor = true;
6306   switch (CSM) {
6307   case Sema::CXXDefaultConstructor:
6308     if (Inherited)
6309       break;
6310     // Since default constructor lookup is essentially trivial (and cannot
6311     // involve, for instance, template instantiation), we compute whether a
6312     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6313     //
6314     // This is important for performance; we need to know whether the default
6315     // constructor is constexpr to determine whether the type is a literal type.
6316     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6317 
6318   case Sema::CXXCopyConstructor:
6319   case Sema::CXXMoveConstructor:
6320     // For copy or move constructors, we need to perform overload resolution.
6321     break;
6322 
6323   case Sema::CXXCopyAssignment:
6324   case Sema::CXXMoveAssignment:
6325     if (!S.getLangOpts().CPlusPlus14)
6326       return false;
6327     // In C++1y, we need to perform overload resolution.
6328     Ctor = false;
6329     break;
6330 
6331   case Sema::CXXDestructor:
6332   case Sema::CXXInvalid:
6333     return false;
6334   }
6335 
6336   //   -- if the class is a non-empty union, or for each non-empty anonymous
6337   //      union member of a non-union class, exactly one non-static data member
6338   //      shall be initialized; [DR1359]
6339   //
6340   // If we squint, this is guaranteed, since exactly one non-static data member
6341   // will be initialized (if the constructor isn't deleted), we just don't know
6342   // which one.
6343   if (Ctor && ClassDecl->isUnion())
6344     return CSM == Sema::CXXDefaultConstructor
6345                ? ClassDecl->hasInClassInitializer() ||
6346                      !ClassDecl->hasVariantMembers()
6347                : true;
6348 
6349   //   -- the class shall not have any virtual base classes;
6350   if (Ctor && ClassDecl->getNumVBases())
6351     return false;
6352 
6353   // C++1y [class.copy]p26:
6354   //   -- [the class] is a literal type, and
6355   if (!Ctor && !ClassDecl->isLiteral())
6356     return false;
6357 
6358   //   -- every constructor involved in initializing [...] base class
6359   //      sub-objects shall be a constexpr constructor;
6360   //   -- the assignment operator selected to copy/move each direct base
6361   //      class is a constexpr function, and
6362   for (const auto &B : ClassDecl->bases()) {
6363     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6364     if (!BaseType) continue;
6365 
6366     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6367     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6368                                   InheritedCtor, Inherited))
6369       return false;
6370   }
6371 
6372   //   -- every constructor involved in initializing non-static data members
6373   //      [...] shall be a constexpr constructor;
6374   //   -- every non-static data member and base class sub-object shall be
6375   //      initialized
6376   //   -- for each non-static data member of X that is of class type (or array
6377   //      thereof), the assignment operator selected to copy/move that member is
6378   //      a constexpr function
6379   for (const auto *F : ClassDecl->fields()) {
6380     if (F->isInvalidDecl())
6381       continue;
6382     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6383       continue;
6384     QualType BaseType = S.Context.getBaseElementType(F->getType());
6385     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6386       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6387       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6388                                     BaseType.getCVRQualifiers(),
6389                                     ConstArg && !F->isMutable()))
6390         return false;
6391     } else if (CSM == Sema::CXXDefaultConstructor) {
6392       return false;
6393     }
6394   }
6395 
6396   // All OK, it's constexpr!
6397   return true;
6398 }
6399 
6400 static Sema::ImplicitExceptionSpecification
6401 ComputeDefaultedSpecialMemberExceptionSpec(
6402     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6403     Sema::InheritedConstructorInfo *ICI);
6404 
6405 static Sema::ImplicitExceptionSpecification
6406 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6407   auto CSM = S.getSpecialMember(MD);
6408   if (CSM != Sema::CXXInvalid)
6409     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6410 
6411   auto *CD = cast<CXXConstructorDecl>(MD);
6412   assert(CD->getInheritedConstructor() &&
6413          "only special members have implicit exception specs");
6414   Sema::InheritedConstructorInfo ICI(
6415       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6416   return ComputeDefaultedSpecialMemberExceptionSpec(
6417       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6418 }
6419 
6420 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6421                                                             CXXMethodDecl *MD) {
6422   FunctionProtoType::ExtProtoInfo EPI;
6423 
6424   // Build an exception specification pointing back at this member.
6425   EPI.ExceptionSpec.Type = EST_Unevaluated;
6426   EPI.ExceptionSpec.SourceDecl = MD;
6427 
6428   // Set the calling convention to the default for C++ instance methods.
6429   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6430       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6431                                             /*IsCXXMethod=*/true));
6432   return EPI;
6433 }
6434 
6435 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6436   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6437   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6438     return;
6439 
6440   // Evaluate the exception specification.
6441   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6442   auto ESI = IES.getExceptionSpec();
6443 
6444   // Update the type of the special member to use it.
6445   UpdateExceptionSpec(MD, ESI);
6446 
6447   // A user-provided destructor can be defined outside the class. When that
6448   // happens, be sure to update the exception specification on both
6449   // declarations.
6450   const FunctionProtoType *CanonicalFPT =
6451     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6452   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6453     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6454 }
6455 
6456 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6457   CXXRecordDecl *RD = MD->getParent();
6458   CXXSpecialMember CSM = getSpecialMember(MD);
6459 
6460   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6461          "not an explicitly-defaulted special member");
6462 
6463   // Whether this was the first-declared instance of the constructor.
6464   // This affects whether we implicitly add an exception spec and constexpr.
6465   bool First = MD == MD->getCanonicalDecl();
6466 
6467   bool HadError = false;
6468 
6469   // C++11 [dcl.fct.def.default]p1:
6470   //   A function that is explicitly defaulted shall
6471   //     -- be a special member function (checked elsewhere),
6472   //     -- have the same type (except for ref-qualifiers, and except that a
6473   //        copy operation can take a non-const reference) as an implicit
6474   //        declaration, and
6475   //     -- not have default arguments.
6476   unsigned ExpectedParams = 1;
6477   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6478     ExpectedParams = 0;
6479   if (MD->getNumParams() != ExpectedParams) {
6480     // This also checks for default arguments: a copy or move constructor with a
6481     // default argument is classified as a default constructor, and assignment
6482     // operations and destructors can't have default arguments.
6483     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6484       << CSM << MD->getSourceRange();
6485     HadError = true;
6486   } else if (MD->isVariadic()) {
6487     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6488       << CSM << MD->getSourceRange();
6489     HadError = true;
6490   }
6491 
6492   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6493 
6494   bool CanHaveConstParam = false;
6495   if (CSM == CXXCopyConstructor)
6496     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6497   else if (CSM == CXXCopyAssignment)
6498     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6499 
6500   QualType ReturnType = Context.VoidTy;
6501   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6502     // Check for return type matching.
6503     ReturnType = Type->getReturnType();
6504     QualType ExpectedReturnType =
6505         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6506     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6507       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6508         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6509       HadError = true;
6510     }
6511 
6512     // A defaulted special member cannot have cv-qualifiers.
6513     if (Type->getTypeQuals()) {
6514       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6515         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6516       HadError = true;
6517     }
6518   }
6519 
6520   // Check for parameter type matching.
6521   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6522   bool HasConstParam = false;
6523   if (ExpectedParams && ArgType->isReferenceType()) {
6524     // Argument must be reference to possibly-const T.
6525     QualType ReferentType = ArgType->getPointeeType();
6526     HasConstParam = ReferentType.isConstQualified();
6527 
6528     if (ReferentType.isVolatileQualified()) {
6529       Diag(MD->getLocation(),
6530            diag::err_defaulted_special_member_volatile_param) << CSM;
6531       HadError = true;
6532     }
6533 
6534     if (HasConstParam && !CanHaveConstParam) {
6535       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6536         Diag(MD->getLocation(),
6537              diag::err_defaulted_special_member_copy_const_param)
6538           << (CSM == CXXCopyAssignment);
6539         // FIXME: Explain why this special member can't be const.
6540       } else {
6541         Diag(MD->getLocation(),
6542              diag::err_defaulted_special_member_move_const_param)
6543           << (CSM == CXXMoveAssignment);
6544       }
6545       HadError = true;
6546     }
6547   } else if (ExpectedParams) {
6548     // A copy assignment operator can take its argument by value, but a
6549     // defaulted one cannot.
6550     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6551     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6552     HadError = true;
6553   }
6554 
6555   // C++11 [dcl.fct.def.default]p2:
6556   //   An explicitly-defaulted function may be declared constexpr only if it
6557   //   would have been implicitly declared as constexpr,
6558   // Do not apply this rule to members of class templates, since core issue 1358
6559   // makes such functions always instantiate to constexpr functions. For
6560   // functions which cannot be constexpr (for non-constructors in C++11 and for
6561   // destructors in C++1y), this is checked elsewhere.
6562   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6563                                                      HasConstParam);
6564   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6565                                  : isa<CXXConstructorDecl>(MD)) &&
6566       MD->isConstexpr() && !Constexpr &&
6567       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6568     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6569     // FIXME: Explain why the special member can't be constexpr.
6570     HadError = true;
6571   }
6572 
6573   //   and may have an explicit exception-specification only if it is compatible
6574   //   with the exception-specification on the implicit declaration.
6575   if (Type->hasExceptionSpec()) {
6576     // Delay the check if this is the first declaration of the special member,
6577     // since we may not have parsed some necessary in-class initializers yet.
6578     if (First) {
6579       // If the exception specification needs to be instantiated, do so now,
6580       // before we clobber it with an EST_Unevaluated specification below.
6581       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6582         InstantiateExceptionSpec(MD->getLocStart(), MD);
6583         Type = MD->getType()->getAs<FunctionProtoType>();
6584       }
6585       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6586     } else
6587       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6588   }
6589 
6590   //   If a function is explicitly defaulted on its first declaration,
6591   if (First) {
6592     //  -- it is implicitly considered to be constexpr if the implicit
6593     //     definition would be,
6594     MD->setConstexpr(Constexpr);
6595 
6596     //  -- it is implicitly considered to have the same exception-specification
6597     //     as if it had been implicitly declared,
6598     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6599     EPI.ExceptionSpec.Type = EST_Unevaluated;
6600     EPI.ExceptionSpec.SourceDecl = MD;
6601     MD->setType(Context.getFunctionType(ReturnType,
6602                                         llvm::makeArrayRef(&ArgType,
6603                                                            ExpectedParams),
6604                                         EPI));
6605   }
6606 
6607   if (ShouldDeleteSpecialMember(MD, CSM)) {
6608     if (First) {
6609       SetDeclDeleted(MD, MD->getLocation());
6610     } else {
6611       // C++11 [dcl.fct.def.default]p4:
6612       //   [For a] user-provided explicitly-defaulted function [...] if such a
6613       //   function is implicitly defined as deleted, the program is ill-formed.
6614       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6615       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6616       HadError = true;
6617     }
6618   }
6619 
6620   if (HadError)
6621     MD->setInvalidDecl();
6622 }
6623 
6624 /// Check whether the exception specification provided for an
6625 /// explicitly-defaulted special member matches the exception specification
6626 /// that would have been generated for an implicit special member, per
6627 /// C++11 [dcl.fct.def.default]p2.
6628 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6629     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6630   // If the exception specification was explicitly specified but hadn't been
6631   // parsed when the method was defaulted, grab it now.
6632   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6633     SpecifiedType =
6634         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6635 
6636   // Compute the implicit exception specification.
6637   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6638                                                        /*IsCXXMethod=*/true);
6639   FunctionProtoType::ExtProtoInfo EPI(CC);
6640   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6641   EPI.ExceptionSpec = IES.getExceptionSpec();
6642   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6643     Context.getFunctionType(Context.VoidTy, None, EPI));
6644 
6645   // Ensure that it matches.
6646   CheckEquivalentExceptionSpec(
6647     PDiag(diag::err_incorrect_defaulted_exception_spec)
6648       << getSpecialMember(MD), PDiag(),
6649     ImplicitType, SourceLocation(),
6650     SpecifiedType, MD->getLocation());
6651 }
6652 
6653 void Sema::CheckDelayedMemberExceptionSpecs() {
6654   decltype(DelayedExceptionSpecChecks) Checks;
6655   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6656 
6657   std::swap(Checks, DelayedExceptionSpecChecks);
6658   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6659 
6660   // Perform any deferred checking of exception specifications for virtual
6661   // destructors.
6662   for (auto &Check : Checks)
6663     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6664 
6665   // Check that any explicitly-defaulted methods have exception specifications
6666   // compatible with their implicit exception specifications.
6667   for (auto &Spec : Specs)
6668     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6669 }
6670 
6671 namespace {
6672 /// CRTP base class for visiting operations performed by a special member
6673 /// function (or inherited constructor).
6674 template<typename Derived>
6675 struct SpecialMemberVisitor {
6676   Sema &S;
6677   CXXMethodDecl *MD;
6678   Sema::CXXSpecialMember CSM;
6679   Sema::InheritedConstructorInfo *ICI;
6680 
6681   // Properties of the special member, computed for convenience.
6682   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6683 
6684   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6685                        Sema::InheritedConstructorInfo *ICI)
6686       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6687     switch (CSM) {
6688     case Sema::CXXDefaultConstructor:
6689     case Sema::CXXCopyConstructor:
6690     case Sema::CXXMoveConstructor:
6691       IsConstructor = true;
6692       break;
6693     case Sema::CXXCopyAssignment:
6694     case Sema::CXXMoveAssignment:
6695       IsAssignment = true;
6696       break;
6697     case Sema::CXXDestructor:
6698       break;
6699     case Sema::CXXInvalid:
6700       llvm_unreachable("invalid special member kind");
6701     }
6702 
6703     if (MD->getNumParams()) {
6704       if (const ReferenceType *RT =
6705               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6706         ConstArg = RT->getPointeeType().isConstQualified();
6707     }
6708   }
6709 
6710   Derived &getDerived() { return static_cast<Derived&>(*this); }
6711 
6712   /// Is this a "move" special member?
6713   bool isMove() const {
6714     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6715   }
6716 
6717   /// Look up the corresponding special member in the given class.
6718   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6719                                              unsigned Quals, bool IsMutable) {
6720     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6721                                        ConstArg && !IsMutable);
6722   }
6723 
6724   /// Look up the constructor for the specified base class to see if it's
6725   /// overridden due to this being an inherited constructor.
6726   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6727     if (!ICI)
6728       return {};
6729     assert(CSM == Sema::CXXDefaultConstructor);
6730     auto *BaseCtor =
6731       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6732     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6733       return MD;
6734     return {};
6735   }
6736 
6737   /// A base or member subobject.
6738   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6739 
6740   /// Get the location to use for a subobject in diagnostics.
6741   static SourceLocation getSubobjectLoc(Subobject Subobj) {
6742     // FIXME: For an indirect virtual base, the direct base leading to
6743     // the indirect virtual base would be a more useful choice.
6744     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6745       return B->getBaseTypeLoc();
6746     else
6747       return Subobj.get<FieldDecl*>()->getLocation();
6748   }
6749 
6750   enum BasesToVisit {
6751     /// Visit all non-virtual (direct) bases.
6752     VisitNonVirtualBases,
6753     /// Visit all direct bases, virtual or not.
6754     VisitDirectBases,
6755     /// Visit all non-virtual bases, and all virtual bases if the class
6756     /// is not abstract.
6757     VisitPotentiallyConstructedBases,
6758     /// Visit all direct or virtual bases.
6759     VisitAllBases
6760   };
6761 
6762   // Visit the bases and members of the class.
6763   bool visit(BasesToVisit Bases) {
6764     CXXRecordDecl *RD = MD->getParent();
6765 
6766     if (Bases == VisitPotentiallyConstructedBases)
6767       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6768 
6769     for (auto &B : RD->bases())
6770       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6771           getDerived().visitBase(&B))
6772         return true;
6773 
6774     if (Bases == VisitAllBases)
6775       for (auto &B : RD->vbases())
6776         if (getDerived().visitBase(&B))
6777           return true;
6778 
6779     for (auto *F : RD->fields())
6780       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6781           getDerived().visitField(F))
6782         return true;
6783 
6784     return false;
6785   }
6786 };
6787 }
6788 
6789 namespace {
6790 struct SpecialMemberDeletionInfo
6791     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6792   bool Diagnose;
6793 
6794   SourceLocation Loc;
6795 
6796   bool AllFieldsAreConst;
6797 
6798   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6799                             Sema::CXXSpecialMember CSM,
6800                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6801       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6802         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6803 
6804   bool inUnion() const { return MD->getParent()->isUnion(); }
6805 
6806   Sema::CXXSpecialMember getEffectiveCSM() {
6807     return ICI ? Sema::CXXInvalid : CSM;
6808   }
6809 
6810   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6811   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6812 
6813   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6814   bool shouldDeleteForField(FieldDecl *FD);
6815   bool shouldDeleteForAllConstMembers();
6816 
6817   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6818                                      unsigned Quals);
6819   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6820                                     Sema::SpecialMemberOverloadResult SMOR,
6821                                     bool IsDtorCallInCtor);
6822 
6823   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6824 };
6825 }
6826 
6827 /// Is the given special member inaccessible when used on the given
6828 /// sub-object.
6829 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6830                                              CXXMethodDecl *target) {
6831   /// If we're operating on a base class, the object type is the
6832   /// type of this special member.
6833   QualType objectTy;
6834   AccessSpecifier access = target->getAccess();
6835   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6836     objectTy = S.Context.getTypeDeclType(MD->getParent());
6837     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6838 
6839   // If we're operating on a field, the object type is the type of the field.
6840   } else {
6841     objectTy = S.Context.getTypeDeclType(target->getParent());
6842   }
6843 
6844   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6845 }
6846 
6847 /// Check whether we should delete a special member due to the implicit
6848 /// definition containing a call to a special member of a subobject.
6849 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6850     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6851     bool IsDtorCallInCtor) {
6852   CXXMethodDecl *Decl = SMOR.getMethod();
6853   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6854 
6855   int DiagKind = -1;
6856 
6857   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6858     DiagKind = !Decl ? 0 : 1;
6859   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6860     DiagKind = 2;
6861   else if (!isAccessible(Subobj, Decl))
6862     DiagKind = 3;
6863   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6864            !Decl->isTrivial()) {
6865     // A member of a union must have a trivial corresponding special member.
6866     // As a weird special case, a destructor call from a union's constructor
6867     // must be accessible and non-deleted, but need not be trivial. Such a
6868     // destructor is never actually called, but is semantically checked as
6869     // if it were.
6870     DiagKind = 4;
6871   }
6872 
6873   if (DiagKind == -1)
6874     return false;
6875 
6876   if (Diagnose) {
6877     if (Field) {
6878       S.Diag(Field->getLocation(),
6879              diag::note_deleted_special_member_class_subobject)
6880         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6881         << Field << DiagKind << IsDtorCallInCtor;
6882     } else {
6883       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6884       S.Diag(Base->getLocStart(),
6885              diag::note_deleted_special_member_class_subobject)
6886         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6887         << Base->getType() << DiagKind << IsDtorCallInCtor;
6888     }
6889 
6890     if (DiagKind == 1)
6891       S.NoteDeletedFunction(Decl);
6892     // FIXME: Explain inaccessibility if DiagKind == 3.
6893   }
6894 
6895   return true;
6896 }
6897 
6898 /// Check whether we should delete a special member function due to having a
6899 /// direct or virtual base class or non-static data member of class type M.
6900 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6901     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6902   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6903   bool IsMutable = Field && Field->isMutable();
6904 
6905   // C++11 [class.ctor]p5:
6906   // -- any direct or virtual base class, or non-static data member with no
6907   //    brace-or-equal-initializer, has class type M (or array thereof) and
6908   //    either M has no default constructor or overload resolution as applied
6909   //    to M's default constructor results in an ambiguity or in a function
6910   //    that is deleted or inaccessible
6911   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6912   // -- a direct or virtual base class B that cannot be copied/moved because
6913   //    overload resolution, as applied to B's corresponding special member,
6914   //    results in an ambiguity or a function that is deleted or inaccessible
6915   //    from the defaulted special member
6916   // C++11 [class.dtor]p5:
6917   // -- any direct or virtual base class [...] has a type with a destructor
6918   //    that is deleted or inaccessible
6919   if (!(CSM == Sema::CXXDefaultConstructor &&
6920         Field && Field->hasInClassInitializer()) &&
6921       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6922                                    false))
6923     return true;
6924 
6925   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6926   // -- any direct or virtual base class or non-static data member has a
6927   //    type with a destructor that is deleted or inaccessible
6928   if (IsConstructor) {
6929     Sema::SpecialMemberOverloadResult SMOR =
6930         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6931                               false, false, false, false, false);
6932     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6933       return true;
6934   }
6935 
6936   return false;
6937 }
6938 
6939 /// Check whether we should delete a special member function due to the class
6940 /// having a particular direct or virtual base class.
6941 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6942   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6943   // If program is correct, BaseClass cannot be null, but if it is, the error
6944   // must be reported elsewhere.
6945   if (!BaseClass)
6946     return false;
6947   // If we have an inheriting constructor, check whether we're calling an
6948   // inherited constructor instead of a default constructor.
6949   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6950   if (auto *BaseCtor = SMOR.getMethod()) {
6951     // Note that we do not check access along this path; other than that,
6952     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6953     // FIXME: Check that the base has a usable destructor! Sink this into
6954     // shouldDeleteForClassSubobject.
6955     if (BaseCtor->isDeleted() && Diagnose) {
6956       S.Diag(Base->getLocStart(),
6957              diag::note_deleted_special_member_class_subobject)
6958         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6959         << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6960       S.NoteDeletedFunction(BaseCtor);
6961     }
6962     return BaseCtor->isDeleted();
6963   }
6964   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6965 }
6966 
6967 /// Check whether we should delete a special member function due to the class
6968 /// having a particular non-static data member.
6969 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6970   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6971   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6972 
6973   if (CSM == Sema::CXXDefaultConstructor) {
6974     // For a default constructor, all references must be initialized in-class
6975     // and, if a union, it must have a non-const member.
6976     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6977       if (Diagnose)
6978         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6979           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6980       return true;
6981     }
6982     // C++11 [class.ctor]p5: any non-variant non-static data member of
6983     // const-qualified type (or array thereof) with no
6984     // brace-or-equal-initializer does not have a user-provided default
6985     // constructor.
6986     if (!inUnion() && FieldType.isConstQualified() &&
6987         !FD->hasInClassInitializer() &&
6988         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6989       if (Diagnose)
6990         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6991           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6992       return true;
6993     }
6994 
6995     if (inUnion() && !FieldType.isConstQualified())
6996       AllFieldsAreConst = false;
6997   } else if (CSM == Sema::CXXCopyConstructor) {
6998     // For a copy constructor, data members must not be of rvalue reference
6999     // type.
7000     if (FieldType->isRValueReferenceType()) {
7001       if (Diagnose)
7002         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7003           << MD->getParent() << FD << FieldType;
7004       return true;
7005     }
7006   } else if (IsAssignment) {
7007     // For an assignment operator, data members must not be of reference type.
7008     if (FieldType->isReferenceType()) {
7009       if (Diagnose)
7010         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7011           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7012       return true;
7013     }
7014     if (!FieldRecord && FieldType.isConstQualified()) {
7015       // C++11 [class.copy]p23:
7016       // -- a non-static data member of const non-class type (or array thereof)
7017       if (Diagnose)
7018         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7019           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7020       return true;
7021     }
7022   }
7023 
7024   if (FieldRecord) {
7025     // Some additional restrictions exist on the variant members.
7026     if (!inUnion() && FieldRecord->isUnion() &&
7027         FieldRecord->isAnonymousStructOrUnion()) {
7028       bool AllVariantFieldsAreConst = true;
7029 
7030       // FIXME: Handle anonymous unions declared within anonymous unions.
7031       for (auto *UI : FieldRecord->fields()) {
7032         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7033 
7034         if (!UnionFieldType.isConstQualified())
7035           AllVariantFieldsAreConst = false;
7036 
7037         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7038         if (UnionFieldRecord &&
7039             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7040                                           UnionFieldType.getCVRQualifiers()))
7041           return true;
7042       }
7043 
7044       // At least one member in each anonymous union must be non-const
7045       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7046           !FieldRecord->field_empty()) {
7047         if (Diagnose)
7048           S.Diag(FieldRecord->getLocation(),
7049                  diag::note_deleted_default_ctor_all_const)
7050             << !!ICI << MD->getParent() << /*anonymous union*/1;
7051         return true;
7052       }
7053 
7054       // Don't check the implicit member of the anonymous union type.
7055       // This is technically non-conformant, but sanity demands it.
7056       return false;
7057     }
7058 
7059     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7060                                       FieldType.getCVRQualifiers()))
7061       return true;
7062   }
7063 
7064   return false;
7065 }
7066 
7067 /// C++11 [class.ctor] p5:
7068 ///   A defaulted default constructor for a class X is defined as deleted if
7069 /// X is a union and all of its variant members are of const-qualified type.
7070 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7071   // This is a silly definition, because it gives an empty union a deleted
7072   // default constructor. Don't do that.
7073   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7074     bool AnyFields = false;
7075     for (auto *F : MD->getParent()->fields())
7076       if ((AnyFields = !F->isUnnamedBitfield()))
7077         break;
7078     if (!AnyFields)
7079       return false;
7080     if (Diagnose)
7081       S.Diag(MD->getParent()->getLocation(),
7082              diag::note_deleted_default_ctor_all_const)
7083         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7084     return true;
7085   }
7086   return false;
7087 }
7088 
7089 /// Determine whether a defaulted special member function should be defined as
7090 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7091 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7092 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7093                                      InheritedConstructorInfo *ICI,
7094                                      bool Diagnose) {
7095   if (MD->isInvalidDecl())
7096     return false;
7097   CXXRecordDecl *RD = MD->getParent();
7098   assert(!RD->isDependentType() && "do deletion after instantiation");
7099   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7100     return false;
7101 
7102   // C++11 [expr.lambda.prim]p19:
7103   //   The closure type associated with a lambda-expression has a
7104   //   deleted (8.4.3) default constructor and a deleted copy
7105   //   assignment operator.
7106   if (RD->isLambda() &&
7107       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7108     if (Diagnose)
7109       Diag(RD->getLocation(), diag::note_lambda_decl);
7110     return true;
7111   }
7112 
7113   // For an anonymous struct or union, the copy and assignment special members
7114   // will never be used, so skip the check. For an anonymous union declared at
7115   // namespace scope, the constructor and destructor are used.
7116   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7117       RD->isAnonymousStructOrUnion())
7118     return false;
7119 
7120   // C++11 [class.copy]p7, p18:
7121   //   If the class definition declares a move constructor or move assignment
7122   //   operator, an implicitly declared copy constructor or copy assignment
7123   //   operator is defined as deleted.
7124   if (MD->isImplicit() &&
7125       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7126     CXXMethodDecl *UserDeclaredMove = nullptr;
7127 
7128     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7129     // deletion of the corresponding copy operation, not both copy operations.
7130     // MSVC 2015 has adopted the standards conforming behavior.
7131     bool DeletesOnlyMatchingCopy =
7132         getLangOpts().MSVCCompat &&
7133         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7134 
7135     if (RD->hasUserDeclaredMoveConstructor() &&
7136         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7137       if (!Diagnose) return true;
7138 
7139       // Find any user-declared move constructor.
7140       for (auto *I : RD->ctors()) {
7141         if (I->isMoveConstructor()) {
7142           UserDeclaredMove = I;
7143           break;
7144         }
7145       }
7146       assert(UserDeclaredMove);
7147     } else if (RD->hasUserDeclaredMoveAssignment() &&
7148                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7149       if (!Diagnose) return true;
7150 
7151       // Find any user-declared move assignment operator.
7152       for (auto *I : RD->methods()) {
7153         if (I->isMoveAssignmentOperator()) {
7154           UserDeclaredMove = I;
7155           break;
7156         }
7157       }
7158       assert(UserDeclaredMove);
7159     }
7160 
7161     if (UserDeclaredMove) {
7162       Diag(UserDeclaredMove->getLocation(),
7163            diag::note_deleted_copy_user_declared_move)
7164         << (CSM == CXXCopyAssignment) << RD
7165         << UserDeclaredMove->isMoveAssignmentOperator();
7166       return true;
7167     }
7168   }
7169 
7170   // Do access control from the special member function
7171   ContextRAII MethodContext(*this, MD);
7172 
7173   // C++11 [class.dtor]p5:
7174   // -- for a virtual destructor, lookup of the non-array deallocation function
7175   //    results in an ambiguity or in a function that is deleted or inaccessible
7176   if (CSM == CXXDestructor && MD->isVirtual()) {
7177     FunctionDecl *OperatorDelete = nullptr;
7178     DeclarationName Name =
7179       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7180     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7181                                  OperatorDelete, /*Diagnose*/false)) {
7182       if (Diagnose)
7183         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7184       return true;
7185     }
7186   }
7187 
7188   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7189 
7190   // Per DR1611, do not consider virtual bases of constructors of abstract
7191   // classes, since we are not going to construct them.
7192   // Per DR1658, do not consider virtual bases of destructors of abstract
7193   // classes either.
7194   // Per DR2180, for assignment operators we only assign (and thus only
7195   // consider) direct bases.
7196   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7197                                  : SMI.VisitPotentiallyConstructedBases))
7198     return true;
7199 
7200   if (SMI.shouldDeleteForAllConstMembers())
7201     return true;
7202 
7203   if (getLangOpts().CUDA) {
7204     // We should delete the special member in CUDA mode if target inference
7205     // failed.
7206     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7207                                                    Diagnose);
7208   }
7209 
7210   return false;
7211 }
7212 
7213 /// Perform lookup for a special member of the specified kind, and determine
7214 /// whether it is trivial. If the triviality can be determined without the
7215 /// lookup, skip it. This is intended for use when determining whether a
7216 /// special member of a containing object is trivial, and thus does not ever
7217 /// perform overload resolution for default constructors.
7218 ///
7219 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7220 /// member that was most likely to be intended to be trivial, if any.
7221 ///
7222 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7223 /// determine whether the special member is trivial.
7224 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7225                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7226                                      bool ConstRHS,
7227                                      Sema::TrivialABIHandling TAH,
7228                                      CXXMethodDecl **Selected) {
7229   if (Selected)
7230     *Selected = nullptr;
7231 
7232   switch (CSM) {
7233   case Sema::CXXInvalid:
7234     llvm_unreachable("not a special member");
7235 
7236   case Sema::CXXDefaultConstructor:
7237     // C++11 [class.ctor]p5:
7238     //   A default constructor is trivial if:
7239     //    - all the [direct subobjects] have trivial default constructors
7240     //
7241     // Note, no overload resolution is performed in this case.
7242     if (RD->hasTrivialDefaultConstructor())
7243       return true;
7244 
7245     if (Selected) {
7246       // If there's a default constructor which could have been trivial, dig it
7247       // out. Otherwise, if there's any user-provided default constructor, point
7248       // to that as an example of why there's not a trivial one.
7249       CXXConstructorDecl *DefCtor = nullptr;
7250       if (RD->needsImplicitDefaultConstructor())
7251         S.DeclareImplicitDefaultConstructor(RD);
7252       for (auto *CI : RD->ctors()) {
7253         if (!CI->isDefaultConstructor())
7254           continue;
7255         DefCtor = CI;
7256         if (!DefCtor->isUserProvided())
7257           break;
7258       }
7259 
7260       *Selected = DefCtor;
7261     }
7262 
7263     return false;
7264 
7265   case Sema::CXXDestructor:
7266     // C++11 [class.dtor]p5:
7267     //   A destructor is trivial if:
7268     //    - all the direct [subobjects] have trivial destructors
7269     if (RD->hasTrivialDestructor() ||
7270         (TAH == Sema::TAH_ConsiderTrivialABI &&
7271          RD->hasTrivialDestructorForCall()))
7272       return true;
7273 
7274     if (Selected) {
7275       if (RD->needsImplicitDestructor())
7276         S.DeclareImplicitDestructor(RD);
7277       *Selected = RD->getDestructor();
7278     }
7279 
7280     return false;
7281 
7282   case Sema::CXXCopyConstructor:
7283     // C++11 [class.copy]p12:
7284     //   A copy constructor is trivial if:
7285     //    - the constructor selected to copy each direct [subobject] is trivial
7286     if (RD->hasTrivialCopyConstructor() ||
7287         (TAH == Sema::TAH_ConsiderTrivialABI &&
7288          RD->hasTrivialCopyConstructorForCall())) {
7289       if (Quals == Qualifiers::Const)
7290         // We must either select the trivial copy constructor or reach an
7291         // ambiguity; no need to actually perform overload resolution.
7292         return true;
7293     } else if (!Selected) {
7294       return false;
7295     }
7296     // In C++98, we are not supposed to perform overload resolution here, but we
7297     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7298     // cases like B as having a non-trivial copy constructor:
7299     //   struct A { template<typename T> A(T&); };
7300     //   struct B { mutable A a; };
7301     goto NeedOverloadResolution;
7302 
7303   case Sema::CXXCopyAssignment:
7304     // C++11 [class.copy]p25:
7305     //   A copy assignment operator is trivial if:
7306     //    - the assignment operator selected to copy each direct [subobject] is
7307     //      trivial
7308     if (RD->hasTrivialCopyAssignment()) {
7309       if (Quals == Qualifiers::Const)
7310         return true;
7311     } else if (!Selected) {
7312       return false;
7313     }
7314     // In C++98, we are not supposed to perform overload resolution here, but we
7315     // treat that as a language defect.
7316     goto NeedOverloadResolution;
7317 
7318   case Sema::CXXMoveConstructor:
7319   case Sema::CXXMoveAssignment:
7320   NeedOverloadResolution:
7321     Sema::SpecialMemberOverloadResult SMOR =
7322         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7323 
7324     // The standard doesn't describe how to behave if the lookup is ambiguous.
7325     // We treat it as not making the member non-trivial, just like the standard
7326     // mandates for the default constructor. This should rarely matter, because
7327     // the member will also be deleted.
7328     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7329       return true;
7330 
7331     if (!SMOR.getMethod()) {
7332       assert(SMOR.getKind() ==
7333              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7334       return false;
7335     }
7336 
7337     // We deliberately don't check if we found a deleted special member. We're
7338     // not supposed to!
7339     if (Selected)
7340       *Selected = SMOR.getMethod();
7341 
7342     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7343         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7344       return SMOR.getMethod()->isTrivialForCall();
7345     return SMOR.getMethod()->isTrivial();
7346   }
7347 
7348   llvm_unreachable("unknown special method kind");
7349 }
7350 
7351 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7352   for (auto *CI : RD->ctors())
7353     if (!CI->isImplicit())
7354       return CI;
7355 
7356   // Look for constructor templates.
7357   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7358   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7359     if (CXXConstructorDecl *CD =
7360           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7361       return CD;
7362   }
7363 
7364   return nullptr;
7365 }
7366 
7367 /// The kind of subobject we are checking for triviality. The values of this
7368 /// enumeration are used in diagnostics.
7369 enum TrivialSubobjectKind {
7370   /// The subobject is a base class.
7371   TSK_BaseClass,
7372   /// The subobject is a non-static data member.
7373   TSK_Field,
7374   /// The object is actually the complete object.
7375   TSK_CompleteObject
7376 };
7377 
7378 /// Check whether the special member selected for a given type would be trivial.
7379 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7380                                       QualType SubType, bool ConstRHS,
7381                                       Sema::CXXSpecialMember CSM,
7382                                       TrivialSubobjectKind Kind,
7383                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7384   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7385   if (!SubRD)
7386     return true;
7387 
7388   CXXMethodDecl *Selected;
7389   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7390                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7391     return true;
7392 
7393   if (Diagnose) {
7394     if (ConstRHS)
7395       SubType.addConst();
7396 
7397     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7398       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7399         << Kind << SubType.getUnqualifiedType();
7400       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7401         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7402     } else if (!Selected)
7403       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7404         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7405     else if (Selected->isUserProvided()) {
7406       if (Kind == TSK_CompleteObject)
7407         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7408           << Kind << SubType.getUnqualifiedType() << CSM;
7409       else {
7410         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7411           << Kind << SubType.getUnqualifiedType() << CSM;
7412         S.Diag(Selected->getLocation(), diag::note_declared_at);
7413       }
7414     } else {
7415       if (Kind != TSK_CompleteObject)
7416         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7417           << Kind << SubType.getUnqualifiedType() << CSM;
7418 
7419       // Explain why the defaulted or deleted special member isn't trivial.
7420       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7421                                Diagnose);
7422     }
7423   }
7424 
7425   return false;
7426 }
7427 
7428 /// Check whether the members of a class type allow a special member to be
7429 /// trivial.
7430 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7431                                      Sema::CXXSpecialMember CSM,
7432                                      bool ConstArg,
7433                                      Sema::TrivialABIHandling TAH,
7434                                      bool Diagnose) {
7435   for (const auto *FI : RD->fields()) {
7436     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7437       continue;
7438 
7439     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7440 
7441     // Pretend anonymous struct or union members are members of this class.
7442     if (FI->isAnonymousStructOrUnion()) {
7443       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7444                                     CSM, ConstArg, TAH, Diagnose))
7445         return false;
7446       continue;
7447     }
7448 
7449     // C++11 [class.ctor]p5:
7450     //   A default constructor is trivial if [...]
7451     //    -- no non-static data member of its class has a
7452     //       brace-or-equal-initializer
7453     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7454       if (Diagnose)
7455         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7456       return false;
7457     }
7458 
7459     // Objective C ARC 4.3.5:
7460     //   [...] nontrivally ownership-qualified types are [...] not trivially
7461     //   default constructible, copy constructible, move constructible, copy
7462     //   assignable, move assignable, or destructible [...]
7463     if (FieldType.hasNonTrivialObjCLifetime()) {
7464       if (Diagnose)
7465         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7466           << RD << FieldType.getObjCLifetime();
7467       return false;
7468     }
7469 
7470     bool ConstRHS = ConstArg && !FI->isMutable();
7471     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7472                                    CSM, TSK_Field, TAH, Diagnose))
7473       return false;
7474   }
7475 
7476   return true;
7477 }
7478 
7479 /// Diagnose why the specified class does not have a trivial special member of
7480 /// the given kind.
7481 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7482   QualType Ty = Context.getRecordType(RD);
7483 
7484   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7485   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7486                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7487                             /*Diagnose*/true);
7488 }
7489 
7490 /// Determine whether a defaulted or deleted special member function is trivial,
7491 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7492 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7493 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7494                                   TrivialABIHandling TAH, bool Diagnose) {
7495   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7496 
7497   CXXRecordDecl *RD = MD->getParent();
7498 
7499   bool ConstArg = false;
7500 
7501   // C++11 [class.copy]p12, p25: [DR1593]
7502   //   A [special member] is trivial if [...] its parameter-type-list is
7503   //   equivalent to the parameter-type-list of an implicit declaration [...]
7504   switch (CSM) {
7505   case CXXDefaultConstructor:
7506   case CXXDestructor:
7507     // Trivial default constructors and destructors cannot have parameters.
7508     break;
7509 
7510   case CXXCopyConstructor:
7511   case CXXCopyAssignment: {
7512     // Trivial copy operations always have const, non-volatile parameter types.
7513     ConstArg = true;
7514     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7515     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7516     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7517       if (Diagnose)
7518         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7519           << Param0->getSourceRange() << Param0->getType()
7520           << Context.getLValueReferenceType(
7521                Context.getRecordType(RD).withConst());
7522       return false;
7523     }
7524     break;
7525   }
7526 
7527   case CXXMoveConstructor:
7528   case CXXMoveAssignment: {
7529     // Trivial move operations always have non-cv-qualified parameters.
7530     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7531     const RValueReferenceType *RT =
7532       Param0->getType()->getAs<RValueReferenceType>();
7533     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7534       if (Diagnose)
7535         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7536           << Param0->getSourceRange() << Param0->getType()
7537           << Context.getRValueReferenceType(Context.getRecordType(RD));
7538       return false;
7539     }
7540     break;
7541   }
7542 
7543   case CXXInvalid:
7544     llvm_unreachable("not a special member");
7545   }
7546 
7547   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7548     if (Diagnose)
7549       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7550            diag::note_nontrivial_default_arg)
7551         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7552     return false;
7553   }
7554   if (MD->isVariadic()) {
7555     if (Diagnose)
7556       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7557     return false;
7558   }
7559 
7560   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7561   //   A copy/move [constructor or assignment operator] is trivial if
7562   //    -- the [member] selected to copy/move each direct base class subobject
7563   //       is trivial
7564   //
7565   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7566   //   A [default constructor or destructor] is trivial if
7567   //    -- all the direct base classes have trivial [default constructors or
7568   //       destructors]
7569   for (const auto &BI : RD->bases())
7570     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7571                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7572       return false;
7573 
7574   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7575   //   A copy/move [constructor or assignment operator] for a class X is
7576   //   trivial if
7577   //    -- for each non-static data member of X that is of class type (or array
7578   //       thereof), the constructor selected to copy/move that member is
7579   //       trivial
7580   //
7581   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7582   //   A [default constructor or destructor] is trivial if
7583   //    -- for all of the non-static data members of its class that are of class
7584   //       type (or array thereof), each such class has a trivial [default
7585   //       constructor or destructor]
7586   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7587     return false;
7588 
7589   // C++11 [class.dtor]p5:
7590   //   A destructor is trivial if [...]
7591   //    -- the destructor is not virtual
7592   if (CSM == CXXDestructor && MD->isVirtual()) {
7593     if (Diagnose)
7594       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7595     return false;
7596   }
7597 
7598   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7599   //   A [special member] for class X is trivial if [...]
7600   //    -- class X has no virtual functions and no virtual base classes
7601   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7602     if (!Diagnose)
7603       return false;
7604 
7605     if (RD->getNumVBases()) {
7606       // Check for virtual bases. We already know that the corresponding
7607       // member in all bases is trivial, so vbases must all be direct.
7608       CXXBaseSpecifier &BS = *RD->vbases_begin();
7609       assert(BS.isVirtual());
7610       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7611       return false;
7612     }
7613 
7614     // Must have a virtual method.
7615     for (const auto *MI : RD->methods()) {
7616       if (MI->isVirtual()) {
7617         SourceLocation MLoc = MI->getLocStart();
7618         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7619         return false;
7620       }
7621     }
7622 
7623     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7624   }
7625 
7626   // Looks like it's trivial!
7627   return true;
7628 }
7629 
7630 namespace {
7631 struct FindHiddenVirtualMethod {
7632   Sema *S;
7633   CXXMethodDecl *Method;
7634   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7635   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7636 
7637 private:
7638   /// Check whether any most overriden method from MD in Methods
7639   static bool CheckMostOverridenMethods(
7640       const CXXMethodDecl *MD,
7641       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7642     if (MD->size_overridden_methods() == 0)
7643       return Methods.count(MD->getCanonicalDecl());
7644     for (const CXXMethodDecl *O : MD->overridden_methods())
7645       if (CheckMostOverridenMethods(O, Methods))
7646         return true;
7647     return false;
7648   }
7649 
7650 public:
7651   /// Member lookup function that determines whether a given C++
7652   /// method overloads virtual methods in a base class without overriding any,
7653   /// to be used with CXXRecordDecl::lookupInBases().
7654   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7655     RecordDecl *BaseRecord =
7656         Specifier->getType()->getAs<RecordType>()->getDecl();
7657 
7658     DeclarationName Name = Method->getDeclName();
7659     assert(Name.getNameKind() == DeclarationName::Identifier);
7660 
7661     bool foundSameNameMethod = false;
7662     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7663     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7664          Path.Decls = Path.Decls.slice(1)) {
7665       NamedDecl *D = Path.Decls.front();
7666       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7667         MD = MD->getCanonicalDecl();
7668         foundSameNameMethod = true;
7669         // Interested only in hidden virtual methods.
7670         if (!MD->isVirtual())
7671           continue;
7672         // If the method we are checking overrides a method from its base
7673         // don't warn about the other overloaded methods. Clang deviates from
7674         // GCC by only diagnosing overloads of inherited virtual functions that
7675         // do not override any other virtual functions in the base. GCC's
7676         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7677         // function from a base class. These cases may be better served by a
7678         // warning (not specific to virtual functions) on call sites when the
7679         // call would select a different function from the base class, were it
7680         // visible.
7681         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7682         if (!S->IsOverload(Method, MD, false))
7683           return true;
7684         // Collect the overload only if its hidden.
7685         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7686           overloadedMethods.push_back(MD);
7687       }
7688     }
7689 
7690     if (foundSameNameMethod)
7691       OverloadedMethods.append(overloadedMethods.begin(),
7692                                overloadedMethods.end());
7693     return foundSameNameMethod;
7694   }
7695 };
7696 } // end anonymous namespace
7697 
7698 /// Add the most overriden methods from MD to Methods
7699 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7700                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7701   if (MD->size_overridden_methods() == 0)
7702     Methods.insert(MD->getCanonicalDecl());
7703   else
7704     for (const CXXMethodDecl *O : MD->overridden_methods())
7705       AddMostOverridenMethods(O, Methods);
7706 }
7707 
7708 /// Check if a method overloads virtual methods in a base class without
7709 /// overriding any.
7710 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7711                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7712   if (!MD->getDeclName().isIdentifier())
7713     return;
7714 
7715   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7716                      /*bool RecordPaths=*/false,
7717                      /*bool DetectVirtual=*/false);
7718   FindHiddenVirtualMethod FHVM;
7719   FHVM.Method = MD;
7720   FHVM.S = this;
7721 
7722   // Keep the base methods that were overriden or introduced in the subclass
7723   // by 'using' in a set. A base method not in this set is hidden.
7724   CXXRecordDecl *DC = MD->getParent();
7725   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7726   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7727     NamedDecl *ND = *I;
7728     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7729       ND = shad->getTargetDecl();
7730     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7731       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7732   }
7733 
7734   if (DC->lookupInBases(FHVM, Paths))
7735     OverloadedMethods = FHVM.OverloadedMethods;
7736 }
7737 
7738 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7739                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7740   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7741     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7742     PartialDiagnostic PD = PDiag(
7743          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7744     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7745     Diag(overloadedMD->getLocation(), PD);
7746   }
7747 }
7748 
7749 /// Diagnose methods which overload virtual methods in a base class
7750 /// without overriding any.
7751 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7752   if (MD->isInvalidDecl())
7753     return;
7754 
7755   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7756     return;
7757 
7758   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7759   FindHiddenVirtualMethods(MD, OverloadedMethods);
7760   if (!OverloadedMethods.empty()) {
7761     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7762       << MD << (OverloadedMethods.size() > 1);
7763 
7764     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7765   }
7766 }
7767 
7768 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7769   auto PrintDiagAndRemoveAttr = [&]() {
7770     // No diagnostics if this is a template instantiation.
7771     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7772       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7773            diag::ext_cannot_use_trivial_abi) << &RD;
7774     RD.dropAttr<TrivialABIAttr>();
7775   };
7776 
7777   // Ill-formed if the struct has virtual functions.
7778   if (RD.isPolymorphic()) {
7779     PrintDiagAndRemoveAttr();
7780     return;
7781   }
7782 
7783   for (const auto &B : RD.bases()) {
7784     // Ill-formed if the base class is non-trivial for the purpose of calls or a
7785     // virtual base.
7786     if ((!B.getType()->isDependentType() &&
7787          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7788         B.isVirtual()) {
7789       PrintDiagAndRemoveAttr();
7790       return;
7791     }
7792   }
7793 
7794   for (const auto *FD : RD.fields()) {
7795     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7796     // non-trivial for the purpose of calls.
7797     QualType FT = FD->getType();
7798     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7799       PrintDiagAndRemoveAttr();
7800       return;
7801     }
7802 
7803     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7804       if (!RT->isDependentType() &&
7805           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7806         PrintDiagAndRemoveAttr();
7807         return;
7808       }
7809   }
7810 }
7811 
7812 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7813                                              Decl *TagDecl,
7814                                              SourceLocation LBrac,
7815                                              SourceLocation RBrac,
7816                                              AttributeList *AttrList) {
7817   if (!TagDecl)
7818     return;
7819 
7820   AdjustDeclIfTemplate(TagDecl);
7821 
7822   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7823     if (l->getKind() != AttributeList::AT_Visibility)
7824       continue;
7825     l->setInvalid();
7826     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7827       l->getName();
7828   }
7829 
7830   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7831               // strict aliasing violation!
7832               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7833               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7834 
7835   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7836 }
7837 
7838 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7839 /// special functions, such as the default constructor, copy
7840 /// constructor, or destructor, to the given C++ class (C++
7841 /// [special]p1).  This routine can only be executed just before the
7842 /// definition of the class is complete.
7843 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7844   if (ClassDecl->needsImplicitDefaultConstructor()) {
7845     ++ASTContext::NumImplicitDefaultConstructors;
7846 
7847     if (ClassDecl->hasInheritedConstructor())
7848       DeclareImplicitDefaultConstructor(ClassDecl);
7849   }
7850 
7851   if (ClassDecl->needsImplicitCopyConstructor()) {
7852     ++ASTContext::NumImplicitCopyConstructors;
7853 
7854     // If the properties or semantics of the copy constructor couldn't be
7855     // determined while the class was being declared, force a declaration
7856     // of it now.
7857     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7858         ClassDecl->hasInheritedConstructor())
7859       DeclareImplicitCopyConstructor(ClassDecl);
7860     // For the MS ABI we need to know whether the copy ctor is deleted. A
7861     // prerequisite for deleting the implicit copy ctor is that the class has a
7862     // move ctor or move assignment that is either user-declared or whose
7863     // semantics are inherited from a subobject. FIXME: We should provide a more
7864     // direct way for CodeGen to ask whether the constructor was deleted.
7865     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7866              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7867               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7868               ClassDecl->hasUserDeclaredMoveAssignment() ||
7869               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7870       DeclareImplicitCopyConstructor(ClassDecl);
7871   }
7872 
7873   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7874     ++ASTContext::NumImplicitMoveConstructors;
7875 
7876     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7877         ClassDecl->hasInheritedConstructor())
7878       DeclareImplicitMoveConstructor(ClassDecl);
7879   }
7880 
7881   if (ClassDecl->needsImplicitCopyAssignment()) {
7882     ++ASTContext::NumImplicitCopyAssignmentOperators;
7883 
7884     // If we have a dynamic class, then the copy assignment operator may be
7885     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7886     // it shows up in the right place in the vtable and that we diagnose
7887     // problems with the implicit exception specification.
7888     if (ClassDecl->isDynamicClass() ||
7889         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7890         ClassDecl->hasInheritedAssignment())
7891       DeclareImplicitCopyAssignment(ClassDecl);
7892   }
7893 
7894   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7895     ++ASTContext::NumImplicitMoveAssignmentOperators;
7896 
7897     // Likewise for the move assignment operator.
7898     if (ClassDecl->isDynamicClass() ||
7899         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7900         ClassDecl->hasInheritedAssignment())
7901       DeclareImplicitMoveAssignment(ClassDecl);
7902   }
7903 
7904   if (ClassDecl->needsImplicitDestructor()) {
7905     ++ASTContext::NumImplicitDestructors;
7906 
7907     // If we have a dynamic class, then the destructor may be virtual, so we
7908     // have to declare the destructor immediately. This ensures that, e.g., it
7909     // shows up in the right place in the vtable and that we diagnose problems
7910     // with the implicit exception specification.
7911     if (ClassDecl->isDynamicClass() ||
7912         ClassDecl->needsOverloadResolutionForDestructor())
7913       DeclareImplicitDestructor(ClassDecl);
7914   }
7915 }
7916 
7917 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7918   if (!D)
7919     return 0;
7920 
7921   // The order of template parameters is not important here. All names
7922   // get added to the same scope.
7923   SmallVector<TemplateParameterList *, 4> ParameterLists;
7924 
7925   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7926     D = TD->getTemplatedDecl();
7927 
7928   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7929     ParameterLists.push_back(PSD->getTemplateParameters());
7930 
7931   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7932     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7933       ParameterLists.push_back(DD->getTemplateParameterList(i));
7934 
7935     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7936       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7937         ParameterLists.push_back(FTD->getTemplateParameters());
7938     }
7939   }
7940 
7941   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7942     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7943       ParameterLists.push_back(TD->getTemplateParameterList(i));
7944 
7945     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7946       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7947         ParameterLists.push_back(CTD->getTemplateParameters());
7948     }
7949   }
7950 
7951   unsigned Count = 0;
7952   for (TemplateParameterList *Params : ParameterLists) {
7953     if (Params->size() > 0)
7954       // Ignore explicit specializations; they don't contribute to the template
7955       // depth.
7956       ++Count;
7957     for (NamedDecl *Param : *Params) {
7958       if (Param->getDeclName()) {
7959         S->AddDecl(Param);
7960         IdResolver.AddDecl(Param);
7961       }
7962     }
7963   }
7964 
7965   return Count;
7966 }
7967 
7968 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7969   if (!RecordD) return;
7970   AdjustDeclIfTemplate(RecordD);
7971   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7972   PushDeclContext(S, Record);
7973 }
7974 
7975 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7976   if (!RecordD) return;
7977   PopDeclContext();
7978 }
7979 
7980 /// This is used to implement the constant expression evaluation part of the
7981 /// attribute enable_if extension. There is nothing in standard C++ which would
7982 /// require reentering parameters.
7983 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7984   if (!Param)
7985     return;
7986 
7987   S->AddDecl(Param);
7988   if (Param->getDeclName())
7989     IdResolver.AddDecl(Param);
7990 }
7991 
7992 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7993 /// parsing a top-level (non-nested) C++ class, and we are now
7994 /// parsing those parts of the given Method declaration that could
7995 /// not be parsed earlier (C++ [class.mem]p2), such as default
7996 /// arguments. This action should enter the scope of the given
7997 /// Method declaration as if we had just parsed the qualified method
7998 /// name. However, it should not bring the parameters into scope;
7999 /// that will be performed by ActOnDelayedCXXMethodParameter.
8000 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8001 }
8002 
8003 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8004 /// C++ method declaration. We're (re-)introducing the given
8005 /// function parameter into scope for use in parsing later parts of
8006 /// the method declaration. For example, we could see an
8007 /// ActOnParamDefaultArgument event for this parameter.
8008 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8009   if (!ParamD)
8010     return;
8011 
8012   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8013 
8014   // If this parameter has an unparsed default argument, clear it out
8015   // to make way for the parsed default argument.
8016   if (Param->hasUnparsedDefaultArg())
8017     Param->setDefaultArg(nullptr);
8018 
8019   S->AddDecl(Param);
8020   if (Param->getDeclName())
8021     IdResolver.AddDecl(Param);
8022 }
8023 
8024 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8025 /// processing the delayed method declaration for Method. The method
8026 /// declaration is now considered finished. There may be a separate
8027 /// ActOnStartOfFunctionDef action later (not necessarily
8028 /// immediately!) for this method, if it was also defined inside the
8029 /// class body.
8030 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8031   if (!MethodD)
8032     return;
8033 
8034   AdjustDeclIfTemplate(MethodD);
8035 
8036   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8037 
8038   // Now that we have our default arguments, check the constructor
8039   // again. It could produce additional diagnostics or affect whether
8040   // the class has implicitly-declared destructors, among other
8041   // things.
8042   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8043     CheckConstructor(Constructor);
8044 
8045   // Check the default arguments, which we may have added.
8046   if (!Method->isInvalidDecl())
8047     CheckCXXDefaultArguments(Method);
8048 }
8049 
8050 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8051 /// the well-formedness of the constructor declarator @p D with type @p
8052 /// R. If there are any errors in the declarator, this routine will
8053 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8054 /// will be updated to reflect a well-formed type for the constructor and
8055 /// returned.
8056 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8057                                           StorageClass &SC) {
8058   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8059 
8060   // C++ [class.ctor]p3:
8061   //   A constructor shall not be virtual (10.3) or static (9.4). A
8062   //   constructor can be invoked for a const, volatile or const
8063   //   volatile object. A constructor shall not be declared const,
8064   //   volatile, or const volatile (9.3.2).
8065   if (isVirtual) {
8066     if (!D.isInvalidType())
8067       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8068         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8069         << SourceRange(D.getIdentifierLoc());
8070     D.setInvalidType();
8071   }
8072   if (SC == SC_Static) {
8073     if (!D.isInvalidType())
8074       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8075         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8076         << SourceRange(D.getIdentifierLoc());
8077     D.setInvalidType();
8078     SC = SC_None;
8079   }
8080 
8081   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8082     diagnoseIgnoredQualifiers(
8083         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8084         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8085         D.getDeclSpec().getRestrictSpecLoc(),
8086         D.getDeclSpec().getAtomicSpecLoc());
8087     D.setInvalidType();
8088   }
8089 
8090   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8091   if (FTI.TypeQuals != 0) {
8092     if (FTI.TypeQuals & Qualifiers::Const)
8093       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8094         << "const" << SourceRange(D.getIdentifierLoc());
8095     if (FTI.TypeQuals & Qualifiers::Volatile)
8096       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8097         << "volatile" << SourceRange(D.getIdentifierLoc());
8098     if (FTI.TypeQuals & Qualifiers::Restrict)
8099       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8100         << "restrict" << SourceRange(D.getIdentifierLoc());
8101     D.setInvalidType();
8102   }
8103 
8104   // C++0x [class.ctor]p4:
8105   //   A constructor shall not be declared with a ref-qualifier.
8106   if (FTI.hasRefQualifier()) {
8107     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8108       << FTI.RefQualifierIsLValueRef
8109       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8110     D.setInvalidType();
8111   }
8112 
8113   // Rebuild the function type "R" without any type qualifiers (in
8114   // case any of the errors above fired) and with "void" as the
8115   // return type, since constructors don't have return types.
8116   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8117   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8118     return R;
8119 
8120   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8121   EPI.TypeQuals = 0;
8122   EPI.RefQualifier = RQ_None;
8123 
8124   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8125 }
8126 
8127 /// CheckConstructor - Checks a fully-formed constructor for
8128 /// well-formedness, issuing any diagnostics required. Returns true if
8129 /// the constructor declarator is invalid.
8130 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8131   CXXRecordDecl *ClassDecl
8132     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8133   if (!ClassDecl)
8134     return Constructor->setInvalidDecl();
8135 
8136   // C++ [class.copy]p3:
8137   //   A declaration of a constructor for a class X is ill-formed if
8138   //   its first parameter is of type (optionally cv-qualified) X and
8139   //   either there are no other parameters or else all other
8140   //   parameters have default arguments.
8141   if (!Constructor->isInvalidDecl() &&
8142       ((Constructor->getNumParams() == 1) ||
8143        (Constructor->getNumParams() > 1 &&
8144         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8145       Constructor->getTemplateSpecializationKind()
8146                                               != TSK_ImplicitInstantiation) {
8147     QualType ParamType = Constructor->getParamDecl(0)->getType();
8148     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8149     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8150       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8151       const char *ConstRef
8152         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8153                                                         : " const &";
8154       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8155         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8156 
8157       // FIXME: Rather that making the constructor invalid, we should endeavor
8158       // to fix the type.
8159       Constructor->setInvalidDecl();
8160     }
8161   }
8162 }
8163 
8164 /// CheckDestructor - Checks a fully-formed destructor definition for
8165 /// well-formedness, issuing any diagnostics required.  Returns true
8166 /// on error.
8167 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8168   CXXRecordDecl *RD = Destructor->getParent();
8169 
8170   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8171     SourceLocation Loc;
8172 
8173     if (!Destructor->isImplicit())
8174       Loc = Destructor->getLocation();
8175     else
8176       Loc = RD->getLocation();
8177 
8178     // If we have a virtual destructor, look up the deallocation function
8179     if (FunctionDecl *OperatorDelete =
8180             FindDeallocationFunctionForDestructor(Loc, RD)) {
8181       Expr *ThisArg = nullptr;
8182 
8183       // If the notional 'delete this' expression requires a non-trivial
8184       // conversion from 'this' to the type of a destroying operator delete's
8185       // first parameter, perform that conversion now.
8186       if (OperatorDelete->isDestroyingOperatorDelete()) {
8187         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8188         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8189           // C++ [class.dtor]p13:
8190           //   ... as if for the expression 'delete this' appearing in a
8191           //   non-virtual destructor of the destructor's class.
8192           ContextRAII SwitchContext(*this, Destructor);
8193           ExprResult This =
8194               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8195           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8196           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8197           if (This.isInvalid()) {
8198             // FIXME: Register this as a context note so that it comes out
8199             // in the right order.
8200             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8201             return true;
8202           }
8203           ThisArg = This.get();
8204         }
8205       }
8206 
8207       MarkFunctionReferenced(Loc, OperatorDelete);
8208       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8209     }
8210   }
8211 
8212   return false;
8213 }
8214 
8215 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8216 /// the well-formednes of the destructor declarator @p D with type @p
8217 /// R. If there are any errors in the declarator, this routine will
8218 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8219 /// will be updated to reflect a well-formed type for the destructor and
8220 /// returned.
8221 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8222                                          StorageClass& SC) {
8223   // C++ [class.dtor]p1:
8224   //   [...] A typedef-name that names a class is a class-name
8225   //   (7.1.3); however, a typedef-name that names a class shall not
8226   //   be used as the identifier in the declarator for a destructor
8227   //   declaration.
8228   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8229   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8230     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8231       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8232   else if (const TemplateSpecializationType *TST =
8233              DeclaratorType->getAs<TemplateSpecializationType>())
8234     if (TST->isTypeAlias())
8235       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8236         << DeclaratorType << 1;
8237 
8238   // C++ [class.dtor]p2:
8239   //   A destructor is used to destroy objects of its class type. A
8240   //   destructor takes no parameters, and no return type can be
8241   //   specified for it (not even void). The address of a destructor
8242   //   shall not be taken. A destructor shall not be static. A
8243   //   destructor can be invoked for a const, volatile or const
8244   //   volatile object. A destructor shall not be declared const,
8245   //   volatile or const volatile (9.3.2).
8246   if (SC == SC_Static) {
8247     if (!D.isInvalidType())
8248       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8249         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8250         << SourceRange(D.getIdentifierLoc())
8251         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8252 
8253     SC = SC_None;
8254   }
8255   if (!D.isInvalidType()) {
8256     // Destructors don't have return types, but the parser will
8257     // happily parse something like:
8258     //
8259     //   class X {
8260     //     float ~X();
8261     //   };
8262     //
8263     // The return type will be eliminated later.
8264     if (D.getDeclSpec().hasTypeSpecifier())
8265       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8266         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8267         << SourceRange(D.getIdentifierLoc());
8268     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8269       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8270                                 SourceLocation(),
8271                                 D.getDeclSpec().getConstSpecLoc(),
8272                                 D.getDeclSpec().getVolatileSpecLoc(),
8273                                 D.getDeclSpec().getRestrictSpecLoc(),
8274                                 D.getDeclSpec().getAtomicSpecLoc());
8275       D.setInvalidType();
8276     }
8277   }
8278 
8279   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8280   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8281     if (FTI.TypeQuals & Qualifiers::Const)
8282       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8283         << "const" << SourceRange(D.getIdentifierLoc());
8284     if (FTI.TypeQuals & Qualifiers::Volatile)
8285       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8286         << "volatile" << SourceRange(D.getIdentifierLoc());
8287     if (FTI.TypeQuals & Qualifiers::Restrict)
8288       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8289         << "restrict" << SourceRange(D.getIdentifierLoc());
8290     D.setInvalidType();
8291   }
8292 
8293   // C++0x [class.dtor]p2:
8294   //   A destructor shall not be declared with a ref-qualifier.
8295   if (FTI.hasRefQualifier()) {
8296     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8297       << FTI.RefQualifierIsLValueRef
8298       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8299     D.setInvalidType();
8300   }
8301 
8302   // Make sure we don't have any parameters.
8303   if (FTIHasNonVoidParameters(FTI)) {
8304     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8305 
8306     // Delete the parameters.
8307     FTI.freeParams();
8308     D.setInvalidType();
8309   }
8310 
8311   // Make sure the destructor isn't variadic.
8312   if (FTI.isVariadic) {
8313     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8314     D.setInvalidType();
8315   }
8316 
8317   // Rebuild the function type "R" without any type qualifiers or
8318   // parameters (in case any of the errors above fired) and with
8319   // "void" as the return type, since destructors don't have return
8320   // types.
8321   if (!D.isInvalidType())
8322     return R;
8323 
8324   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8325   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8326   EPI.Variadic = false;
8327   EPI.TypeQuals = 0;
8328   EPI.RefQualifier = RQ_None;
8329   return Context.getFunctionType(Context.VoidTy, None, EPI);
8330 }
8331 
8332 static void extendLeft(SourceRange &R, SourceRange Before) {
8333   if (Before.isInvalid())
8334     return;
8335   R.setBegin(Before.getBegin());
8336   if (R.getEnd().isInvalid())
8337     R.setEnd(Before.getEnd());
8338 }
8339 
8340 static void extendRight(SourceRange &R, SourceRange After) {
8341   if (After.isInvalid())
8342     return;
8343   if (R.getBegin().isInvalid())
8344     R.setBegin(After.getBegin());
8345   R.setEnd(After.getEnd());
8346 }
8347 
8348 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8349 /// well-formednes of the conversion function declarator @p D with
8350 /// type @p R. If there are any errors in the declarator, this routine
8351 /// will emit diagnostics and return true. Otherwise, it will return
8352 /// false. Either way, the type @p R will be updated to reflect a
8353 /// well-formed type for the conversion operator.
8354 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8355                                      StorageClass& SC) {
8356   // C++ [class.conv.fct]p1:
8357   //   Neither parameter types nor return type can be specified. The
8358   //   type of a conversion function (8.3.5) is "function taking no
8359   //   parameter returning conversion-type-id."
8360   if (SC == SC_Static) {
8361     if (!D.isInvalidType())
8362       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8363         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8364         << D.getName().getSourceRange();
8365     D.setInvalidType();
8366     SC = SC_None;
8367   }
8368 
8369   TypeSourceInfo *ConvTSI = nullptr;
8370   QualType ConvType =
8371       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8372 
8373   const DeclSpec &DS = D.getDeclSpec();
8374   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8375     // Conversion functions don't have return types, but the parser will
8376     // happily parse something like:
8377     //
8378     //   class X {
8379     //     float operator bool();
8380     //   };
8381     //
8382     // The return type will be changed later anyway.
8383     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8384       << SourceRange(DS.getTypeSpecTypeLoc())
8385       << SourceRange(D.getIdentifierLoc());
8386     D.setInvalidType();
8387   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8388     // It's also plausible that the user writes type qualifiers in the wrong
8389     // place, such as:
8390     //   struct S { const operator int(); };
8391     // FIXME: we could provide a fixit to move the qualifiers onto the
8392     // conversion type.
8393     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8394         << SourceRange(D.getIdentifierLoc()) << 0;
8395     D.setInvalidType();
8396   }
8397 
8398   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8399 
8400   // Make sure we don't have any parameters.
8401   if (Proto->getNumParams() > 0) {
8402     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8403 
8404     // Delete the parameters.
8405     D.getFunctionTypeInfo().freeParams();
8406     D.setInvalidType();
8407   } else if (Proto->isVariadic()) {
8408     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8409     D.setInvalidType();
8410   }
8411 
8412   // Diagnose "&operator bool()" and other such nonsense.  This
8413   // is actually a gcc extension which we don't support.
8414   if (Proto->getReturnType() != ConvType) {
8415     bool NeedsTypedef = false;
8416     SourceRange Before, After;
8417 
8418     // Walk the chunks and extract information on them for our diagnostic.
8419     bool PastFunctionChunk = false;
8420     for (auto &Chunk : D.type_objects()) {
8421       switch (Chunk.Kind) {
8422       case DeclaratorChunk::Function:
8423         if (!PastFunctionChunk) {
8424           if (Chunk.Fun.HasTrailingReturnType) {
8425             TypeSourceInfo *TRT = nullptr;
8426             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8427             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8428           }
8429           PastFunctionChunk = true;
8430           break;
8431         }
8432         LLVM_FALLTHROUGH;
8433       case DeclaratorChunk::Array:
8434         NeedsTypedef = true;
8435         extendRight(After, Chunk.getSourceRange());
8436         break;
8437 
8438       case DeclaratorChunk::Pointer:
8439       case DeclaratorChunk::BlockPointer:
8440       case DeclaratorChunk::Reference:
8441       case DeclaratorChunk::MemberPointer:
8442       case DeclaratorChunk::Pipe:
8443         extendLeft(Before, Chunk.getSourceRange());
8444         break;
8445 
8446       case DeclaratorChunk::Paren:
8447         extendLeft(Before, Chunk.Loc);
8448         extendRight(After, Chunk.EndLoc);
8449         break;
8450       }
8451     }
8452 
8453     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8454                          After.isValid()  ? After.getBegin() :
8455                                             D.getIdentifierLoc();
8456     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8457     DB << Before << After;
8458 
8459     if (!NeedsTypedef) {
8460       DB << /*don't need a typedef*/0;
8461 
8462       // If we can provide a correct fix-it hint, do so.
8463       if (After.isInvalid() && ConvTSI) {
8464         SourceLocation InsertLoc =
8465             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8466         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8467            << FixItHint::CreateInsertionFromRange(
8468                   InsertLoc, CharSourceRange::getTokenRange(Before))
8469            << FixItHint::CreateRemoval(Before);
8470       }
8471     } else if (!Proto->getReturnType()->isDependentType()) {
8472       DB << /*typedef*/1 << Proto->getReturnType();
8473     } else if (getLangOpts().CPlusPlus11) {
8474       DB << /*alias template*/2 << Proto->getReturnType();
8475     } else {
8476       DB << /*might not be fixable*/3;
8477     }
8478 
8479     // Recover by incorporating the other type chunks into the result type.
8480     // Note, this does *not* change the name of the function. This is compatible
8481     // with the GCC extension:
8482     //   struct S { &operator int(); } s;
8483     //   int &r = s.operator int(); // ok in GCC
8484     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8485     ConvType = Proto->getReturnType();
8486   }
8487 
8488   // C++ [class.conv.fct]p4:
8489   //   The conversion-type-id shall not represent a function type nor
8490   //   an array type.
8491   if (ConvType->isArrayType()) {
8492     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8493     ConvType = Context.getPointerType(ConvType);
8494     D.setInvalidType();
8495   } else if (ConvType->isFunctionType()) {
8496     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8497     ConvType = Context.getPointerType(ConvType);
8498     D.setInvalidType();
8499   }
8500 
8501   // Rebuild the function type "R" without any parameters (in case any
8502   // of the errors above fired) and with the conversion type as the
8503   // return type.
8504   if (D.isInvalidType())
8505     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8506 
8507   // C++0x explicit conversion operators.
8508   if (DS.isExplicitSpecified())
8509     Diag(DS.getExplicitSpecLoc(),
8510          getLangOpts().CPlusPlus11
8511              ? diag::warn_cxx98_compat_explicit_conversion_functions
8512              : diag::ext_explicit_conversion_functions)
8513         << SourceRange(DS.getExplicitSpecLoc());
8514 }
8515 
8516 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8517 /// the declaration of the given C++ conversion function. This routine
8518 /// is responsible for recording the conversion function in the C++
8519 /// class, if possible.
8520 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8521   assert(Conversion && "Expected to receive a conversion function declaration");
8522 
8523   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8524 
8525   // Make sure we aren't redeclaring the conversion function.
8526   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8527 
8528   // C++ [class.conv.fct]p1:
8529   //   [...] A conversion function is never used to convert a
8530   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8531   //   same object type (or a reference to it), to a (possibly
8532   //   cv-qualified) base class of that type (or a reference to it),
8533   //   or to (possibly cv-qualified) void.
8534   // FIXME: Suppress this warning if the conversion function ends up being a
8535   // virtual function that overrides a virtual function in a base class.
8536   QualType ClassType
8537     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8538   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8539     ConvType = ConvTypeRef->getPointeeType();
8540   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8541       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8542     /* Suppress diagnostics for instantiations. */;
8543   else if (ConvType->isRecordType()) {
8544     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8545     if (ConvType == ClassType)
8546       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8547         << ClassType;
8548     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8549       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8550         <<  ClassType << ConvType;
8551   } else if (ConvType->isVoidType()) {
8552     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8553       << ClassType << ConvType;
8554   }
8555 
8556   if (FunctionTemplateDecl *ConversionTemplate
8557                                 = Conversion->getDescribedFunctionTemplate())
8558     return ConversionTemplate;
8559 
8560   return Conversion;
8561 }
8562 
8563 namespace {
8564 /// Utility class to accumulate and print a diagnostic listing the invalid
8565 /// specifier(s) on a declaration.
8566 struct BadSpecifierDiagnoser {
8567   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8568       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8569   ~BadSpecifierDiagnoser() {
8570     Diagnostic << Specifiers;
8571   }
8572 
8573   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8574     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8575   }
8576   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8577     return check(SpecLoc,
8578                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8579   }
8580   void check(SourceLocation SpecLoc, const char *Spec) {
8581     if (SpecLoc.isInvalid()) return;
8582     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8583     if (!Specifiers.empty()) Specifiers += " ";
8584     Specifiers += Spec;
8585   }
8586 
8587   Sema &S;
8588   Sema::SemaDiagnosticBuilder Diagnostic;
8589   std::string Specifiers;
8590 };
8591 }
8592 
8593 /// Check the validity of a declarator that we parsed for a deduction-guide.
8594 /// These aren't actually declarators in the grammar, so we need to check that
8595 /// the user didn't specify any pieces that are not part of the deduction-guide
8596 /// grammar.
8597 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8598                                          StorageClass &SC) {
8599   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8600   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8601   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8602 
8603   // C++ [temp.deduct.guide]p3:
8604   //   A deduction-gide shall be declared in the same scope as the
8605   //   corresponding class template.
8606   if (!CurContext->getRedeclContext()->Equals(
8607           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8608     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8609       << GuidedTemplateDecl;
8610     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8611   }
8612 
8613   auto &DS = D.getMutableDeclSpec();
8614   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8615   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8616       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8617       DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8618     BadSpecifierDiagnoser Diagnoser(
8619         *this, D.getIdentifierLoc(),
8620         diag::err_deduction_guide_invalid_specifier);
8621 
8622     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8623     DS.ClearStorageClassSpecs();
8624     SC = SC_None;
8625 
8626     // 'explicit' is permitted.
8627     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8628     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8629     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8630     DS.ClearConstexprSpec();
8631 
8632     Diagnoser.check(DS.getConstSpecLoc(), "const");
8633     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8634     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8635     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8636     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8637     DS.ClearTypeQualifiers();
8638 
8639     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8640     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8641     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8642     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8643     DS.ClearTypeSpecType();
8644   }
8645 
8646   if (D.isInvalidType())
8647     return;
8648 
8649   // Check the declarator is simple enough.
8650   bool FoundFunction = false;
8651   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8652     if (Chunk.Kind == DeclaratorChunk::Paren)
8653       continue;
8654     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8655       Diag(D.getDeclSpec().getLocStart(),
8656           diag::err_deduction_guide_with_complex_decl)
8657         << D.getSourceRange();
8658       break;
8659     }
8660     if (!Chunk.Fun.hasTrailingReturnType()) {
8661       Diag(D.getName().getLocStart(),
8662            diag::err_deduction_guide_no_trailing_return_type);
8663       break;
8664     }
8665 
8666     // Check that the return type is written as a specialization of
8667     // the template specified as the deduction-guide's name.
8668     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8669     TypeSourceInfo *TSI = nullptr;
8670     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8671     assert(TSI && "deduction guide has valid type but invalid return type?");
8672     bool AcceptableReturnType = false;
8673     bool MightInstantiateToSpecialization = false;
8674     if (auto RetTST =
8675             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8676       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8677       bool TemplateMatches =
8678           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8679       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8680         AcceptableReturnType = true;
8681       else {
8682         // This could still instantiate to the right type, unless we know it
8683         // names the wrong class template.
8684         auto *TD = SpecifiedName.getAsTemplateDecl();
8685         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8686                                              !TemplateMatches);
8687       }
8688     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8689       MightInstantiateToSpecialization = true;
8690     }
8691 
8692     if (!AcceptableReturnType) {
8693       Diag(TSI->getTypeLoc().getLocStart(),
8694            diag::err_deduction_guide_bad_trailing_return_type)
8695         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8696         << TSI->getTypeLoc().getSourceRange();
8697     }
8698 
8699     // Keep going to check that we don't have any inner declarator pieces (we
8700     // could still have a function returning a pointer to a function).
8701     FoundFunction = true;
8702   }
8703 
8704   if (D.isFunctionDefinition())
8705     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8706 }
8707 
8708 //===----------------------------------------------------------------------===//
8709 // Namespace Handling
8710 //===----------------------------------------------------------------------===//
8711 
8712 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8713 /// reopened.
8714 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8715                                             SourceLocation Loc,
8716                                             IdentifierInfo *II, bool *IsInline,
8717                                             NamespaceDecl *PrevNS) {
8718   assert(*IsInline != PrevNS->isInline());
8719 
8720   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8721   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8722   // inline namespaces, with the intention of bringing names into namespace std.
8723   //
8724   // We support this just well enough to get that case working; this is not
8725   // sufficient to support reopening namespaces as inline in general.
8726   if (*IsInline && II && II->getName().startswith("__atomic") &&
8727       S.getSourceManager().isInSystemHeader(Loc)) {
8728     // Mark all prior declarations of the namespace as inline.
8729     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8730          NS = NS->getPreviousDecl())
8731       NS->setInline(*IsInline);
8732     // Patch up the lookup table for the containing namespace. This isn't really
8733     // correct, but it's good enough for this particular case.
8734     for (auto *I : PrevNS->decls())
8735       if (auto *ND = dyn_cast<NamedDecl>(I))
8736         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8737     return;
8738   }
8739 
8740   if (PrevNS->isInline())
8741     // The user probably just forgot the 'inline', so suggest that it
8742     // be added back.
8743     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8744       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8745   else
8746     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8747 
8748   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8749   *IsInline = PrevNS->isInline();
8750 }
8751 
8752 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8753 /// definition.
8754 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8755                                    SourceLocation InlineLoc,
8756                                    SourceLocation NamespaceLoc,
8757                                    SourceLocation IdentLoc,
8758                                    IdentifierInfo *II,
8759                                    SourceLocation LBrace,
8760                                    AttributeList *AttrList,
8761                                    UsingDirectiveDecl *&UD) {
8762   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8763   // For anonymous namespace, take the location of the left brace.
8764   SourceLocation Loc = II ? IdentLoc : LBrace;
8765   bool IsInline = InlineLoc.isValid();
8766   bool IsInvalid = false;
8767   bool IsStd = false;
8768   bool AddToKnown = false;
8769   Scope *DeclRegionScope = NamespcScope->getParent();
8770 
8771   NamespaceDecl *PrevNS = nullptr;
8772   if (II) {
8773     // C++ [namespace.def]p2:
8774     //   The identifier in an original-namespace-definition shall not
8775     //   have been previously defined in the declarative region in
8776     //   which the original-namespace-definition appears. The
8777     //   identifier in an original-namespace-definition is the name of
8778     //   the namespace. Subsequently in that declarative region, it is
8779     //   treated as an original-namespace-name.
8780     //
8781     // Since namespace names are unique in their scope, and we don't
8782     // look through using directives, just look for any ordinary names
8783     // as if by qualified name lookup.
8784     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8785                    ForExternalRedeclaration);
8786     LookupQualifiedName(R, CurContext->getRedeclContext());
8787     NamedDecl *PrevDecl =
8788         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8789     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8790 
8791     if (PrevNS) {
8792       // This is an extended namespace definition.
8793       if (IsInline != PrevNS->isInline())
8794         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8795                                         &IsInline, PrevNS);
8796     } else if (PrevDecl) {
8797       // This is an invalid name redefinition.
8798       Diag(Loc, diag::err_redefinition_different_kind)
8799         << II;
8800       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8801       IsInvalid = true;
8802       // Continue on to push Namespc as current DeclContext and return it.
8803     } else if (II->isStr("std") &&
8804                CurContext->getRedeclContext()->isTranslationUnit()) {
8805       // This is the first "real" definition of the namespace "std", so update
8806       // our cache of the "std" namespace to point at this definition.
8807       PrevNS = getStdNamespace();
8808       IsStd = true;
8809       AddToKnown = !IsInline;
8810     } else {
8811       // We've seen this namespace for the first time.
8812       AddToKnown = !IsInline;
8813     }
8814   } else {
8815     // Anonymous namespaces.
8816 
8817     // Determine whether the parent already has an anonymous namespace.
8818     DeclContext *Parent = CurContext->getRedeclContext();
8819     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8820       PrevNS = TU->getAnonymousNamespace();
8821     } else {
8822       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8823       PrevNS = ND->getAnonymousNamespace();
8824     }
8825 
8826     if (PrevNS && IsInline != PrevNS->isInline())
8827       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8828                                       &IsInline, PrevNS);
8829   }
8830 
8831   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8832                                                  StartLoc, Loc, II, PrevNS);
8833   if (IsInvalid)
8834     Namespc->setInvalidDecl();
8835 
8836   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8837   AddPragmaAttributes(DeclRegionScope, Namespc);
8838 
8839   // FIXME: Should we be merging attributes?
8840   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8841     PushNamespaceVisibilityAttr(Attr, Loc);
8842 
8843   if (IsStd)
8844     StdNamespace = Namespc;
8845   if (AddToKnown)
8846     KnownNamespaces[Namespc] = false;
8847 
8848   if (II) {
8849     PushOnScopeChains(Namespc, DeclRegionScope);
8850   } else {
8851     // Link the anonymous namespace into its parent.
8852     DeclContext *Parent = CurContext->getRedeclContext();
8853     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8854       TU->setAnonymousNamespace(Namespc);
8855     } else {
8856       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8857     }
8858 
8859     CurContext->addDecl(Namespc);
8860 
8861     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8862     //   behaves as if it were replaced by
8863     //     namespace unique { /* empty body */ }
8864     //     using namespace unique;
8865     //     namespace unique { namespace-body }
8866     //   where all occurrences of 'unique' in a translation unit are
8867     //   replaced by the same identifier and this identifier differs
8868     //   from all other identifiers in the entire program.
8869 
8870     // We just create the namespace with an empty name and then add an
8871     // implicit using declaration, just like the standard suggests.
8872     //
8873     // CodeGen enforces the "universally unique" aspect by giving all
8874     // declarations semantically contained within an anonymous
8875     // namespace internal linkage.
8876 
8877     if (!PrevNS) {
8878       UD = UsingDirectiveDecl::Create(Context, Parent,
8879                                       /* 'using' */ LBrace,
8880                                       /* 'namespace' */ SourceLocation(),
8881                                       /* qualifier */ NestedNameSpecifierLoc(),
8882                                       /* identifier */ SourceLocation(),
8883                                       Namespc,
8884                                       /* Ancestor */ Parent);
8885       UD->setImplicit();
8886       Parent->addDecl(UD);
8887     }
8888   }
8889 
8890   ActOnDocumentableDecl(Namespc);
8891 
8892   // Although we could have an invalid decl (i.e. the namespace name is a
8893   // redefinition), push it as current DeclContext and try to continue parsing.
8894   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8895   // for the namespace has the declarations that showed up in that particular
8896   // namespace definition.
8897   PushDeclContext(NamespcScope, Namespc);
8898   return Namespc;
8899 }
8900 
8901 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8902 /// is a namespace alias, returns the namespace it points to.
8903 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8904   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8905     return AD->getNamespace();
8906   return dyn_cast_or_null<NamespaceDecl>(D);
8907 }
8908 
8909 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8910 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8911 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8912   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8913   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8914   Namespc->setRBraceLoc(RBrace);
8915   PopDeclContext();
8916   if (Namespc->hasAttr<VisibilityAttr>())
8917     PopPragmaVisibility(true, RBrace);
8918 }
8919 
8920 CXXRecordDecl *Sema::getStdBadAlloc() const {
8921   return cast_or_null<CXXRecordDecl>(
8922                                   StdBadAlloc.get(Context.getExternalSource()));
8923 }
8924 
8925 EnumDecl *Sema::getStdAlignValT() const {
8926   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8927 }
8928 
8929 NamespaceDecl *Sema::getStdNamespace() const {
8930   return cast_or_null<NamespaceDecl>(
8931                                  StdNamespace.get(Context.getExternalSource()));
8932 }
8933 
8934 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8935   if (!StdExperimentalNamespaceCache) {
8936     if (auto Std = getStdNamespace()) {
8937       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8938                           SourceLocation(), LookupNamespaceName);
8939       if (!LookupQualifiedName(Result, Std) ||
8940           !(StdExperimentalNamespaceCache =
8941                 Result.getAsSingle<NamespaceDecl>()))
8942         Result.suppressDiagnostics();
8943     }
8944   }
8945   return StdExperimentalNamespaceCache;
8946 }
8947 
8948 namespace {
8949 
8950 enum UnsupportedSTLSelect {
8951   USS_InvalidMember,
8952   USS_MissingMember,
8953   USS_NonTrivial,
8954   USS_Other
8955 };
8956 
8957 struct InvalidSTLDiagnoser {
8958   Sema &S;
8959   SourceLocation Loc;
8960   QualType TyForDiags;
8961 
8962   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
8963                       const VarDecl *VD = nullptr) {
8964     {
8965       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
8966                << TyForDiags << ((int)Sel);
8967       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
8968         assert(!Name.empty());
8969         D << Name;
8970       }
8971     }
8972     if (Sel == USS_InvalidMember) {
8973       S.Diag(VD->getLocation(), diag::note_var_declared_here)
8974           << VD << VD->getSourceRange();
8975     }
8976     return QualType();
8977   }
8978 };
8979 } // namespace
8980 
8981 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
8982                                            SourceLocation Loc) {
8983   assert(getLangOpts().CPlusPlus &&
8984          "Looking for comparison category type outside of C++.");
8985 
8986   // Check if we've already successfully checked the comparison category type
8987   // before. If so, skip checking it again.
8988   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
8989   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
8990     return Info->getType();
8991 
8992   // If lookup failed
8993   if (!Info) {
8994     std::string NameForDiags = "std::";
8995     NameForDiags += ComparisonCategories::getCategoryString(Kind);
8996     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
8997         << NameForDiags;
8998     return QualType();
8999   }
9000 
9001   assert(Info->Kind == Kind);
9002   assert(Info->Record);
9003 
9004   // Update the Record decl in case we encountered a forward declaration on our
9005   // first pass. FIXME: This is a bit of a hack.
9006   if (Info->Record->hasDefinition())
9007     Info->Record = Info->Record->getDefinition();
9008 
9009   // Use an elaborated type for diagnostics which has a name containing the
9010   // prepended 'std' namespace but not any inline namespace names.
9011   QualType TyForDiags = [&]() {
9012     auto *NNS =
9013         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9014     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9015   }();
9016 
9017   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9018     return QualType();
9019 
9020   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9021 
9022   if (!Info->Record->isTriviallyCopyable())
9023     return UnsupportedSTLError(USS_NonTrivial);
9024 
9025   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9026     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9027     // Tolerate empty base classes.
9028     if (Base->isEmpty())
9029       continue;
9030     // Reject STL implementations which have at least one non-empty base.
9031     return UnsupportedSTLError();
9032   }
9033 
9034   // Check that the STL has implemented the types using a single integer field.
9035   // This expectation allows better codegen for builtin operators. We require:
9036   //   (1) The class has exactly one field.
9037   //   (2) The field is an integral or enumeration type.
9038   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9039   if (std::distance(FIt, FEnd) != 1 ||
9040       !FIt->getType()->isIntegralOrEnumerationType()) {
9041     return UnsupportedSTLError();
9042   }
9043 
9044   // Build each of the require values and store them in Info.
9045   for (ComparisonCategoryResult CCR :
9046        ComparisonCategories::getPossibleResultsForType(Kind)) {
9047     StringRef MemName = ComparisonCategories::getResultString(CCR);
9048     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9049 
9050     if (!ValInfo)
9051       return UnsupportedSTLError(USS_MissingMember, MemName);
9052 
9053     VarDecl *VD = ValInfo->VD;
9054     assert(VD && "should not be null!");
9055 
9056     // Attempt to diagnose reasons why the STL definition of this type
9057     // might be foobar, including it failing to be a constant expression.
9058     // TODO Handle more ways the lookup or result can be invalid.
9059     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9060         !VD->checkInitIsICE())
9061       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9062 
9063     // Attempt to evaluate the var decl as a constant expression and extract
9064     // the value of its first field as a ICE. If this fails, the STL
9065     // implementation is not supported.
9066     if (!ValInfo->hasValidIntValue())
9067       return UnsupportedSTLError();
9068 
9069     MarkVariableReferenced(Loc, VD);
9070   }
9071 
9072   // We've successfully built the required types and expressions. Update
9073   // the cache and return the newly cached value.
9074   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9075   return Info->getType();
9076 }
9077 
9078 /// Retrieve the special "std" namespace, which may require us to
9079 /// implicitly define the namespace.
9080 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9081   if (!StdNamespace) {
9082     // The "std" namespace has not yet been defined, so build one implicitly.
9083     StdNamespace = NamespaceDecl::Create(Context,
9084                                          Context.getTranslationUnitDecl(),
9085                                          /*Inline=*/false,
9086                                          SourceLocation(), SourceLocation(),
9087                                          &PP.getIdentifierTable().get("std"),
9088                                          /*PrevDecl=*/nullptr);
9089     getStdNamespace()->setImplicit(true);
9090   }
9091 
9092   return getStdNamespace();
9093 }
9094 
9095 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9096   assert(getLangOpts().CPlusPlus &&
9097          "Looking for std::initializer_list outside of C++.");
9098 
9099   // We're looking for implicit instantiations of
9100   // template <typename E> class std::initializer_list.
9101 
9102   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9103     return false;
9104 
9105   ClassTemplateDecl *Template = nullptr;
9106   const TemplateArgument *Arguments = nullptr;
9107 
9108   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9109 
9110     ClassTemplateSpecializationDecl *Specialization =
9111         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9112     if (!Specialization)
9113       return false;
9114 
9115     Template = Specialization->getSpecializedTemplate();
9116     Arguments = Specialization->getTemplateArgs().data();
9117   } else if (const TemplateSpecializationType *TST =
9118                  Ty->getAs<TemplateSpecializationType>()) {
9119     Template = dyn_cast_or_null<ClassTemplateDecl>(
9120         TST->getTemplateName().getAsTemplateDecl());
9121     Arguments = TST->getArgs();
9122   }
9123   if (!Template)
9124     return false;
9125 
9126   if (!StdInitializerList) {
9127     // Haven't recognized std::initializer_list yet, maybe this is it.
9128     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9129     if (TemplateClass->getIdentifier() !=
9130             &PP.getIdentifierTable().get("initializer_list") ||
9131         !getStdNamespace()->InEnclosingNamespaceSetOf(
9132             TemplateClass->getDeclContext()))
9133       return false;
9134     // This is a template called std::initializer_list, but is it the right
9135     // template?
9136     TemplateParameterList *Params = Template->getTemplateParameters();
9137     if (Params->getMinRequiredArguments() != 1)
9138       return false;
9139     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9140       return false;
9141 
9142     // It's the right template.
9143     StdInitializerList = Template;
9144   }
9145 
9146   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9147     return false;
9148 
9149   // This is an instance of std::initializer_list. Find the argument type.
9150   if (Element)
9151     *Element = Arguments[0].getAsType();
9152   return true;
9153 }
9154 
9155 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9156   NamespaceDecl *Std = S.getStdNamespace();
9157   if (!Std) {
9158     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9159     return nullptr;
9160   }
9161 
9162   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9163                       Loc, Sema::LookupOrdinaryName);
9164   if (!S.LookupQualifiedName(Result, Std)) {
9165     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9166     return nullptr;
9167   }
9168   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9169   if (!Template) {
9170     Result.suppressDiagnostics();
9171     // We found something weird. Complain about the first thing we found.
9172     NamedDecl *Found = *Result.begin();
9173     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9174     return nullptr;
9175   }
9176 
9177   // We found some template called std::initializer_list. Now verify that it's
9178   // correct.
9179   TemplateParameterList *Params = Template->getTemplateParameters();
9180   if (Params->getMinRequiredArguments() != 1 ||
9181       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9182     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9183     return nullptr;
9184   }
9185 
9186   return Template;
9187 }
9188 
9189 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9190   if (!StdInitializerList) {
9191     StdInitializerList = LookupStdInitializerList(*this, Loc);
9192     if (!StdInitializerList)
9193       return QualType();
9194   }
9195 
9196   TemplateArgumentListInfo Args(Loc, Loc);
9197   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9198                                        Context.getTrivialTypeSourceInfo(Element,
9199                                                                         Loc)));
9200   return Context.getCanonicalType(
9201       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9202 }
9203 
9204 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9205   // C++ [dcl.init.list]p2:
9206   //   A constructor is an initializer-list constructor if its first parameter
9207   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9208   //   std::initializer_list<E> for some type E, and either there are no other
9209   //   parameters or else all other parameters have default arguments.
9210   if (Ctor->getNumParams() < 1 ||
9211       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9212     return false;
9213 
9214   QualType ArgType = Ctor->getParamDecl(0)->getType();
9215   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9216     ArgType = RT->getPointeeType().getUnqualifiedType();
9217 
9218   return isStdInitializerList(ArgType, nullptr);
9219 }
9220 
9221 /// Determine whether a using statement is in a context where it will be
9222 /// apply in all contexts.
9223 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9224   switch (CurContext->getDeclKind()) {
9225     case Decl::TranslationUnit:
9226       return true;
9227     case Decl::LinkageSpec:
9228       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9229     default:
9230       return false;
9231   }
9232 }
9233 
9234 namespace {
9235 
9236 // Callback to only accept typo corrections that are namespaces.
9237 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9238 public:
9239   bool ValidateCandidate(const TypoCorrection &candidate) override {
9240     if (NamedDecl *ND = candidate.getCorrectionDecl())
9241       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9242     return false;
9243   }
9244 };
9245 
9246 }
9247 
9248 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9249                                        CXXScopeSpec &SS,
9250                                        SourceLocation IdentLoc,
9251                                        IdentifierInfo *Ident) {
9252   R.clear();
9253   if (TypoCorrection Corrected =
9254           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9255                         llvm::make_unique<NamespaceValidatorCCC>(),
9256                         Sema::CTK_ErrorRecovery)) {
9257     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9258       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9259       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9260                               Ident->getName().equals(CorrectedStr);
9261       S.diagnoseTypo(Corrected,
9262                      S.PDiag(diag::err_using_directive_member_suggest)
9263                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9264                      S.PDiag(diag::note_namespace_defined_here));
9265     } else {
9266       S.diagnoseTypo(Corrected,
9267                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9268                      S.PDiag(diag::note_namespace_defined_here));
9269     }
9270     R.addDecl(Corrected.getFoundDecl());
9271     return true;
9272   }
9273   return false;
9274 }
9275 
9276 Decl *Sema::ActOnUsingDirective(Scope *S,
9277                                           SourceLocation UsingLoc,
9278                                           SourceLocation NamespcLoc,
9279                                           CXXScopeSpec &SS,
9280                                           SourceLocation IdentLoc,
9281                                           IdentifierInfo *NamespcName,
9282                                           AttributeList *AttrList) {
9283   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9284   assert(NamespcName && "Invalid NamespcName.");
9285   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9286 
9287   // This can only happen along a recovery path.
9288   while (S->isTemplateParamScope())
9289     S = S->getParent();
9290   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9291 
9292   UsingDirectiveDecl *UDir = nullptr;
9293   NestedNameSpecifier *Qualifier = nullptr;
9294   if (SS.isSet())
9295     Qualifier = SS.getScopeRep();
9296 
9297   // Lookup namespace name.
9298   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9299   LookupParsedName(R, S, &SS);
9300   if (R.isAmbiguous())
9301     return nullptr;
9302 
9303   if (R.empty()) {
9304     R.clear();
9305     // Allow "using namespace std;" or "using namespace ::std;" even if
9306     // "std" hasn't been defined yet, for GCC compatibility.
9307     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9308         NamespcName->isStr("std")) {
9309       Diag(IdentLoc, diag::ext_using_undefined_std);
9310       R.addDecl(getOrCreateStdNamespace());
9311       R.resolveKind();
9312     }
9313     // Otherwise, attempt typo correction.
9314     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9315   }
9316 
9317   if (!R.empty()) {
9318     NamedDecl *Named = R.getRepresentativeDecl();
9319     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9320     assert(NS && "expected namespace decl");
9321 
9322     // The use of a nested name specifier may trigger deprecation warnings.
9323     DiagnoseUseOfDecl(Named, IdentLoc);
9324 
9325     // C++ [namespace.udir]p1:
9326     //   A using-directive specifies that the names in the nominated
9327     //   namespace can be used in the scope in which the
9328     //   using-directive appears after the using-directive. During
9329     //   unqualified name lookup (3.4.1), the names appear as if they
9330     //   were declared in the nearest enclosing namespace which
9331     //   contains both the using-directive and the nominated
9332     //   namespace. [Note: in this context, "contains" means "contains
9333     //   directly or indirectly". ]
9334 
9335     // Find enclosing context containing both using-directive and
9336     // nominated namespace.
9337     DeclContext *CommonAncestor = NS;
9338     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9339       CommonAncestor = CommonAncestor->getParent();
9340 
9341     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9342                                       SS.getWithLocInContext(Context),
9343                                       IdentLoc, Named, CommonAncestor);
9344 
9345     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9346         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9347       Diag(IdentLoc, diag::warn_using_directive_in_header);
9348     }
9349 
9350     PushUsingDirective(S, UDir);
9351   } else {
9352     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9353   }
9354 
9355   if (UDir)
9356     ProcessDeclAttributeList(S, UDir, AttrList);
9357 
9358   return UDir;
9359 }
9360 
9361 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9362   // If the scope has an associated entity and the using directive is at
9363   // namespace or translation unit scope, add the UsingDirectiveDecl into
9364   // its lookup structure so qualified name lookup can find it.
9365   DeclContext *Ctx = S->getEntity();
9366   if (Ctx && !Ctx->isFunctionOrMethod())
9367     Ctx->addDecl(UDir);
9368   else
9369     // Otherwise, it is at block scope. The using-directives will affect lookup
9370     // only to the end of the scope.
9371     S->PushUsingDirective(UDir);
9372 }
9373 
9374 
9375 Decl *Sema::ActOnUsingDeclaration(Scope *S,
9376                                   AccessSpecifier AS,
9377                                   SourceLocation UsingLoc,
9378                                   SourceLocation TypenameLoc,
9379                                   CXXScopeSpec &SS,
9380                                   UnqualifiedId &Name,
9381                                   SourceLocation EllipsisLoc,
9382                                   AttributeList *AttrList) {
9383   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9384 
9385   if (SS.isEmpty()) {
9386     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
9387     return nullptr;
9388   }
9389 
9390   switch (Name.getKind()) {
9391   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9392   case UnqualifiedIdKind::IK_Identifier:
9393   case UnqualifiedIdKind::IK_OperatorFunctionId:
9394   case UnqualifiedIdKind::IK_LiteralOperatorId:
9395   case UnqualifiedIdKind::IK_ConversionFunctionId:
9396     break;
9397 
9398   case UnqualifiedIdKind::IK_ConstructorName:
9399   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9400     // C++11 inheriting constructors.
9401     Diag(Name.getLocStart(),
9402          getLangOpts().CPlusPlus11 ?
9403            diag::warn_cxx98_compat_using_decl_constructor :
9404            diag::err_using_decl_constructor)
9405       << SS.getRange();
9406 
9407     if (getLangOpts().CPlusPlus11) break;
9408 
9409     return nullptr;
9410 
9411   case UnqualifiedIdKind::IK_DestructorName:
9412     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9413       << SS.getRange();
9414     return nullptr;
9415 
9416   case UnqualifiedIdKind::IK_TemplateId:
9417     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9418       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9419     return nullptr;
9420 
9421   case UnqualifiedIdKind::IK_DeductionGuideName:
9422     llvm_unreachable("cannot parse qualified deduction guide name");
9423   }
9424 
9425   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9426   DeclarationName TargetName = TargetNameInfo.getName();
9427   if (!TargetName)
9428     return nullptr;
9429 
9430   // Warn about access declarations.
9431   if (UsingLoc.isInvalid()) {
9432     Diag(Name.getLocStart(),
9433          getLangOpts().CPlusPlus11 ? diag::err_access_decl
9434                                    : diag::warn_access_decl_deprecated)
9435       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9436   }
9437 
9438   if (EllipsisLoc.isInvalid()) {
9439     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9440         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9441       return nullptr;
9442   } else {
9443     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9444         !TargetNameInfo.containsUnexpandedParameterPack()) {
9445       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9446         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9447       EllipsisLoc = SourceLocation();
9448     }
9449   }
9450 
9451   NamedDecl *UD =
9452       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9453                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9454                             /*IsInstantiation*/false);
9455   if (UD)
9456     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9457 
9458   return UD;
9459 }
9460 
9461 /// Determine whether a using declaration considers the given
9462 /// declarations as "equivalent", e.g., if they are redeclarations of
9463 /// the same entity or are both typedefs of the same type.
9464 static bool
9465 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9466   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9467     return true;
9468 
9469   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9470     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9471       return Context.hasSameType(TD1->getUnderlyingType(),
9472                                  TD2->getUnderlyingType());
9473 
9474   return false;
9475 }
9476 
9477 
9478 /// Determines whether to create a using shadow decl for a particular
9479 /// decl, given the set of decls existing prior to this using lookup.
9480 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9481                                 const LookupResult &Previous,
9482                                 UsingShadowDecl *&PrevShadow) {
9483   // Diagnose finding a decl which is not from a base class of the
9484   // current class.  We do this now because there are cases where this
9485   // function will silently decide not to build a shadow decl, which
9486   // will pre-empt further diagnostics.
9487   //
9488   // We don't need to do this in C++11 because we do the check once on
9489   // the qualifier.
9490   //
9491   // FIXME: diagnose the following if we care enough:
9492   //   struct A { int foo; };
9493   //   struct B : A { using A::foo; };
9494   //   template <class T> struct C : A {};
9495   //   template <class T> struct D : C<T> { using B::foo; } // <---
9496   // This is invalid (during instantiation) in C++03 because B::foo
9497   // resolves to the using decl in B, which is not a base class of D<T>.
9498   // We can't diagnose it immediately because C<T> is an unknown
9499   // specialization.  The UsingShadowDecl in D<T> then points directly
9500   // to A::foo, which will look well-formed when we instantiate.
9501   // The right solution is to not collapse the shadow-decl chain.
9502   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9503     DeclContext *OrigDC = Orig->getDeclContext();
9504 
9505     // Handle enums and anonymous structs.
9506     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9507     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9508     while (OrigRec->isAnonymousStructOrUnion())
9509       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9510 
9511     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9512       if (OrigDC == CurContext) {
9513         Diag(Using->getLocation(),
9514              diag::err_using_decl_nested_name_specifier_is_current_class)
9515           << Using->getQualifierLoc().getSourceRange();
9516         Diag(Orig->getLocation(), diag::note_using_decl_target);
9517         Using->setInvalidDecl();
9518         return true;
9519       }
9520 
9521       Diag(Using->getQualifierLoc().getBeginLoc(),
9522            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9523         << Using->getQualifier()
9524         << cast<CXXRecordDecl>(CurContext)
9525         << Using->getQualifierLoc().getSourceRange();
9526       Diag(Orig->getLocation(), diag::note_using_decl_target);
9527       Using->setInvalidDecl();
9528       return true;
9529     }
9530   }
9531 
9532   if (Previous.empty()) return false;
9533 
9534   NamedDecl *Target = Orig;
9535   if (isa<UsingShadowDecl>(Target))
9536     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9537 
9538   // If the target happens to be one of the previous declarations, we
9539   // don't have a conflict.
9540   //
9541   // FIXME: but we might be increasing its access, in which case we
9542   // should redeclare it.
9543   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9544   bool FoundEquivalentDecl = false;
9545   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9546          I != E; ++I) {
9547     NamedDecl *D = (*I)->getUnderlyingDecl();
9548     // We can have UsingDecls in our Previous results because we use the same
9549     // LookupResult for checking whether the UsingDecl itself is a valid
9550     // redeclaration.
9551     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9552       continue;
9553 
9554     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9555       // C++ [class.mem]p19:
9556       //   If T is the name of a class, then [every named member other than
9557       //   a non-static data member] shall have a name different from T
9558       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9559           !isa<IndirectFieldDecl>(Target) &&
9560           !isa<UnresolvedUsingValueDecl>(Target) &&
9561           DiagnoseClassNameShadow(
9562               CurContext,
9563               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9564         return true;
9565     }
9566 
9567     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9568       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9569         PrevShadow = Shadow;
9570       FoundEquivalentDecl = true;
9571     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9572       // We don't conflict with an existing using shadow decl of an equivalent
9573       // declaration, but we're not a redeclaration of it.
9574       FoundEquivalentDecl = true;
9575     }
9576 
9577     if (isVisible(D))
9578       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9579   }
9580 
9581   if (FoundEquivalentDecl)
9582     return false;
9583 
9584   if (FunctionDecl *FD = Target->getAsFunction()) {
9585     NamedDecl *OldDecl = nullptr;
9586     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9587                           /*IsForUsingDecl*/ true)) {
9588     case Ovl_Overload:
9589       return false;
9590 
9591     case Ovl_NonFunction:
9592       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9593       break;
9594 
9595     // We found a decl with the exact signature.
9596     case Ovl_Match:
9597       // If we're in a record, we want to hide the target, so we
9598       // return true (without a diagnostic) to tell the caller not to
9599       // build a shadow decl.
9600       if (CurContext->isRecord())
9601         return true;
9602 
9603       // If we're not in a record, this is an error.
9604       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9605       break;
9606     }
9607 
9608     Diag(Target->getLocation(), diag::note_using_decl_target);
9609     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9610     Using->setInvalidDecl();
9611     return true;
9612   }
9613 
9614   // Target is not a function.
9615 
9616   if (isa<TagDecl>(Target)) {
9617     // No conflict between a tag and a non-tag.
9618     if (!Tag) return false;
9619 
9620     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9621     Diag(Target->getLocation(), diag::note_using_decl_target);
9622     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9623     Using->setInvalidDecl();
9624     return true;
9625   }
9626 
9627   // No conflict between a tag and a non-tag.
9628   if (!NonTag) return false;
9629 
9630   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9631   Diag(Target->getLocation(), diag::note_using_decl_target);
9632   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9633   Using->setInvalidDecl();
9634   return true;
9635 }
9636 
9637 /// Determine whether a direct base class is a virtual base class.
9638 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9639   if (!Derived->getNumVBases())
9640     return false;
9641   for (auto &B : Derived->bases())
9642     if (B.getType()->getAsCXXRecordDecl() == Base)
9643       return B.isVirtual();
9644   llvm_unreachable("not a direct base class");
9645 }
9646 
9647 /// Builds a shadow declaration corresponding to a 'using' declaration.
9648 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9649                                             UsingDecl *UD,
9650                                             NamedDecl *Orig,
9651                                             UsingShadowDecl *PrevDecl) {
9652   // If we resolved to another shadow declaration, just coalesce them.
9653   NamedDecl *Target = Orig;
9654   if (isa<UsingShadowDecl>(Target)) {
9655     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9656     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9657   }
9658 
9659   NamedDecl *NonTemplateTarget = Target;
9660   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9661     NonTemplateTarget = TargetTD->getTemplatedDecl();
9662 
9663   UsingShadowDecl *Shadow;
9664   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9665     bool IsVirtualBase =
9666         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9667                             UD->getQualifier()->getAsRecordDecl());
9668     Shadow = ConstructorUsingShadowDecl::Create(
9669         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9670   } else {
9671     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9672                                      Target);
9673   }
9674   UD->addShadowDecl(Shadow);
9675 
9676   Shadow->setAccess(UD->getAccess());
9677   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9678     Shadow->setInvalidDecl();
9679 
9680   Shadow->setPreviousDecl(PrevDecl);
9681 
9682   if (S)
9683     PushOnScopeChains(Shadow, S);
9684   else
9685     CurContext->addDecl(Shadow);
9686 
9687 
9688   return Shadow;
9689 }
9690 
9691 /// Hides a using shadow declaration.  This is required by the current
9692 /// using-decl implementation when a resolvable using declaration in a
9693 /// class is followed by a declaration which would hide or override
9694 /// one or more of the using decl's targets; for example:
9695 ///
9696 ///   struct Base { void foo(int); };
9697 ///   struct Derived : Base {
9698 ///     using Base::foo;
9699 ///     void foo(int);
9700 ///   };
9701 ///
9702 /// The governing language is C++03 [namespace.udecl]p12:
9703 ///
9704 ///   When a using-declaration brings names from a base class into a
9705 ///   derived class scope, member functions in the derived class
9706 ///   override and/or hide member functions with the same name and
9707 ///   parameter types in a base class (rather than conflicting).
9708 ///
9709 /// There are two ways to implement this:
9710 ///   (1) optimistically create shadow decls when they're not hidden
9711 ///       by existing declarations, or
9712 ///   (2) don't create any shadow decls (or at least don't make them
9713 ///       visible) until we've fully parsed/instantiated the class.
9714 /// The problem with (1) is that we might have to retroactively remove
9715 /// a shadow decl, which requires several O(n) operations because the
9716 /// decl structures are (very reasonably) not designed for removal.
9717 /// (2) avoids this but is very fiddly and phase-dependent.
9718 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9719   if (Shadow->getDeclName().getNameKind() ==
9720         DeclarationName::CXXConversionFunctionName)
9721     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9722 
9723   // Remove it from the DeclContext...
9724   Shadow->getDeclContext()->removeDecl(Shadow);
9725 
9726   // ...and the scope, if applicable...
9727   if (S) {
9728     S->RemoveDecl(Shadow);
9729     IdResolver.RemoveDecl(Shadow);
9730   }
9731 
9732   // ...and the using decl.
9733   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9734 
9735   // TODO: complain somehow if Shadow was used.  It shouldn't
9736   // be possible for this to happen, because...?
9737 }
9738 
9739 /// Find the base specifier for a base class with the given type.
9740 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9741                                                 QualType DesiredBase,
9742                                                 bool &AnyDependentBases) {
9743   // Check whether the named type is a direct base class.
9744   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9745   for (auto &Base : Derived->bases()) {
9746     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9747     if (CanonicalDesiredBase == BaseType)
9748       return &Base;
9749     if (BaseType->isDependentType())
9750       AnyDependentBases = true;
9751   }
9752   return nullptr;
9753 }
9754 
9755 namespace {
9756 class UsingValidatorCCC : public CorrectionCandidateCallback {
9757 public:
9758   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9759                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9760       : HasTypenameKeyword(HasTypenameKeyword),
9761         IsInstantiation(IsInstantiation), OldNNS(NNS),
9762         RequireMemberOf(RequireMemberOf) {}
9763 
9764   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9765     NamedDecl *ND = Candidate.getCorrectionDecl();
9766 
9767     // Keywords are not valid here.
9768     if (!ND || isa<NamespaceDecl>(ND))
9769       return false;
9770 
9771     // Completely unqualified names are invalid for a 'using' declaration.
9772     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9773       return false;
9774 
9775     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9776     // reject.
9777 
9778     if (RequireMemberOf) {
9779       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9780       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9781         // No-one ever wants a using-declaration to name an injected-class-name
9782         // of a base class, unless they're declaring an inheriting constructor.
9783         ASTContext &Ctx = ND->getASTContext();
9784         if (!Ctx.getLangOpts().CPlusPlus11)
9785           return false;
9786         QualType FoundType = Ctx.getRecordType(FoundRecord);
9787 
9788         // Check that the injected-class-name is named as a member of its own
9789         // type; we don't want to suggest 'using Derived::Base;', since that
9790         // means something else.
9791         NestedNameSpecifier *Specifier =
9792             Candidate.WillReplaceSpecifier()
9793                 ? Candidate.getCorrectionSpecifier()
9794                 : OldNNS;
9795         if (!Specifier->getAsType() ||
9796             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9797           return false;
9798 
9799         // Check that this inheriting constructor declaration actually names a
9800         // direct base class of the current class.
9801         bool AnyDependentBases = false;
9802         if (!findDirectBaseWithType(RequireMemberOf,
9803                                     Ctx.getRecordType(FoundRecord),
9804                                     AnyDependentBases) &&
9805             !AnyDependentBases)
9806           return false;
9807       } else {
9808         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9809         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9810           return false;
9811 
9812         // FIXME: Check that the base class member is accessible?
9813       }
9814     } else {
9815       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9816       if (FoundRecord && FoundRecord->isInjectedClassName())
9817         return false;
9818     }
9819 
9820     if (isa<TypeDecl>(ND))
9821       return HasTypenameKeyword || !IsInstantiation;
9822 
9823     return !HasTypenameKeyword;
9824   }
9825 
9826 private:
9827   bool HasTypenameKeyword;
9828   bool IsInstantiation;
9829   NestedNameSpecifier *OldNNS;
9830   CXXRecordDecl *RequireMemberOf;
9831 };
9832 } // end anonymous namespace
9833 
9834 /// Builds a using declaration.
9835 ///
9836 /// \param IsInstantiation - Whether this call arises from an
9837 ///   instantiation of an unresolved using declaration.  We treat
9838 ///   the lookup differently for these declarations.
9839 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9840                                        SourceLocation UsingLoc,
9841                                        bool HasTypenameKeyword,
9842                                        SourceLocation TypenameLoc,
9843                                        CXXScopeSpec &SS,
9844                                        DeclarationNameInfo NameInfo,
9845                                        SourceLocation EllipsisLoc,
9846                                        AttributeList *AttrList,
9847                                        bool IsInstantiation) {
9848   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9849   SourceLocation IdentLoc = NameInfo.getLoc();
9850   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9851 
9852   // FIXME: We ignore attributes for now.
9853 
9854   // For an inheriting constructor declaration, the name of the using
9855   // declaration is the name of a constructor in this class, not in the
9856   // base class.
9857   DeclarationNameInfo UsingName = NameInfo;
9858   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9859     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9860       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9861           Context.getCanonicalType(Context.getRecordType(RD))));
9862 
9863   // Do the redeclaration lookup in the current scope.
9864   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9865                         ForVisibleRedeclaration);
9866   Previous.setHideTags(false);
9867   if (S) {
9868     LookupName(Previous, S);
9869 
9870     // It is really dumb that we have to do this.
9871     LookupResult::Filter F = Previous.makeFilter();
9872     while (F.hasNext()) {
9873       NamedDecl *D = F.next();
9874       if (!isDeclInScope(D, CurContext, S))
9875         F.erase();
9876       // If we found a local extern declaration that's not ordinarily visible,
9877       // and this declaration is being added to a non-block scope, ignore it.
9878       // We're only checking for scope conflicts here, not also for violations
9879       // of the linkage rules.
9880       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9881                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9882         F.erase();
9883     }
9884     F.done();
9885   } else {
9886     assert(IsInstantiation && "no scope in non-instantiation");
9887     if (CurContext->isRecord())
9888       LookupQualifiedName(Previous, CurContext);
9889     else {
9890       // No redeclaration check is needed here; in non-member contexts we
9891       // diagnosed all possible conflicts with other using-declarations when
9892       // building the template:
9893       //
9894       // For a dependent non-type using declaration, the only valid case is
9895       // if we instantiate to a single enumerator. We check for conflicts
9896       // between shadow declarations we introduce, and we check in the template
9897       // definition for conflicts between a non-type using declaration and any
9898       // other declaration, which together covers all cases.
9899       //
9900       // A dependent typename using declaration will never successfully
9901       // instantiate, since it will always name a class member, so we reject
9902       // that in the template definition.
9903     }
9904   }
9905 
9906   // Check for invalid redeclarations.
9907   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9908                                   SS, IdentLoc, Previous))
9909     return nullptr;
9910 
9911   // Check for bad qualifiers.
9912   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9913                               IdentLoc))
9914     return nullptr;
9915 
9916   DeclContext *LookupContext = computeDeclContext(SS);
9917   NamedDecl *D;
9918   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9919   if (!LookupContext || EllipsisLoc.isValid()) {
9920     if (HasTypenameKeyword) {
9921       // FIXME: not all declaration name kinds are legal here
9922       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9923                                               UsingLoc, TypenameLoc,
9924                                               QualifierLoc,
9925                                               IdentLoc, NameInfo.getName(),
9926                                               EllipsisLoc);
9927     } else {
9928       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9929                                            QualifierLoc, NameInfo, EllipsisLoc);
9930     }
9931     D->setAccess(AS);
9932     CurContext->addDecl(D);
9933     return D;
9934   }
9935 
9936   auto Build = [&](bool Invalid) {
9937     UsingDecl *UD =
9938         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9939                           UsingName, HasTypenameKeyword);
9940     UD->setAccess(AS);
9941     CurContext->addDecl(UD);
9942     UD->setInvalidDecl(Invalid);
9943     return UD;
9944   };
9945   auto BuildInvalid = [&]{ return Build(true); };
9946   auto BuildValid = [&]{ return Build(false); };
9947 
9948   if (RequireCompleteDeclContext(SS, LookupContext))
9949     return BuildInvalid();
9950 
9951   // Look up the target name.
9952   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9953 
9954   // Unlike most lookups, we don't always want to hide tag
9955   // declarations: tag names are visible through the using declaration
9956   // even if hidden by ordinary names, *except* in a dependent context
9957   // where it's important for the sanity of two-phase lookup.
9958   if (!IsInstantiation)
9959     R.setHideTags(false);
9960 
9961   // For the purposes of this lookup, we have a base object type
9962   // equal to that of the current context.
9963   if (CurContext->isRecord()) {
9964     R.setBaseObjectType(
9965                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9966   }
9967 
9968   LookupQualifiedName(R, LookupContext);
9969 
9970   // Try to correct typos if possible. If constructor name lookup finds no
9971   // results, that means the named class has no explicit constructors, and we
9972   // suppressed declaring implicit ones (probably because it's dependent or
9973   // invalid).
9974   if (R.empty() &&
9975       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9976     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9977     // it will believe that glibc provides a ::gets in cases where it does not,
9978     // and will try to pull it into namespace std with a using-declaration.
9979     // Just ignore the using-declaration in that case.
9980     auto *II = NameInfo.getName().getAsIdentifierInfo();
9981     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9982         CurContext->isStdNamespace() &&
9983         isa<TranslationUnitDecl>(LookupContext) &&
9984         getSourceManager().isInSystemHeader(UsingLoc))
9985       return nullptr;
9986     if (TypoCorrection Corrected = CorrectTypo(
9987             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9988             llvm::make_unique<UsingValidatorCCC>(
9989                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9990                 dyn_cast<CXXRecordDecl>(CurContext)),
9991             CTK_ErrorRecovery)) {
9992       // We reject candidates where DroppedSpecifier == true, hence the
9993       // literal '0' below.
9994       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9995                                 << NameInfo.getName() << LookupContext << 0
9996                                 << SS.getRange());
9997 
9998       // If we picked a correction with no attached Decl we can't do anything
9999       // useful with it, bail out.
10000       NamedDecl *ND = Corrected.getCorrectionDecl();
10001       if (!ND)
10002         return BuildInvalid();
10003 
10004       // If we corrected to an inheriting constructor, handle it as one.
10005       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10006       if (RD && RD->isInjectedClassName()) {
10007         // The parent of the injected class name is the class itself.
10008         RD = cast<CXXRecordDecl>(RD->getParent());
10009 
10010         // Fix up the information we'll use to build the using declaration.
10011         if (Corrected.WillReplaceSpecifier()) {
10012           NestedNameSpecifierLocBuilder Builder;
10013           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10014                               QualifierLoc.getSourceRange());
10015           QualifierLoc = Builder.getWithLocInContext(Context);
10016         }
10017 
10018         // In this case, the name we introduce is the name of a derived class
10019         // constructor.
10020         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10021         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10022             Context.getCanonicalType(Context.getRecordType(CurClass))));
10023         UsingName.setNamedTypeInfo(nullptr);
10024         for (auto *Ctor : LookupConstructors(RD))
10025           R.addDecl(Ctor);
10026         R.resolveKind();
10027       } else {
10028         // FIXME: Pick up all the declarations if we found an overloaded
10029         // function.
10030         UsingName.setName(ND->getDeclName());
10031         R.addDecl(ND);
10032       }
10033     } else {
10034       Diag(IdentLoc, diag::err_no_member)
10035         << NameInfo.getName() << LookupContext << SS.getRange();
10036       return BuildInvalid();
10037     }
10038   }
10039 
10040   if (R.isAmbiguous())
10041     return BuildInvalid();
10042 
10043   if (HasTypenameKeyword) {
10044     // If we asked for a typename and got a non-type decl, error out.
10045     if (!R.getAsSingle<TypeDecl>()) {
10046       Diag(IdentLoc, diag::err_using_typename_non_type);
10047       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10048         Diag((*I)->getUnderlyingDecl()->getLocation(),
10049              diag::note_using_decl_target);
10050       return BuildInvalid();
10051     }
10052   } else {
10053     // If we asked for a non-typename and we got a type, error out,
10054     // but only if this is an instantiation of an unresolved using
10055     // decl.  Otherwise just silently find the type name.
10056     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10057       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10058       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10059       return BuildInvalid();
10060     }
10061   }
10062 
10063   // C++14 [namespace.udecl]p6:
10064   // A using-declaration shall not name a namespace.
10065   if (R.getAsSingle<NamespaceDecl>()) {
10066     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10067       << SS.getRange();
10068     return BuildInvalid();
10069   }
10070 
10071   // C++14 [namespace.udecl]p7:
10072   // A using-declaration shall not name a scoped enumerator.
10073   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10074     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10075       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10076         << SS.getRange();
10077       return BuildInvalid();
10078     }
10079   }
10080 
10081   UsingDecl *UD = BuildValid();
10082 
10083   // Some additional rules apply to inheriting constructors.
10084   if (UsingName.getName().getNameKind() ==
10085         DeclarationName::CXXConstructorName) {
10086     // Suppress access diagnostics; the access check is instead performed at the
10087     // point of use for an inheriting constructor.
10088     R.suppressDiagnostics();
10089     if (CheckInheritingConstructorUsingDecl(UD))
10090       return UD;
10091   }
10092 
10093   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10094     UsingShadowDecl *PrevDecl = nullptr;
10095     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10096       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10097   }
10098 
10099   return UD;
10100 }
10101 
10102 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10103                                     ArrayRef<NamedDecl *> Expansions) {
10104   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10105          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10106          isa<UsingPackDecl>(InstantiatedFrom));
10107 
10108   auto *UPD =
10109       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10110   UPD->setAccess(InstantiatedFrom->getAccess());
10111   CurContext->addDecl(UPD);
10112   return UPD;
10113 }
10114 
10115 /// Additional checks for a using declaration referring to a constructor name.
10116 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10117   assert(!UD->hasTypename() && "expecting a constructor name");
10118 
10119   const Type *SourceType = UD->getQualifier()->getAsType();
10120   assert(SourceType &&
10121          "Using decl naming constructor doesn't have type in scope spec.");
10122   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10123 
10124   // Check whether the named type is a direct base class.
10125   bool AnyDependentBases = false;
10126   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10127                                       AnyDependentBases);
10128   if (!Base && !AnyDependentBases) {
10129     Diag(UD->getUsingLoc(),
10130          diag::err_using_decl_constructor_not_in_direct_base)
10131       << UD->getNameInfo().getSourceRange()
10132       << QualType(SourceType, 0) << TargetClass;
10133     UD->setInvalidDecl();
10134     return true;
10135   }
10136 
10137   if (Base)
10138     Base->setInheritConstructors();
10139 
10140   return false;
10141 }
10142 
10143 /// Checks that the given using declaration is not an invalid
10144 /// redeclaration.  Note that this is checking only for the using decl
10145 /// itself, not for any ill-formedness among the UsingShadowDecls.
10146 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10147                                        bool HasTypenameKeyword,
10148                                        const CXXScopeSpec &SS,
10149                                        SourceLocation NameLoc,
10150                                        const LookupResult &Prev) {
10151   NestedNameSpecifier *Qual = SS.getScopeRep();
10152 
10153   // C++03 [namespace.udecl]p8:
10154   // C++0x [namespace.udecl]p10:
10155   //   A using-declaration is a declaration and can therefore be used
10156   //   repeatedly where (and only where) multiple declarations are
10157   //   allowed.
10158   //
10159   // That's in non-member contexts.
10160   if (!CurContext->getRedeclContext()->isRecord()) {
10161     // A dependent qualifier outside a class can only ever resolve to an
10162     // enumeration type. Therefore it conflicts with any other non-type
10163     // declaration in the same scope.
10164     // FIXME: How should we check for dependent type-type conflicts at block
10165     // scope?
10166     if (Qual->isDependent() && !HasTypenameKeyword) {
10167       for (auto *D : Prev) {
10168         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10169           bool OldCouldBeEnumerator =
10170               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10171           Diag(NameLoc,
10172                OldCouldBeEnumerator ? diag::err_redefinition
10173                                     : diag::err_redefinition_different_kind)
10174               << Prev.getLookupName();
10175           Diag(D->getLocation(), diag::note_previous_definition);
10176           return true;
10177         }
10178       }
10179     }
10180     return false;
10181   }
10182 
10183   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10184     NamedDecl *D = *I;
10185 
10186     bool DTypename;
10187     NestedNameSpecifier *DQual;
10188     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10189       DTypename = UD->hasTypename();
10190       DQual = UD->getQualifier();
10191     } else if (UnresolvedUsingValueDecl *UD
10192                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10193       DTypename = false;
10194       DQual = UD->getQualifier();
10195     } else if (UnresolvedUsingTypenameDecl *UD
10196                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10197       DTypename = true;
10198       DQual = UD->getQualifier();
10199     } else continue;
10200 
10201     // using decls differ if one says 'typename' and the other doesn't.
10202     // FIXME: non-dependent using decls?
10203     if (HasTypenameKeyword != DTypename) continue;
10204 
10205     // using decls differ if they name different scopes (but note that
10206     // template instantiation can cause this check to trigger when it
10207     // didn't before instantiation).
10208     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10209         Context.getCanonicalNestedNameSpecifier(DQual))
10210       continue;
10211 
10212     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10213     Diag(D->getLocation(), diag::note_using_decl) << 1;
10214     return true;
10215   }
10216 
10217   return false;
10218 }
10219 
10220 
10221 /// Checks that the given nested-name qualifier used in a using decl
10222 /// in the current context is appropriately related to the current
10223 /// scope.  If an error is found, diagnoses it and returns true.
10224 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10225                                    bool HasTypename,
10226                                    const CXXScopeSpec &SS,
10227                                    const DeclarationNameInfo &NameInfo,
10228                                    SourceLocation NameLoc) {
10229   DeclContext *NamedContext = computeDeclContext(SS);
10230 
10231   if (!CurContext->isRecord()) {
10232     // C++03 [namespace.udecl]p3:
10233     // C++0x [namespace.udecl]p8:
10234     //   A using-declaration for a class member shall be a member-declaration.
10235 
10236     // If we weren't able to compute a valid scope, it might validly be a
10237     // dependent class scope or a dependent enumeration unscoped scope. If
10238     // we have a 'typename' keyword, the scope must resolve to a class type.
10239     if ((HasTypename && !NamedContext) ||
10240         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10241       auto *RD = NamedContext
10242                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10243                      : nullptr;
10244       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10245         RD = nullptr;
10246 
10247       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10248         << SS.getRange();
10249 
10250       // If we have a complete, non-dependent source type, try to suggest a
10251       // way to get the same effect.
10252       if (!RD)
10253         return true;
10254 
10255       // Find what this using-declaration was referring to.
10256       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10257       R.setHideTags(false);
10258       R.suppressDiagnostics();
10259       LookupQualifiedName(R, RD);
10260 
10261       if (R.getAsSingle<TypeDecl>()) {
10262         if (getLangOpts().CPlusPlus11) {
10263           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10264           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10265             << 0 // alias declaration
10266             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10267                                           NameInfo.getName().getAsString() +
10268                                               " = ");
10269         } else {
10270           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10271           SourceLocation InsertLoc =
10272               getLocForEndOfToken(NameInfo.getLocEnd());
10273           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10274             << 1 // typedef declaration
10275             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10276             << FixItHint::CreateInsertion(
10277                    InsertLoc, " " + NameInfo.getName().getAsString());
10278         }
10279       } else if (R.getAsSingle<VarDecl>()) {
10280         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10281         // repeating the type of the static data member here.
10282         FixItHint FixIt;
10283         if (getLangOpts().CPlusPlus11) {
10284           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10285           FixIt = FixItHint::CreateReplacement(
10286               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10287         }
10288 
10289         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10290           << 2 // reference declaration
10291           << FixIt;
10292       } else if (R.getAsSingle<EnumConstantDecl>()) {
10293         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10294         // repeating the type of the enumeration here, and we can't do so if
10295         // the type is anonymous.
10296         FixItHint FixIt;
10297         if (getLangOpts().CPlusPlus11) {
10298           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10299           FixIt = FixItHint::CreateReplacement(
10300               UsingLoc,
10301               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10302         }
10303 
10304         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10305           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10306           << FixIt;
10307       }
10308       return true;
10309     }
10310 
10311     // Otherwise, this might be valid.
10312     return false;
10313   }
10314 
10315   // The current scope is a record.
10316 
10317   // If the named context is dependent, we can't decide much.
10318   if (!NamedContext) {
10319     // FIXME: in C++0x, we can diagnose if we can prove that the
10320     // nested-name-specifier does not refer to a base class, which is
10321     // still possible in some cases.
10322 
10323     // Otherwise we have to conservatively report that things might be
10324     // okay.
10325     return false;
10326   }
10327 
10328   if (!NamedContext->isRecord()) {
10329     // Ideally this would point at the last name in the specifier,
10330     // but we don't have that level of source info.
10331     Diag(SS.getRange().getBegin(),
10332          diag::err_using_decl_nested_name_specifier_is_not_class)
10333       << SS.getScopeRep() << SS.getRange();
10334     return true;
10335   }
10336 
10337   if (!NamedContext->isDependentContext() &&
10338       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10339     return true;
10340 
10341   if (getLangOpts().CPlusPlus11) {
10342     // C++11 [namespace.udecl]p3:
10343     //   In a using-declaration used as a member-declaration, the
10344     //   nested-name-specifier shall name a base class of the class
10345     //   being defined.
10346 
10347     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10348                                  cast<CXXRecordDecl>(NamedContext))) {
10349       if (CurContext == NamedContext) {
10350         Diag(NameLoc,
10351              diag::err_using_decl_nested_name_specifier_is_current_class)
10352           << SS.getRange();
10353         return true;
10354       }
10355 
10356       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10357         Diag(SS.getRange().getBegin(),
10358              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10359           << SS.getScopeRep()
10360           << cast<CXXRecordDecl>(CurContext)
10361           << SS.getRange();
10362       }
10363       return true;
10364     }
10365 
10366     return false;
10367   }
10368 
10369   // C++03 [namespace.udecl]p4:
10370   //   A using-declaration used as a member-declaration shall refer
10371   //   to a member of a base class of the class being defined [etc.].
10372 
10373   // Salient point: SS doesn't have to name a base class as long as
10374   // lookup only finds members from base classes.  Therefore we can
10375   // diagnose here only if we can prove that that can't happen,
10376   // i.e. if the class hierarchies provably don't intersect.
10377 
10378   // TODO: it would be nice if "definitely valid" results were cached
10379   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10380   // need to be repeated.
10381 
10382   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10383   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10384     Bases.insert(Base);
10385     return true;
10386   };
10387 
10388   // Collect all bases. Return false if we find a dependent base.
10389   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10390     return false;
10391 
10392   // Returns true if the base is dependent or is one of the accumulated base
10393   // classes.
10394   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10395     return !Bases.count(Base);
10396   };
10397 
10398   // Return false if the class has a dependent base or if it or one
10399   // of its bases is present in the base set of the current context.
10400   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10401       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10402     return false;
10403 
10404   Diag(SS.getRange().getBegin(),
10405        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10406     << SS.getScopeRep()
10407     << cast<CXXRecordDecl>(CurContext)
10408     << SS.getRange();
10409 
10410   return true;
10411 }
10412 
10413 Decl *Sema::ActOnAliasDeclaration(Scope *S,
10414                                   AccessSpecifier AS,
10415                                   MultiTemplateParamsArg TemplateParamLists,
10416                                   SourceLocation UsingLoc,
10417                                   UnqualifiedId &Name,
10418                                   AttributeList *AttrList,
10419                                   TypeResult Type,
10420                                   Decl *DeclFromDeclSpec) {
10421   // Skip up to the relevant declaration scope.
10422   while (S->isTemplateParamScope())
10423     S = S->getParent();
10424   assert((S->getFlags() & Scope::DeclScope) &&
10425          "got alias-declaration outside of declaration scope");
10426 
10427   if (Type.isInvalid())
10428     return nullptr;
10429 
10430   bool Invalid = false;
10431   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10432   TypeSourceInfo *TInfo = nullptr;
10433   GetTypeFromParser(Type.get(), &TInfo);
10434 
10435   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10436     return nullptr;
10437 
10438   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10439                                       UPPC_DeclarationType)) {
10440     Invalid = true;
10441     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10442                                              TInfo->getTypeLoc().getBeginLoc());
10443   }
10444 
10445   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10446                         TemplateParamLists.size()
10447                             ? forRedeclarationInCurContext()
10448                             : ForVisibleRedeclaration);
10449   LookupName(Previous, S);
10450 
10451   // Warn about shadowing the name of a template parameter.
10452   if (Previous.isSingleResult() &&
10453       Previous.getFoundDecl()->isTemplateParameter()) {
10454     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10455     Previous.clear();
10456   }
10457 
10458   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10459          "name in alias declaration must be an identifier");
10460   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10461                                                Name.StartLocation,
10462                                                Name.Identifier, TInfo);
10463 
10464   NewTD->setAccess(AS);
10465 
10466   if (Invalid)
10467     NewTD->setInvalidDecl();
10468 
10469   ProcessDeclAttributeList(S, NewTD, AttrList);
10470   AddPragmaAttributes(S, NewTD);
10471 
10472   CheckTypedefForVariablyModifiedType(S, NewTD);
10473   Invalid |= NewTD->isInvalidDecl();
10474 
10475   bool Redeclaration = false;
10476 
10477   NamedDecl *NewND;
10478   if (TemplateParamLists.size()) {
10479     TypeAliasTemplateDecl *OldDecl = nullptr;
10480     TemplateParameterList *OldTemplateParams = nullptr;
10481 
10482     if (TemplateParamLists.size() != 1) {
10483       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10484         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10485          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10486     }
10487     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10488 
10489     // Check that we can declare a template here.
10490     if (CheckTemplateDeclScope(S, TemplateParams))
10491       return nullptr;
10492 
10493     // Only consider previous declarations in the same scope.
10494     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10495                          /*ExplicitInstantiationOrSpecialization*/false);
10496     if (!Previous.empty()) {
10497       Redeclaration = true;
10498 
10499       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10500       if (!OldDecl && !Invalid) {
10501         Diag(UsingLoc, diag::err_redefinition_different_kind)
10502           << Name.Identifier;
10503 
10504         NamedDecl *OldD = Previous.getRepresentativeDecl();
10505         if (OldD->getLocation().isValid())
10506           Diag(OldD->getLocation(), diag::note_previous_definition);
10507 
10508         Invalid = true;
10509       }
10510 
10511       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10512         if (TemplateParameterListsAreEqual(TemplateParams,
10513                                            OldDecl->getTemplateParameters(),
10514                                            /*Complain=*/true,
10515                                            TPL_TemplateMatch))
10516           OldTemplateParams = OldDecl->getTemplateParameters();
10517         else
10518           Invalid = true;
10519 
10520         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10521         if (!Invalid &&
10522             !Context.hasSameType(OldTD->getUnderlyingType(),
10523                                  NewTD->getUnderlyingType())) {
10524           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10525           // but we can't reasonably accept it.
10526           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10527             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10528           if (OldTD->getLocation().isValid())
10529             Diag(OldTD->getLocation(), diag::note_previous_definition);
10530           Invalid = true;
10531         }
10532       }
10533     }
10534 
10535     // Merge any previous default template arguments into our parameters,
10536     // and check the parameter list.
10537     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10538                                    TPC_TypeAliasTemplate))
10539       return nullptr;
10540 
10541     TypeAliasTemplateDecl *NewDecl =
10542       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10543                                     Name.Identifier, TemplateParams,
10544                                     NewTD);
10545     NewTD->setDescribedAliasTemplate(NewDecl);
10546 
10547     NewDecl->setAccess(AS);
10548 
10549     if (Invalid)
10550       NewDecl->setInvalidDecl();
10551     else if (OldDecl) {
10552       NewDecl->setPreviousDecl(OldDecl);
10553       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10554     }
10555 
10556     NewND = NewDecl;
10557   } else {
10558     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10559       setTagNameForLinkagePurposes(TD, NewTD);
10560       handleTagNumbering(TD, S);
10561     }
10562     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10563     NewND = NewTD;
10564   }
10565 
10566   PushOnScopeChains(NewND, S);
10567   ActOnDocumentableDecl(NewND);
10568   return NewND;
10569 }
10570 
10571 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10572                                    SourceLocation AliasLoc,
10573                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10574                                    SourceLocation IdentLoc,
10575                                    IdentifierInfo *Ident) {
10576 
10577   // Lookup the namespace name.
10578   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10579   LookupParsedName(R, S, &SS);
10580 
10581   if (R.isAmbiguous())
10582     return nullptr;
10583 
10584   if (R.empty()) {
10585     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10586       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10587       return nullptr;
10588     }
10589   }
10590   assert(!R.isAmbiguous() && !R.empty());
10591   NamedDecl *ND = R.getRepresentativeDecl();
10592 
10593   // Check if we have a previous declaration with the same name.
10594   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10595                      ForVisibleRedeclaration);
10596   LookupName(PrevR, S);
10597 
10598   // Check we're not shadowing a template parameter.
10599   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10600     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10601     PrevR.clear();
10602   }
10603 
10604   // Filter out any other lookup result from an enclosing scope.
10605   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10606                        /*AllowInlineNamespace*/false);
10607 
10608   // Find the previous declaration and check that we can redeclare it.
10609   NamespaceAliasDecl *Prev = nullptr;
10610   if (PrevR.isSingleResult()) {
10611     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10612     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10613       // We already have an alias with the same name that points to the same
10614       // namespace; check that it matches.
10615       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10616         Prev = AD;
10617       } else if (isVisible(PrevDecl)) {
10618         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10619           << Alias;
10620         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10621           << AD->getNamespace();
10622         return nullptr;
10623       }
10624     } else if (isVisible(PrevDecl)) {
10625       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10626                             ? diag::err_redefinition
10627                             : diag::err_redefinition_different_kind;
10628       Diag(AliasLoc, DiagID) << Alias;
10629       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10630       return nullptr;
10631     }
10632   }
10633 
10634   // The use of a nested name specifier may trigger deprecation warnings.
10635   DiagnoseUseOfDecl(ND, IdentLoc);
10636 
10637   NamespaceAliasDecl *AliasDecl =
10638     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10639                                Alias, SS.getWithLocInContext(Context),
10640                                IdentLoc, ND);
10641   if (Prev)
10642     AliasDecl->setPreviousDecl(Prev);
10643 
10644   PushOnScopeChains(AliasDecl, S);
10645   return AliasDecl;
10646 }
10647 
10648 namespace {
10649 struct SpecialMemberExceptionSpecInfo
10650     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10651   SourceLocation Loc;
10652   Sema::ImplicitExceptionSpecification ExceptSpec;
10653 
10654   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10655                                  Sema::CXXSpecialMember CSM,
10656                                  Sema::InheritedConstructorInfo *ICI,
10657                                  SourceLocation Loc)
10658       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10659 
10660   bool visitBase(CXXBaseSpecifier *Base);
10661   bool visitField(FieldDecl *FD);
10662 
10663   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10664                            unsigned Quals);
10665 
10666   void visitSubobjectCall(Subobject Subobj,
10667                           Sema::SpecialMemberOverloadResult SMOR);
10668 };
10669 }
10670 
10671 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10672   auto *RT = Base->getType()->getAs<RecordType>();
10673   if (!RT)
10674     return false;
10675 
10676   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10677   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10678   if (auto *BaseCtor = SMOR.getMethod()) {
10679     visitSubobjectCall(Base, BaseCtor);
10680     return false;
10681   }
10682 
10683   visitClassSubobject(BaseClass, Base, 0);
10684   return false;
10685 }
10686 
10687 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10688   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10689     Expr *E = FD->getInClassInitializer();
10690     if (!E)
10691       // FIXME: It's a little wasteful to build and throw away a
10692       // CXXDefaultInitExpr here.
10693       // FIXME: We should have a single context note pointing at Loc, and
10694       // this location should be MD->getLocation() instead, since that's
10695       // the location where we actually use the default init expression.
10696       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10697     if (E)
10698       ExceptSpec.CalledExpr(E);
10699   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10700                             ->getAs<RecordType>()) {
10701     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10702                         FD->getType().getCVRQualifiers());
10703   }
10704   return false;
10705 }
10706 
10707 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10708                                                          Subobject Subobj,
10709                                                          unsigned Quals) {
10710   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10711   bool IsMutable = Field && Field->isMutable();
10712   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10713 }
10714 
10715 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10716     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10717   // Note, if lookup fails, it doesn't matter what exception specification we
10718   // choose because the special member will be deleted.
10719   if (CXXMethodDecl *MD = SMOR.getMethod())
10720     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10721 }
10722 
10723 static Sema::ImplicitExceptionSpecification
10724 ComputeDefaultedSpecialMemberExceptionSpec(
10725     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10726     Sema::InheritedConstructorInfo *ICI) {
10727   CXXRecordDecl *ClassDecl = MD->getParent();
10728 
10729   // C++ [except.spec]p14:
10730   //   An implicitly declared special member function (Clause 12) shall have an
10731   //   exception-specification. [...]
10732   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10733   if (ClassDecl->isInvalidDecl())
10734     return Info.ExceptSpec;
10735 
10736   // C++1z [except.spec]p7:
10737   //   [Look for exceptions thrown by] a constructor selected [...] to
10738   //   initialize a potentially constructed subobject,
10739   // C++1z [except.spec]p8:
10740   //   The exception specification for an implicitly-declared destructor, or a
10741   //   destructor without a noexcept-specifier, is potentially-throwing if and
10742   //   only if any of the destructors for any of its potentially constructed
10743   //   subojects is potentially throwing.
10744   // FIXME: We respect the first rule but ignore the "potentially constructed"
10745   // in the second rule to resolve a core issue (no number yet) that would have
10746   // us reject:
10747   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10748   //   struct B : A {};
10749   //   struct C : B { void f(); };
10750   // ... due to giving B::~B() a non-throwing exception specification.
10751   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10752                                 : Info.VisitAllBases);
10753 
10754   return Info.ExceptSpec;
10755 }
10756 
10757 namespace {
10758 /// RAII object to register a special member as being currently declared.
10759 struct DeclaringSpecialMember {
10760   Sema &S;
10761   Sema::SpecialMemberDecl D;
10762   Sema::ContextRAII SavedContext;
10763   bool WasAlreadyBeingDeclared;
10764 
10765   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10766       : S(S), D(RD, CSM), SavedContext(S, RD) {
10767     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10768     if (WasAlreadyBeingDeclared)
10769       // This almost never happens, but if it does, ensure that our cache
10770       // doesn't contain a stale result.
10771       S.SpecialMemberCache.clear();
10772     else {
10773       // Register a note to be produced if we encounter an error while
10774       // declaring the special member.
10775       Sema::CodeSynthesisContext Ctx;
10776       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10777       // FIXME: We don't have a location to use here. Using the class's
10778       // location maintains the fiction that we declare all special members
10779       // with the class, but (1) it's not clear that lying about that helps our
10780       // users understand what's going on, and (2) there may be outer contexts
10781       // on the stack (some of which are relevant) and printing them exposes
10782       // our lies.
10783       Ctx.PointOfInstantiation = RD->getLocation();
10784       Ctx.Entity = RD;
10785       Ctx.SpecialMember = CSM;
10786       S.pushCodeSynthesisContext(Ctx);
10787     }
10788   }
10789   ~DeclaringSpecialMember() {
10790     if (!WasAlreadyBeingDeclared) {
10791       S.SpecialMembersBeingDeclared.erase(D);
10792       S.popCodeSynthesisContext();
10793     }
10794   }
10795 
10796   /// Are we already trying to declare this special member?
10797   bool isAlreadyBeingDeclared() const {
10798     return WasAlreadyBeingDeclared;
10799   }
10800 };
10801 }
10802 
10803 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10804   // Look up any existing declarations, but don't trigger declaration of all
10805   // implicit special members with this name.
10806   DeclarationName Name = FD->getDeclName();
10807   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10808                  ForExternalRedeclaration);
10809   for (auto *D : FD->getParent()->lookup(Name))
10810     if (auto *Acceptable = R.getAcceptableDecl(D))
10811       R.addDecl(Acceptable);
10812   R.resolveKind();
10813   R.suppressDiagnostics();
10814 
10815   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10816 }
10817 
10818 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10819                                                      CXXRecordDecl *ClassDecl) {
10820   // C++ [class.ctor]p5:
10821   //   A default constructor for a class X is a constructor of class X
10822   //   that can be called without an argument. If there is no
10823   //   user-declared constructor for class X, a default constructor is
10824   //   implicitly declared. An implicitly-declared default constructor
10825   //   is an inline public member of its class.
10826   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10827          "Should not build implicit default constructor!");
10828 
10829   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10830   if (DSM.isAlreadyBeingDeclared())
10831     return nullptr;
10832 
10833   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10834                                                      CXXDefaultConstructor,
10835                                                      false);
10836 
10837   // Create the actual constructor declaration.
10838   CanQualType ClassType
10839     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10840   SourceLocation ClassLoc = ClassDecl->getLocation();
10841   DeclarationName Name
10842     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10843   DeclarationNameInfo NameInfo(Name, ClassLoc);
10844   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10845       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10846       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10847       /*isImplicitlyDeclared=*/true, Constexpr);
10848   DefaultCon->setAccess(AS_public);
10849   DefaultCon->setDefaulted();
10850 
10851   if (getLangOpts().CUDA) {
10852     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10853                                             DefaultCon,
10854                                             /* ConstRHS */ false,
10855                                             /* Diagnose */ false);
10856   }
10857 
10858   // Build an exception specification pointing back at this constructor.
10859   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10860   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10861 
10862   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10863   // constructors is easy to compute.
10864   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10865 
10866   // Note that we have declared this constructor.
10867   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10868 
10869   Scope *S = getScopeForContext(ClassDecl);
10870   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10871 
10872   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10873     SetDeclDeleted(DefaultCon, ClassLoc);
10874 
10875   if (S)
10876     PushOnScopeChains(DefaultCon, S, false);
10877   ClassDecl->addDecl(DefaultCon);
10878 
10879   return DefaultCon;
10880 }
10881 
10882 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10883                                             CXXConstructorDecl *Constructor) {
10884   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10885           !Constructor->doesThisDeclarationHaveABody() &&
10886           !Constructor->isDeleted()) &&
10887     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10888   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10889     return;
10890 
10891   CXXRecordDecl *ClassDecl = Constructor->getParent();
10892   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10893 
10894   SynthesizedFunctionScope Scope(*this, Constructor);
10895 
10896   // The exception specification is needed because we are defining the
10897   // function.
10898   ResolveExceptionSpec(CurrentLocation,
10899                        Constructor->getType()->castAs<FunctionProtoType>());
10900   MarkVTableUsed(CurrentLocation, ClassDecl);
10901 
10902   // Add a context note for diagnostics produced after this point.
10903   Scope.addContextNote(CurrentLocation);
10904 
10905   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10906     Constructor->setInvalidDecl();
10907     return;
10908   }
10909 
10910   SourceLocation Loc = Constructor->getLocEnd().isValid()
10911                            ? Constructor->getLocEnd()
10912                            : Constructor->getLocation();
10913   Constructor->setBody(new (Context) CompoundStmt(Loc));
10914   Constructor->markUsed(Context);
10915 
10916   if (ASTMutationListener *L = getASTMutationListener()) {
10917     L->CompletedImplicitDefinition(Constructor);
10918   }
10919 
10920   DiagnoseUninitializedFields(*this, Constructor);
10921 }
10922 
10923 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10924   // Perform any delayed checks on exception specifications.
10925   CheckDelayedMemberExceptionSpecs();
10926 }
10927 
10928 /// Find or create the fake constructor we synthesize to model constructing an
10929 /// object of a derived class via a constructor of a base class.
10930 CXXConstructorDecl *
10931 Sema::findInheritingConstructor(SourceLocation Loc,
10932                                 CXXConstructorDecl *BaseCtor,
10933                                 ConstructorUsingShadowDecl *Shadow) {
10934   CXXRecordDecl *Derived = Shadow->getParent();
10935   SourceLocation UsingLoc = Shadow->getLocation();
10936 
10937   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10938   // For now we use the name of the base class constructor as a member of the
10939   // derived class to indicate a (fake) inherited constructor name.
10940   DeclarationName Name = BaseCtor->getDeclName();
10941 
10942   // Check to see if we already have a fake constructor for this inherited
10943   // constructor call.
10944   for (NamedDecl *Ctor : Derived->lookup(Name))
10945     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10946                                ->getInheritedConstructor()
10947                                .getConstructor(),
10948                            BaseCtor))
10949       return cast<CXXConstructorDecl>(Ctor);
10950 
10951   DeclarationNameInfo NameInfo(Name, UsingLoc);
10952   TypeSourceInfo *TInfo =
10953       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10954   FunctionProtoTypeLoc ProtoLoc =
10955       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10956 
10957   // Check the inherited constructor is valid and find the list of base classes
10958   // from which it was inherited.
10959   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10960 
10961   bool Constexpr =
10962       BaseCtor->isConstexpr() &&
10963       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10964                                         false, BaseCtor, &ICI);
10965 
10966   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10967       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10968       BaseCtor->isExplicit(), /*Inline=*/true,
10969       /*ImplicitlyDeclared=*/true, Constexpr,
10970       InheritedConstructor(Shadow, BaseCtor));
10971   if (Shadow->isInvalidDecl())
10972     DerivedCtor->setInvalidDecl();
10973 
10974   // Build an unevaluated exception specification for this fake constructor.
10975   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10976   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10977   EPI.ExceptionSpec.Type = EST_Unevaluated;
10978   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10979   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10980                                                FPT->getParamTypes(), EPI));
10981 
10982   // Build the parameter declarations.
10983   SmallVector<ParmVarDecl *, 16> ParamDecls;
10984   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10985     TypeSourceInfo *TInfo =
10986         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10987     ParmVarDecl *PD = ParmVarDecl::Create(
10988         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10989         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10990     PD->setScopeInfo(0, I);
10991     PD->setImplicit();
10992     // Ensure attributes are propagated onto parameters (this matters for
10993     // format, pass_object_size, ...).
10994     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10995     ParamDecls.push_back(PD);
10996     ProtoLoc.setParam(I, PD);
10997   }
10998 
10999   // Set up the new constructor.
11000   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11001   DerivedCtor->setAccess(BaseCtor->getAccess());
11002   DerivedCtor->setParams(ParamDecls);
11003   Derived->addDecl(DerivedCtor);
11004 
11005   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11006     SetDeclDeleted(DerivedCtor, UsingLoc);
11007 
11008   return DerivedCtor;
11009 }
11010 
11011 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11012   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11013                                Ctor->getInheritedConstructor().getShadowDecl());
11014   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11015                             /*Diagnose*/true);
11016 }
11017 
11018 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11019                                        CXXConstructorDecl *Constructor) {
11020   CXXRecordDecl *ClassDecl = Constructor->getParent();
11021   assert(Constructor->getInheritedConstructor() &&
11022          !Constructor->doesThisDeclarationHaveABody() &&
11023          !Constructor->isDeleted());
11024   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11025     return;
11026 
11027   // Initializations are performed "as if by a defaulted default constructor",
11028   // so enter the appropriate scope.
11029   SynthesizedFunctionScope Scope(*this, Constructor);
11030 
11031   // The exception specification is needed because we are defining the
11032   // function.
11033   ResolveExceptionSpec(CurrentLocation,
11034                        Constructor->getType()->castAs<FunctionProtoType>());
11035   MarkVTableUsed(CurrentLocation, ClassDecl);
11036 
11037   // Add a context note for diagnostics produced after this point.
11038   Scope.addContextNote(CurrentLocation);
11039 
11040   ConstructorUsingShadowDecl *Shadow =
11041       Constructor->getInheritedConstructor().getShadowDecl();
11042   CXXConstructorDecl *InheritedCtor =
11043       Constructor->getInheritedConstructor().getConstructor();
11044 
11045   // [class.inhctor.init]p1:
11046   //   initialization proceeds as if a defaulted default constructor is used to
11047   //   initialize the D object and each base class subobject from which the
11048   //   constructor was inherited
11049 
11050   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11051   CXXRecordDecl *RD = Shadow->getParent();
11052   SourceLocation InitLoc = Shadow->getLocation();
11053 
11054   // Build explicit initializers for all base classes from which the
11055   // constructor was inherited.
11056   SmallVector<CXXCtorInitializer*, 8> Inits;
11057   for (bool VBase : {false, true}) {
11058     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11059       if (B.isVirtual() != VBase)
11060         continue;
11061 
11062       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11063       if (!BaseRD)
11064         continue;
11065 
11066       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11067       if (!BaseCtor.first)
11068         continue;
11069 
11070       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11071       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11072           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11073 
11074       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11075       Inits.push_back(new (Context) CXXCtorInitializer(
11076           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11077           SourceLocation()));
11078     }
11079   }
11080 
11081   // We now proceed as if for a defaulted default constructor, with the relevant
11082   // initializers replaced.
11083 
11084   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11085     Constructor->setInvalidDecl();
11086     return;
11087   }
11088 
11089   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11090   Constructor->markUsed(Context);
11091 
11092   if (ASTMutationListener *L = getASTMutationListener()) {
11093     L->CompletedImplicitDefinition(Constructor);
11094   }
11095 
11096   DiagnoseUninitializedFields(*this, Constructor);
11097 }
11098 
11099 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11100   // C++ [class.dtor]p2:
11101   //   If a class has no user-declared destructor, a destructor is
11102   //   declared implicitly. An implicitly-declared destructor is an
11103   //   inline public member of its class.
11104   assert(ClassDecl->needsImplicitDestructor());
11105 
11106   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11107   if (DSM.isAlreadyBeingDeclared())
11108     return nullptr;
11109 
11110   // Create the actual destructor declaration.
11111   CanQualType ClassType
11112     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11113   SourceLocation ClassLoc = ClassDecl->getLocation();
11114   DeclarationName Name
11115     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11116   DeclarationNameInfo NameInfo(Name, ClassLoc);
11117   CXXDestructorDecl *Destructor
11118       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11119                                   QualType(), nullptr, /*isInline=*/true,
11120                                   /*isImplicitlyDeclared=*/true);
11121   Destructor->setAccess(AS_public);
11122   Destructor->setDefaulted();
11123 
11124   if (getLangOpts().CUDA) {
11125     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11126                                             Destructor,
11127                                             /* ConstRHS */ false,
11128                                             /* Diagnose */ false);
11129   }
11130 
11131   // Build an exception specification pointing back at this destructor.
11132   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
11133   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11134 
11135   // We don't need to use SpecialMemberIsTrivial here; triviality for
11136   // destructors is easy to compute.
11137   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11138   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11139                                 ClassDecl->hasTrivialDestructorForCall());
11140 
11141   // Note that we have declared this destructor.
11142   ++ASTContext::NumImplicitDestructorsDeclared;
11143 
11144   Scope *S = getScopeForContext(ClassDecl);
11145   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11146 
11147   // We can't check whether an implicit destructor is deleted before we complete
11148   // the definition of the class, because its validity depends on the alignment
11149   // of the class. We'll check this from ActOnFields once the class is complete.
11150   if (ClassDecl->isCompleteDefinition() &&
11151       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11152     SetDeclDeleted(Destructor, ClassLoc);
11153 
11154   // Introduce this destructor into its scope.
11155   if (S)
11156     PushOnScopeChains(Destructor, S, false);
11157   ClassDecl->addDecl(Destructor);
11158 
11159   return Destructor;
11160 }
11161 
11162 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11163                                     CXXDestructorDecl *Destructor) {
11164   assert((Destructor->isDefaulted() &&
11165           !Destructor->doesThisDeclarationHaveABody() &&
11166           !Destructor->isDeleted()) &&
11167          "DefineImplicitDestructor - call it for implicit default dtor");
11168   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11169     return;
11170 
11171   CXXRecordDecl *ClassDecl = Destructor->getParent();
11172   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11173 
11174   SynthesizedFunctionScope Scope(*this, Destructor);
11175 
11176   // The exception specification is needed because we are defining the
11177   // function.
11178   ResolveExceptionSpec(CurrentLocation,
11179                        Destructor->getType()->castAs<FunctionProtoType>());
11180   MarkVTableUsed(CurrentLocation, ClassDecl);
11181 
11182   // Add a context note for diagnostics produced after this point.
11183   Scope.addContextNote(CurrentLocation);
11184 
11185   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11186                                          Destructor->getParent());
11187 
11188   if (CheckDestructor(Destructor)) {
11189     Destructor->setInvalidDecl();
11190     return;
11191   }
11192 
11193   SourceLocation Loc = Destructor->getLocEnd().isValid()
11194                            ? Destructor->getLocEnd()
11195                            : Destructor->getLocation();
11196   Destructor->setBody(new (Context) CompoundStmt(Loc));
11197   Destructor->markUsed(Context);
11198 
11199   if (ASTMutationListener *L = getASTMutationListener()) {
11200     L->CompletedImplicitDefinition(Destructor);
11201   }
11202 }
11203 
11204 /// Perform any semantic analysis which needs to be delayed until all
11205 /// pending class member declarations have been parsed.
11206 void Sema::ActOnFinishCXXMemberDecls() {
11207   // If the context is an invalid C++ class, just suppress these checks.
11208   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11209     if (Record->isInvalidDecl()) {
11210       DelayedDefaultedMemberExceptionSpecs.clear();
11211       DelayedExceptionSpecChecks.clear();
11212       return;
11213     }
11214     checkForMultipleExportedDefaultConstructors(*this, Record);
11215   }
11216 }
11217 
11218 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11219   referenceDLLExportedClassMethods();
11220 }
11221 
11222 void Sema::referenceDLLExportedClassMethods() {
11223   if (!DelayedDllExportClasses.empty()) {
11224     // Calling ReferenceDllExportedMembers might cause the current function to
11225     // be called again, so use a local copy of DelayedDllExportClasses.
11226     SmallVector<CXXRecordDecl *, 4> WorkList;
11227     std::swap(DelayedDllExportClasses, WorkList);
11228     for (CXXRecordDecl *Class : WorkList)
11229       ReferenceDllExportedMembers(*this, Class);
11230   }
11231 }
11232 
11233 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
11234                                          CXXDestructorDecl *Destructor) {
11235   assert(getLangOpts().CPlusPlus11 &&
11236          "adjusting dtor exception specs was introduced in c++11");
11237 
11238   // C++11 [class.dtor]p3:
11239   //   A declaration of a destructor that does not have an exception-
11240   //   specification is implicitly considered to have the same exception-
11241   //   specification as an implicit declaration.
11242   const FunctionProtoType *DtorType = Destructor->getType()->
11243                                         getAs<FunctionProtoType>();
11244   if (DtorType->hasExceptionSpec())
11245     return;
11246 
11247   // Replace the destructor's type, building off the existing one. Fortunately,
11248   // the only thing of interest in the destructor type is its extended info.
11249   // The return and arguments are fixed.
11250   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11251   EPI.ExceptionSpec.Type = EST_Unevaluated;
11252   EPI.ExceptionSpec.SourceDecl = Destructor;
11253   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11254 
11255   // FIXME: If the destructor has a body that could throw, and the newly created
11256   // spec doesn't allow exceptions, we should emit a warning, because this
11257   // change in behavior can break conforming C++03 programs at runtime.
11258   // However, we don't have a body or an exception specification yet, so it
11259   // needs to be done somewhere else.
11260 }
11261 
11262 namespace {
11263 /// An abstract base class for all helper classes used in building the
11264 //  copy/move operators. These classes serve as factory functions and help us
11265 //  avoid using the same Expr* in the AST twice.
11266 class ExprBuilder {
11267   ExprBuilder(const ExprBuilder&) = delete;
11268   ExprBuilder &operator=(const ExprBuilder&) = delete;
11269 
11270 protected:
11271   static Expr *assertNotNull(Expr *E) {
11272     assert(E && "Expression construction must not fail.");
11273     return E;
11274   }
11275 
11276 public:
11277   ExprBuilder() {}
11278   virtual ~ExprBuilder() {}
11279 
11280   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11281 };
11282 
11283 class RefBuilder: public ExprBuilder {
11284   VarDecl *Var;
11285   QualType VarType;
11286 
11287 public:
11288   Expr *build(Sema &S, SourceLocation Loc) const override {
11289     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11290   }
11291 
11292   RefBuilder(VarDecl *Var, QualType VarType)
11293       : Var(Var), VarType(VarType) {}
11294 };
11295 
11296 class ThisBuilder: public ExprBuilder {
11297 public:
11298   Expr *build(Sema &S, SourceLocation Loc) const override {
11299     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11300   }
11301 };
11302 
11303 class CastBuilder: public ExprBuilder {
11304   const ExprBuilder &Builder;
11305   QualType Type;
11306   ExprValueKind Kind;
11307   const CXXCastPath &Path;
11308 
11309 public:
11310   Expr *build(Sema &S, SourceLocation Loc) const override {
11311     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11312                                              CK_UncheckedDerivedToBase, Kind,
11313                                              &Path).get());
11314   }
11315 
11316   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11317               const CXXCastPath &Path)
11318       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11319 };
11320 
11321 class DerefBuilder: public ExprBuilder {
11322   const ExprBuilder &Builder;
11323 
11324 public:
11325   Expr *build(Sema &S, SourceLocation Loc) const override {
11326     return assertNotNull(
11327         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11328   }
11329 
11330   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11331 };
11332 
11333 class MemberBuilder: public ExprBuilder {
11334   const ExprBuilder &Builder;
11335   QualType Type;
11336   CXXScopeSpec SS;
11337   bool IsArrow;
11338   LookupResult &MemberLookup;
11339 
11340 public:
11341   Expr *build(Sema &S, SourceLocation Loc) const override {
11342     return assertNotNull(S.BuildMemberReferenceExpr(
11343         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11344         nullptr, MemberLookup, nullptr, nullptr).get());
11345   }
11346 
11347   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11348                 LookupResult &MemberLookup)
11349       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11350         MemberLookup(MemberLookup) {}
11351 };
11352 
11353 class MoveCastBuilder: public ExprBuilder {
11354   const ExprBuilder &Builder;
11355 
11356 public:
11357   Expr *build(Sema &S, SourceLocation Loc) const override {
11358     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11359   }
11360 
11361   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11362 };
11363 
11364 class LvalueConvBuilder: public ExprBuilder {
11365   const ExprBuilder &Builder;
11366 
11367 public:
11368   Expr *build(Sema &S, SourceLocation Loc) const override {
11369     return assertNotNull(
11370         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11371   }
11372 
11373   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11374 };
11375 
11376 class SubscriptBuilder: public ExprBuilder {
11377   const ExprBuilder &Base;
11378   const ExprBuilder &Index;
11379 
11380 public:
11381   Expr *build(Sema &S, SourceLocation Loc) const override {
11382     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11383         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11384   }
11385 
11386   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11387       : Base(Base), Index(Index) {}
11388 };
11389 
11390 } // end anonymous namespace
11391 
11392 /// When generating a defaulted copy or move assignment operator, if a field
11393 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11394 /// do so. This optimization only applies for arrays of scalars, and for arrays
11395 /// of class type where the selected copy/move-assignment operator is trivial.
11396 static StmtResult
11397 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11398                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11399   // Compute the size of the memory buffer to be copied.
11400   QualType SizeType = S.Context.getSizeType();
11401   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11402                    S.Context.getTypeSizeInChars(T).getQuantity());
11403 
11404   // Take the address of the field references for "from" and "to". We
11405   // directly construct UnaryOperators here because semantic analysis
11406   // does not permit us to take the address of an xvalue.
11407   Expr *From = FromB.build(S, Loc);
11408   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11409                          S.Context.getPointerType(From->getType()),
11410                          VK_RValue, OK_Ordinary, Loc, false);
11411   Expr *To = ToB.build(S, Loc);
11412   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11413                        S.Context.getPointerType(To->getType()),
11414                        VK_RValue, OK_Ordinary, Loc, false);
11415 
11416   const Type *E = T->getBaseElementTypeUnsafe();
11417   bool NeedsCollectableMemCpy =
11418     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11419 
11420   // Create a reference to the __builtin_objc_memmove_collectable function
11421   StringRef MemCpyName = NeedsCollectableMemCpy ?
11422     "__builtin_objc_memmove_collectable" :
11423     "__builtin_memcpy";
11424   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11425                  Sema::LookupOrdinaryName);
11426   S.LookupName(R, S.TUScope, true);
11427 
11428   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11429   if (!MemCpy)
11430     // Something went horribly wrong earlier, and we will have complained
11431     // about it.
11432     return StmtError();
11433 
11434   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11435                                             VK_RValue, Loc, nullptr);
11436   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11437 
11438   Expr *CallArgs[] = {
11439     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11440   };
11441   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11442                                     Loc, CallArgs, Loc);
11443 
11444   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11445   return Call.getAs<Stmt>();
11446 }
11447 
11448 /// Builds a statement that copies/moves the given entity from \p From to
11449 /// \c To.
11450 ///
11451 /// This routine is used to copy/move the members of a class with an
11452 /// implicitly-declared copy/move assignment operator. When the entities being
11453 /// copied are arrays, this routine builds for loops to copy them.
11454 ///
11455 /// \param S The Sema object used for type-checking.
11456 ///
11457 /// \param Loc The location where the implicit copy/move is being generated.
11458 ///
11459 /// \param T The type of the expressions being copied/moved. Both expressions
11460 /// must have this type.
11461 ///
11462 /// \param To The expression we are copying/moving to.
11463 ///
11464 /// \param From The expression we are copying/moving from.
11465 ///
11466 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11467 /// Otherwise, it's a non-static member subobject.
11468 ///
11469 /// \param Copying Whether we're copying or moving.
11470 ///
11471 /// \param Depth Internal parameter recording the depth of the recursion.
11472 ///
11473 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11474 /// if a memcpy should be used instead.
11475 static StmtResult
11476 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11477                                  const ExprBuilder &To, const ExprBuilder &From,
11478                                  bool CopyingBaseSubobject, bool Copying,
11479                                  unsigned Depth = 0) {
11480   // C++11 [class.copy]p28:
11481   //   Each subobject is assigned in the manner appropriate to its type:
11482   //
11483   //     - if the subobject is of class type, as if by a call to operator= with
11484   //       the subobject as the object expression and the corresponding
11485   //       subobject of x as a single function argument (as if by explicit
11486   //       qualification; that is, ignoring any possible virtual overriding
11487   //       functions in more derived classes);
11488   //
11489   // C++03 [class.copy]p13:
11490   //     - if the subobject is of class type, the copy assignment operator for
11491   //       the class is used (as if by explicit qualification; that is,
11492   //       ignoring any possible virtual overriding functions in more derived
11493   //       classes);
11494   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11495     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11496 
11497     // Look for operator=.
11498     DeclarationName Name
11499       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11500     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11501     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11502 
11503     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11504     // operator.
11505     if (!S.getLangOpts().CPlusPlus11) {
11506       LookupResult::Filter F = OpLookup.makeFilter();
11507       while (F.hasNext()) {
11508         NamedDecl *D = F.next();
11509         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11510           if (Method->isCopyAssignmentOperator() ||
11511               (!Copying && Method->isMoveAssignmentOperator()))
11512             continue;
11513 
11514         F.erase();
11515       }
11516       F.done();
11517     }
11518 
11519     // Suppress the protected check (C++ [class.protected]) for each of the
11520     // assignment operators we found. This strange dance is required when
11521     // we're assigning via a base classes's copy-assignment operator. To
11522     // ensure that we're getting the right base class subobject (without
11523     // ambiguities), we need to cast "this" to that subobject type; to
11524     // ensure that we don't go through the virtual call mechanism, we need
11525     // to qualify the operator= name with the base class (see below). However,
11526     // this means that if the base class has a protected copy assignment
11527     // operator, the protected member access check will fail. So, we
11528     // rewrite "protected" access to "public" access in this case, since we
11529     // know by construction that we're calling from a derived class.
11530     if (CopyingBaseSubobject) {
11531       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11532            L != LEnd; ++L) {
11533         if (L.getAccess() == AS_protected)
11534           L.setAccess(AS_public);
11535       }
11536     }
11537 
11538     // Create the nested-name-specifier that will be used to qualify the
11539     // reference to operator=; this is required to suppress the virtual
11540     // call mechanism.
11541     CXXScopeSpec SS;
11542     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11543     SS.MakeTrivial(S.Context,
11544                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11545                                                CanonicalT),
11546                    Loc);
11547 
11548     // Create the reference to operator=.
11549     ExprResult OpEqualRef
11550       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11551                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11552                                    /*FirstQualifierInScope=*/nullptr,
11553                                    OpLookup,
11554                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11555                                    /*SuppressQualifierCheck=*/true);
11556     if (OpEqualRef.isInvalid())
11557       return StmtError();
11558 
11559     // Build the call to the assignment operator.
11560 
11561     Expr *FromInst = From.build(S, Loc);
11562     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11563                                                   OpEqualRef.getAs<Expr>(),
11564                                                   Loc, FromInst, Loc);
11565     if (Call.isInvalid())
11566       return StmtError();
11567 
11568     // If we built a call to a trivial 'operator=' while copying an array,
11569     // bail out. We'll replace the whole shebang with a memcpy.
11570     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11571     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11572       return StmtResult((Stmt*)nullptr);
11573 
11574     // Convert to an expression-statement, and clean up any produced
11575     // temporaries.
11576     return S.ActOnExprStmt(Call);
11577   }
11578 
11579   //     - if the subobject is of scalar type, the built-in assignment
11580   //       operator is used.
11581   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11582   if (!ArrayTy) {
11583     ExprResult Assignment = S.CreateBuiltinBinOp(
11584         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11585     if (Assignment.isInvalid())
11586       return StmtError();
11587     return S.ActOnExprStmt(Assignment);
11588   }
11589 
11590   //     - if the subobject is an array, each element is assigned, in the
11591   //       manner appropriate to the element type;
11592 
11593   // Construct a loop over the array bounds, e.g.,
11594   //
11595   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11596   //
11597   // that will copy each of the array elements.
11598   QualType SizeType = S.Context.getSizeType();
11599 
11600   // Create the iteration variable.
11601   IdentifierInfo *IterationVarName = nullptr;
11602   {
11603     SmallString<8> Str;
11604     llvm::raw_svector_ostream OS(Str);
11605     OS << "__i" << Depth;
11606     IterationVarName = &S.Context.Idents.get(OS.str());
11607   }
11608   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11609                                           IterationVarName, SizeType,
11610                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11611                                           SC_None);
11612 
11613   // Initialize the iteration variable to zero.
11614   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11615   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11616 
11617   // Creates a reference to the iteration variable.
11618   RefBuilder IterationVarRef(IterationVar, SizeType);
11619   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11620 
11621   // Create the DeclStmt that holds the iteration variable.
11622   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11623 
11624   // Subscript the "from" and "to" expressions with the iteration variable.
11625   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11626   MoveCastBuilder FromIndexMove(FromIndexCopy);
11627   const ExprBuilder *FromIndex;
11628   if (Copying)
11629     FromIndex = &FromIndexCopy;
11630   else
11631     FromIndex = &FromIndexMove;
11632 
11633   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11634 
11635   // Build the copy/move for an individual element of the array.
11636   StmtResult Copy =
11637     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11638                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11639                                      Copying, Depth + 1);
11640   // Bail out if copying fails or if we determined that we should use memcpy.
11641   if (Copy.isInvalid() || !Copy.get())
11642     return Copy;
11643 
11644   // Create the comparison against the array bound.
11645   llvm::APInt Upper
11646     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11647   Expr *Comparison
11648     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11649                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11650                                      BO_NE, S.Context.BoolTy,
11651                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
11652 
11653   // Create the pre-increment of the iteration variable. We can determine
11654   // whether the increment will overflow based on the value of the array
11655   // bound.
11656   Expr *Increment = new (S.Context)
11657       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11658                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11659 
11660   // Construct the loop that copies all elements of this array.
11661   return S.ActOnForStmt(
11662       Loc, Loc, InitStmt,
11663       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11664       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11665 }
11666 
11667 static StmtResult
11668 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11669                       const ExprBuilder &To, const ExprBuilder &From,
11670                       bool CopyingBaseSubobject, bool Copying) {
11671   // Maybe we should use a memcpy?
11672   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11673       T.isTriviallyCopyableType(S.Context))
11674     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11675 
11676   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11677                                                      CopyingBaseSubobject,
11678                                                      Copying, 0));
11679 
11680   // If we ended up picking a trivial assignment operator for an array of a
11681   // non-trivially-copyable class type, just emit a memcpy.
11682   if (!Result.isInvalid() && !Result.get())
11683     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11684 
11685   return Result;
11686 }
11687 
11688 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11689   // Note: The following rules are largely analoguous to the copy
11690   // constructor rules. Note that virtual bases are not taken into account
11691   // for determining the argument type of the operator. Note also that
11692   // operators taking an object instead of a reference are allowed.
11693   assert(ClassDecl->needsImplicitCopyAssignment());
11694 
11695   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11696   if (DSM.isAlreadyBeingDeclared())
11697     return nullptr;
11698 
11699   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11700   QualType RetType = Context.getLValueReferenceType(ArgType);
11701   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11702   if (Const)
11703     ArgType = ArgType.withConst();
11704   ArgType = Context.getLValueReferenceType(ArgType);
11705 
11706   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11707                                                      CXXCopyAssignment,
11708                                                      Const);
11709 
11710   //   An implicitly-declared copy assignment operator is an inline public
11711   //   member of its class.
11712   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11713   SourceLocation ClassLoc = ClassDecl->getLocation();
11714   DeclarationNameInfo NameInfo(Name, ClassLoc);
11715   CXXMethodDecl *CopyAssignment =
11716       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11717                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11718                             /*isInline=*/true, Constexpr, SourceLocation());
11719   CopyAssignment->setAccess(AS_public);
11720   CopyAssignment->setDefaulted();
11721   CopyAssignment->setImplicit();
11722 
11723   if (getLangOpts().CUDA) {
11724     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11725                                             CopyAssignment,
11726                                             /* ConstRHS */ Const,
11727                                             /* Diagnose */ false);
11728   }
11729 
11730   // Build an exception specification pointing back at this member.
11731   FunctionProtoType::ExtProtoInfo EPI =
11732       getImplicitMethodEPI(*this, CopyAssignment);
11733   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11734 
11735   // Add the parameter to the operator.
11736   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11737                                                ClassLoc, ClassLoc,
11738                                                /*Id=*/nullptr, ArgType,
11739                                                /*TInfo=*/nullptr, SC_None,
11740                                                nullptr);
11741   CopyAssignment->setParams(FromParam);
11742 
11743   CopyAssignment->setTrivial(
11744     ClassDecl->needsOverloadResolutionForCopyAssignment()
11745       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11746       : ClassDecl->hasTrivialCopyAssignment());
11747 
11748   // Note that we have added this copy-assignment operator.
11749   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11750 
11751   Scope *S = getScopeForContext(ClassDecl);
11752   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11753 
11754   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11755     SetDeclDeleted(CopyAssignment, ClassLoc);
11756 
11757   if (S)
11758     PushOnScopeChains(CopyAssignment, S, false);
11759   ClassDecl->addDecl(CopyAssignment);
11760 
11761   return CopyAssignment;
11762 }
11763 
11764 /// Diagnose an implicit copy operation for a class which is odr-used, but
11765 /// which is deprecated because the class has a user-declared copy constructor,
11766 /// copy assignment operator, or destructor.
11767 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11768   assert(CopyOp->isImplicit());
11769 
11770   CXXRecordDecl *RD = CopyOp->getParent();
11771   CXXMethodDecl *UserDeclaredOperation = nullptr;
11772 
11773   // In Microsoft mode, assignment operations don't affect constructors and
11774   // vice versa.
11775   if (RD->hasUserDeclaredDestructor()) {
11776     UserDeclaredOperation = RD->getDestructor();
11777   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11778              RD->hasUserDeclaredCopyConstructor() &&
11779              !S.getLangOpts().MSVCCompat) {
11780     // Find any user-declared copy constructor.
11781     for (auto *I : RD->ctors()) {
11782       if (I->isCopyConstructor()) {
11783         UserDeclaredOperation = I;
11784         break;
11785       }
11786     }
11787     assert(UserDeclaredOperation);
11788   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11789              RD->hasUserDeclaredCopyAssignment() &&
11790              !S.getLangOpts().MSVCCompat) {
11791     // Find any user-declared move assignment operator.
11792     for (auto *I : RD->methods()) {
11793       if (I->isCopyAssignmentOperator()) {
11794         UserDeclaredOperation = I;
11795         break;
11796       }
11797     }
11798     assert(UserDeclaredOperation);
11799   }
11800 
11801   if (UserDeclaredOperation) {
11802     S.Diag(UserDeclaredOperation->getLocation(),
11803          diag::warn_deprecated_copy_operation)
11804       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11805       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11806   }
11807 }
11808 
11809 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11810                                         CXXMethodDecl *CopyAssignOperator) {
11811   assert((CopyAssignOperator->isDefaulted() &&
11812           CopyAssignOperator->isOverloadedOperator() &&
11813           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11814           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11815           !CopyAssignOperator->isDeleted()) &&
11816          "DefineImplicitCopyAssignment called for wrong function");
11817   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11818     return;
11819 
11820   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11821   if (ClassDecl->isInvalidDecl()) {
11822     CopyAssignOperator->setInvalidDecl();
11823     return;
11824   }
11825 
11826   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11827 
11828   // The exception specification is needed because we are defining the
11829   // function.
11830   ResolveExceptionSpec(CurrentLocation,
11831                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11832 
11833   // Add a context note for diagnostics produced after this point.
11834   Scope.addContextNote(CurrentLocation);
11835 
11836   // C++11 [class.copy]p18:
11837   //   The [definition of an implicitly declared copy assignment operator] is
11838   //   deprecated if the class has a user-declared copy constructor or a
11839   //   user-declared destructor.
11840   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11841     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11842 
11843   // C++0x [class.copy]p30:
11844   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11845   //   for a non-union class X performs memberwise copy assignment of its
11846   //   subobjects. The direct base classes of X are assigned first, in the
11847   //   order of their declaration in the base-specifier-list, and then the
11848   //   immediate non-static data members of X are assigned, in the order in
11849   //   which they were declared in the class definition.
11850 
11851   // The statements that form the synthesized function body.
11852   SmallVector<Stmt*, 8> Statements;
11853 
11854   // The parameter for the "other" object, which we are copying from.
11855   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11856   Qualifiers OtherQuals = Other->getType().getQualifiers();
11857   QualType OtherRefType = Other->getType();
11858   if (const LValueReferenceType *OtherRef
11859                                 = OtherRefType->getAs<LValueReferenceType>()) {
11860     OtherRefType = OtherRef->getPointeeType();
11861     OtherQuals = OtherRefType.getQualifiers();
11862   }
11863 
11864   // Our location for everything implicitly-generated.
11865   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11866                            ? CopyAssignOperator->getLocEnd()
11867                            : CopyAssignOperator->getLocation();
11868 
11869   // Builds a DeclRefExpr for the "other" object.
11870   RefBuilder OtherRef(Other, OtherRefType);
11871 
11872   // Builds the "this" pointer.
11873   ThisBuilder This;
11874 
11875   // Assign base classes.
11876   bool Invalid = false;
11877   for (auto &Base : ClassDecl->bases()) {
11878     // Form the assignment:
11879     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11880     QualType BaseType = Base.getType().getUnqualifiedType();
11881     if (!BaseType->isRecordType()) {
11882       Invalid = true;
11883       continue;
11884     }
11885 
11886     CXXCastPath BasePath;
11887     BasePath.push_back(&Base);
11888 
11889     // Construct the "from" expression, which is an implicit cast to the
11890     // appropriately-qualified base type.
11891     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11892                      VK_LValue, BasePath);
11893 
11894     // Dereference "this".
11895     DerefBuilder DerefThis(This);
11896     CastBuilder To(DerefThis,
11897                    Context.getCVRQualifiedType(
11898                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11899                    VK_LValue, BasePath);
11900 
11901     // Build the copy.
11902     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11903                                             To, From,
11904                                             /*CopyingBaseSubobject=*/true,
11905                                             /*Copying=*/true);
11906     if (Copy.isInvalid()) {
11907       CopyAssignOperator->setInvalidDecl();
11908       return;
11909     }
11910 
11911     // Success! Record the copy.
11912     Statements.push_back(Copy.getAs<Expr>());
11913   }
11914 
11915   // Assign non-static members.
11916   for (auto *Field : ClassDecl->fields()) {
11917     // FIXME: We should form some kind of AST representation for the implied
11918     // memcpy in a union copy operation.
11919     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11920       continue;
11921 
11922     if (Field->isInvalidDecl()) {
11923       Invalid = true;
11924       continue;
11925     }
11926 
11927     // Check for members of reference type; we can't copy those.
11928     if (Field->getType()->isReferenceType()) {
11929       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11930         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11931       Diag(Field->getLocation(), diag::note_declared_at);
11932       Invalid = true;
11933       continue;
11934     }
11935 
11936     // Check for members of const-qualified, non-class type.
11937     QualType BaseType = Context.getBaseElementType(Field->getType());
11938     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11939       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11940         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11941       Diag(Field->getLocation(), diag::note_declared_at);
11942       Invalid = true;
11943       continue;
11944     }
11945 
11946     // Suppress assigning zero-width bitfields.
11947     if (Field->isZeroLengthBitField(Context))
11948       continue;
11949 
11950     QualType FieldType = Field->getType().getNonReferenceType();
11951     if (FieldType->isIncompleteArrayType()) {
11952       assert(ClassDecl->hasFlexibleArrayMember() &&
11953              "Incomplete array type is not valid");
11954       continue;
11955     }
11956 
11957     // Build references to the field in the object we're copying from and to.
11958     CXXScopeSpec SS; // Intentionally empty
11959     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11960                               LookupMemberName);
11961     MemberLookup.addDecl(Field);
11962     MemberLookup.resolveKind();
11963 
11964     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11965 
11966     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11967 
11968     // Build the copy of this field.
11969     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11970                                             To, From,
11971                                             /*CopyingBaseSubobject=*/false,
11972                                             /*Copying=*/true);
11973     if (Copy.isInvalid()) {
11974       CopyAssignOperator->setInvalidDecl();
11975       return;
11976     }
11977 
11978     // Success! Record the copy.
11979     Statements.push_back(Copy.getAs<Stmt>());
11980   }
11981 
11982   if (!Invalid) {
11983     // Add a "return *this;"
11984     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11985 
11986     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11987     if (Return.isInvalid())
11988       Invalid = true;
11989     else
11990       Statements.push_back(Return.getAs<Stmt>());
11991   }
11992 
11993   if (Invalid) {
11994     CopyAssignOperator->setInvalidDecl();
11995     return;
11996   }
11997 
11998   StmtResult Body;
11999   {
12000     CompoundScopeRAII CompoundScope(*this);
12001     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12002                              /*isStmtExpr=*/false);
12003     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12004   }
12005   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12006   CopyAssignOperator->markUsed(Context);
12007 
12008   if (ASTMutationListener *L = getASTMutationListener()) {
12009     L->CompletedImplicitDefinition(CopyAssignOperator);
12010   }
12011 }
12012 
12013 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12014   assert(ClassDecl->needsImplicitMoveAssignment());
12015 
12016   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12017   if (DSM.isAlreadyBeingDeclared())
12018     return nullptr;
12019 
12020   // Note: The following rules are largely analoguous to the move
12021   // constructor rules.
12022 
12023   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12024   QualType RetType = Context.getLValueReferenceType(ArgType);
12025   ArgType = Context.getRValueReferenceType(ArgType);
12026 
12027   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12028                                                      CXXMoveAssignment,
12029                                                      false);
12030 
12031   //   An implicitly-declared move assignment operator is an inline public
12032   //   member of its class.
12033   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12034   SourceLocation ClassLoc = ClassDecl->getLocation();
12035   DeclarationNameInfo NameInfo(Name, ClassLoc);
12036   CXXMethodDecl *MoveAssignment =
12037       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12038                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12039                             /*isInline=*/true, Constexpr, SourceLocation());
12040   MoveAssignment->setAccess(AS_public);
12041   MoveAssignment->setDefaulted();
12042   MoveAssignment->setImplicit();
12043 
12044   if (getLangOpts().CUDA) {
12045     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12046                                             MoveAssignment,
12047                                             /* ConstRHS */ false,
12048                                             /* Diagnose */ false);
12049   }
12050 
12051   // Build an exception specification pointing back at this member.
12052   FunctionProtoType::ExtProtoInfo EPI =
12053       getImplicitMethodEPI(*this, MoveAssignment);
12054   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12055 
12056   // Add the parameter to the operator.
12057   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12058                                                ClassLoc, ClassLoc,
12059                                                /*Id=*/nullptr, ArgType,
12060                                                /*TInfo=*/nullptr, SC_None,
12061                                                nullptr);
12062   MoveAssignment->setParams(FromParam);
12063 
12064   MoveAssignment->setTrivial(
12065     ClassDecl->needsOverloadResolutionForMoveAssignment()
12066       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12067       : ClassDecl->hasTrivialMoveAssignment());
12068 
12069   // Note that we have added this copy-assignment operator.
12070   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
12071 
12072   Scope *S = getScopeForContext(ClassDecl);
12073   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12074 
12075   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12076     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12077     SetDeclDeleted(MoveAssignment, ClassLoc);
12078   }
12079 
12080   if (S)
12081     PushOnScopeChains(MoveAssignment, S, false);
12082   ClassDecl->addDecl(MoveAssignment);
12083 
12084   return MoveAssignment;
12085 }
12086 
12087 /// Check if we're implicitly defining a move assignment operator for a class
12088 /// with virtual bases. Such a move assignment might move-assign the virtual
12089 /// base multiple times.
12090 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12091                                                SourceLocation CurrentLocation) {
12092   assert(!Class->isDependentContext() && "should not define dependent move");
12093 
12094   // Only a virtual base could get implicitly move-assigned multiple times.
12095   // Only a non-trivial move assignment can observe this. We only want to
12096   // diagnose if we implicitly define an assignment operator that assigns
12097   // two base classes, both of which move-assign the same virtual base.
12098   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12099       Class->getNumBases() < 2)
12100     return;
12101 
12102   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12103   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12104   VBaseMap VBases;
12105 
12106   for (auto &BI : Class->bases()) {
12107     Worklist.push_back(&BI);
12108     while (!Worklist.empty()) {
12109       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12110       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12111 
12112       // If the base has no non-trivial move assignment operators,
12113       // we don't care about moves from it.
12114       if (!Base->hasNonTrivialMoveAssignment())
12115         continue;
12116 
12117       // If there's nothing virtual here, skip it.
12118       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12119         continue;
12120 
12121       // If we're not actually going to call a move assignment for this base,
12122       // or the selected move assignment is trivial, skip it.
12123       Sema::SpecialMemberOverloadResult SMOR =
12124         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12125                               /*ConstArg*/false, /*VolatileArg*/false,
12126                               /*RValueThis*/true, /*ConstThis*/false,
12127                               /*VolatileThis*/false);
12128       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12129           !SMOR.getMethod()->isMoveAssignmentOperator())
12130         continue;
12131 
12132       if (BaseSpec->isVirtual()) {
12133         // We're going to move-assign this virtual base, and its move
12134         // assignment operator is not trivial. If this can happen for
12135         // multiple distinct direct bases of Class, diagnose it. (If it
12136         // only happens in one base, we'll diagnose it when synthesizing
12137         // that base class's move assignment operator.)
12138         CXXBaseSpecifier *&Existing =
12139             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12140                 .first->second;
12141         if (Existing && Existing != &BI) {
12142           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12143             << Class << Base;
12144           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
12145             << (Base->getCanonicalDecl() ==
12146                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12147             << Base << Existing->getType() << Existing->getSourceRange();
12148           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
12149             << (Base->getCanonicalDecl() ==
12150                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12151             << Base << BI.getType() << BaseSpec->getSourceRange();
12152 
12153           // Only diagnose each vbase once.
12154           Existing = nullptr;
12155         }
12156       } else {
12157         // Only walk over bases that have defaulted move assignment operators.
12158         // We assume that any user-provided move assignment operator handles
12159         // the multiple-moves-of-vbase case itself somehow.
12160         if (!SMOR.getMethod()->isDefaulted())
12161           continue;
12162 
12163         // We're going to move the base classes of Base. Add them to the list.
12164         for (auto &BI : Base->bases())
12165           Worklist.push_back(&BI);
12166       }
12167     }
12168   }
12169 }
12170 
12171 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12172                                         CXXMethodDecl *MoveAssignOperator) {
12173   assert((MoveAssignOperator->isDefaulted() &&
12174           MoveAssignOperator->isOverloadedOperator() &&
12175           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12176           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12177           !MoveAssignOperator->isDeleted()) &&
12178          "DefineImplicitMoveAssignment called for wrong function");
12179   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12180     return;
12181 
12182   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12183   if (ClassDecl->isInvalidDecl()) {
12184     MoveAssignOperator->setInvalidDecl();
12185     return;
12186   }
12187 
12188   // C++0x [class.copy]p28:
12189   //   The implicitly-defined or move assignment operator for a non-union class
12190   //   X performs memberwise move assignment of its subobjects. The direct base
12191   //   classes of X are assigned first, in the order of their declaration in the
12192   //   base-specifier-list, and then the immediate non-static data members of X
12193   //   are assigned, in the order in which they were declared in the class
12194   //   definition.
12195 
12196   // Issue a warning if our implicit move assignment operator will move
12197   // from a virtual base more than once.
12198   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12199 
12200   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12201 
12202   // The exception specification is needed because we are defining the
12203   // function.
12204   ResolveExceptionSpec(CurrentLocation,
12205                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12206 
12207   // Add a context note for diagnostics produced after this point.
12208   Scope.addContextNote(CurrentLocation);
12209 
12210   // The statements that form the synthesized function body.
12211   SmallVector<Stmt*, 8> Statements;
12212 
12213   // The parameter for the "other" object, which we are move from.
12214   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12215   QualType OtherRefType = Other->getType()->
12216       getAs<RValueReferenceType>()->getPointeeType();
12217   assert(!OtherRefType.getQualifiers() &&
12218          "Bad argument type of defaulted move assignment");
12219 
12220   // Our location for everything implicitly-generated.
12221   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
12222                            ? MoveAssignOperator->getLocEnd()
12223                            : MoveAssignOperator->getLocation();
12224 
12225   // Builds a reference to the "other" object.
12226   RefBuilder OtherRef(Other, OtherRefType);
12227   // Cast to rvalue.
12228   MoveCastBuilder MoveOther(OtherRef);
12229 
12230   // Builds the "this" pointer.
12231   ThisBuilder This;
12232 
12233   // Assign base classes.
12234   bool Invalid = false;
12235   for (auto &Base : ClassDecl->bases()) {
12236     // C++11 [class.copy]p28:
12237     //   It is unspecified whether subobjects representing virtual base classes
12238     //   are assigned more than once by the implicitly-defined copy assignment
12239     //   operator.
12240     // FIXME: Do not assign to a vbase that will be assigned by some other base
12241     // class. For a move-assignment, this can result in the vbase being moved
12242     // multiple times.
12243 
12244     // Form the assignment:
12245     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12246     QualType BaseType = Base.getType().getUnqualifiedType();
12247     if (!BaseType->isRecordType()) {
12248       Invalid = true;
12249       continue;
12250     }
12251 
12252     CXXCastPath BasePath;
12253     BasePath.push_back(&Base);
12254 
12255     // Construct the "from" expression, which is an implicit cast to the
12256     // appropriately-qualified base type.
12257     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12258 
12259     // Dereference "this".
12260     DerefBuilder DerefThis(This);
12261 
12262     // Implicitly cast "this" to the appropriately-qualified base type.
12263     CastBuilder To(DerefThis,
12264                    Context.getCVRQualifiedType(
12265                        BaseType, MoveAssignOperator->getTypeQualifiers()),
12266                    VK_LValue, BasePath);
12267 
12268     // Build the move.
12269     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12270                                             To, From,
12271                                             /*CopyingBaseSubobject=*/true,
12272                                             /*Copying=*/false);
12273     if (Move.isInvalid()) {
12274       MoveAssignOperator->setInvalidDecl();
12275       return;
12276     }
12277 
12278     // Success! Record the move.
12279     Statements.push_back(Move.getAs<Expr>());
12280   }
12281 
12282   // Assign non-static members.
12283   for (auto *Field : ClassDecl->fields()) {
12284     // FIXME: We should form some kind of AST representation for the implied
12285     // memcpy in a union copy operation.
12286     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12287       continue;
12288 
12289     if (Field->isInvalidDecl()) {
12290       Invalid = true;
12291       continue;
12292     }
12293 
12294     // Check for members of reference type; we can't move those.
12295     if (Field->getType()->isReferenceType()) {
12296       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12297         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12298       Diag(Field->getLocation(), diag::note_declared_at);
12299       Invalid = true;
12300       continue;
12301     }
12302 
12303     // Check for members of const-qualified, non-class type.
12304     QualType BaseType = Context.getBaseElementType(Field->getType());
12305     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12306       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12307         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12308       Diag(Field->getLocation(), diag::note_declared_at);
12309       Invalid = true;
12310       continue;
12311     }
12312 
12313     // Suppress assigning zero-width bitfields.
12314     if (Field->isZeroLengthBitField(Context))
12315       continue;
12316 
12317     QualType FieldType = Field->getType().getNonReferenceType();
12318     if (FieldType->isIncompleteArrayType()) {
12319       assert(ClassDecl->hasFlexibleArrayMember() &&
12320              "Incomplete array type is not valid");
12321       continue;
12322     }
12323 
12324     // Build references to the field in the object we're copying from and to.
12325     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12326                               LookupMemberName);
12327     MemberLookup.addDecl(Field);
12328     MemberLookup.resolveKind();
12329     MemberBuilder From(MoveOther, OtherRefType,
12330                        /*IsArrow=*/false, MemberLookup);
12331     MemberBuilder To(This, getCurrentThisType(),
12332                      /*IsArrow=*/true, MemberLookup);
12333 
12334     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12335         "Member reference with rvalue base must be rvalue except for reference "
12336         "members, which aren't allowed for move assignment.");
12337 
12338     // Build the move of this field.
12339     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12340                                             To, From,
12341                                             /*CopyingBaseSubobject=*/false,
12342                                             /*Copying=*/false);
12343     if (Move.isInvalid()) {
12344       MoveAssignOperator->setInvalidDecl();
12345       return;
12346     }
12347 
12348     // Success! Record the copy.
12349     Statements.push_back(Move.getAs<Stmt>());
12350   }
12351 
12352   if (!Invalid) {
12353     // Add a "return *this;"
12354     ExprResult ThisObj =
12355         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12356 
12357     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12358     if (Return.isInvalid())
12359       Invalid = true;
12360     else
12361       Statements.push_back(Return.getAs<Stmt>());
12362   }
12363 
12364   if (Invalid) {
12365     MoveAssignOperator->setInvalidDecl();
12366     return;
12367   }
12368 
12369   StmtResult Body;
12370   {
12371     CompoundScopeRAII CompoundScope(*this);
12372     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12373                              /*isStmtExpr=*/false);
12374     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12375   }
12376   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12377   MoveAssignOperator->markUsed(Context);
12378 
12379   if (ASTMutationListener *L = getASTMutationListener()) {
12380     L->CompletedImplicitDefinition(MoveAssignOperator);
12381   }
12382 }
12383 
12384 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12385                                                     CXXRecordDecl *ClassDecl) {
12386   // C++ [class.copy]p4:
12387   //   If the class definition does not explicitly declare a copy
12388   //   constructor, one is declared implicitly.
12389   assert(ClassDecl->needsImplicitCopyConstructor());
12390 
12391   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12392   if (DSM.isAlreadyBeingDeclared())
12393     return nullptr;
12394 
12395   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12396   QualType ArgType = ClassType;
12397   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12398   if (Const)
12399     ArgType = ArgType.withConst();
12400   ArgType = Context.getLValueReferenceType(ArgType);
12401 
12402   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12403                                                      CXXCopyConstructor,
12404                                                      Const);
12405 
12406   DeclarationName Name
12407     = Context.DeclarationNames.getCXXConstructorName(
12408                                            Context.getCanonicalType(ClassType));
12409   SourceLocation ClassLoc = ClassDecl->getLocation();
12410   DeclarationNameInfo NameInfo(Name, ClassLoc);
12411 
12412   //   An implicitly-declared copy constructor is an inline public
12413   //   member of its class.
12414   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12415       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12416       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12417       Constexpr);
12418   CopyConstructor->setAccess(AS_public);
12419   CopyConstructor->setDefaulted();
12420 
12421   if (getLangOpts().CUDA) {
12422     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12423                                             CopyConstructor,
12424                                             /* ConstRHS */ Const,
12425                                             /* Diagnose */ false);
12426   }
12427 
12428   // Build an exception specification pointing back at this member.
12429   FunctionProtoType::ExtProtoInfo EPI =
12430       getImplicitMethodEPI(*this, CopyConstructor);
12431   CopyConstructor->setType(
12432       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12433 
12434   // Add the parameter to the constructor.
12435   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12436                                                ClassLoc, ClassLoc,
12437                                                /*IdentifierInfo=*/nullptr,
12438                                                ArgType, /*TInfo=*/nullptr,
12439                                                SC_None, nullptr);
12440   CopyConstructor->setParams(FromParam);
12441 
12442   CopyConstructor->setTrivial(
12443       ClassDecl->needsOverloadResolutionForCopyConstructor()
12444           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12445           : ClassDecl->hasTrivialCopyConstructor());
12446 
12447   CopyConstructor->setTrivialForCall(
12448       ClassDecl->hasAttr<TrivialABIAttr>() ||
12449       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12450            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12451              TAH_ConsiderTrivialABI)
12452            : ClassDecl->hasTrivialCopyConstructorForCall()));
12453 
12454   // Note that we have declared this constructor.
12455   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12456 
12457   Scope *S = getScopeForContext(ClassDecl);
12458   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12459 
12460   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12461     ClassDecl->setImplicitCopyConstructorIsDeleted();
12462     SetDeclDeleted(CopyConstructor, ClassLoc);
12463   }
12464 
12465   if (S)
12466     PushOnScopeChains(CopyConstructor, S, false);
12467   ClassDecl->addDecl(CopyConstructor);
12468 
12469   return CopyConstructor;
12470 }
12471 
12472 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12473                                          CXXConstructorDecl *CopyConstructor) {
12474   assert((CopyConstructor->isDefaulted() &&
12475           CopyConstructor->isCopyConstructor() &&
12476           !CopyConstructor->doesThisDeclarationHaveABody() &&
12477           !CopyConstructor->isDeleted()) &&
12478          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12479   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12480     return;
12481 
12482   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12483   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12484 
12485   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12486 
12487   // The exception specification is needed because we are defining the
12488   // function.
12489   ResolveExceptionSpec(CurrentLocation,
12490                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12491   MarkVTableUsed(CurrentLocation, ClassDecl);
12492 
12493   // Add a context note for diagnostics produced after this point.
12494   Scope.addContextNote(CurrentLocation);
12495 
12496   // C++11 [class.copy]p7:
12497   //   The [definition of an implicitly declared copy constructor] is
12498   //   deprecated if the class has a user-declared copy assignment operator
12499   //   or a user-declared destructor.
12500   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12501     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12502 
12503   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12504     CopyConstructor->setInvalidDecl();
12505   }  else {
12506     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12507                              ? CopyConstructor->getLocEnd()
12508                              : CopyConstructor->getLocation();
12509     Sema::CompoundScopeRAII CompoundScope(*this);
12510     CopyConstructor->setBody(
12511         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12512     CopyConstructor->markUsed(Context);
12513   }
12514 
12515   if (ASTMutationListener *L = getASTMutationListener()) {
12516     L->CompletedImplicitDefinition(CopyConstructor);
12517   }
12518 }
12519 
12520 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12521                                                     CXXRecordDecl *ClassDecl) {
12522   assert(ClassDecl->needsImplicitMoveConstructor());
12523 
12524   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12525   if (DSM.isAlreadyBeingDeclared())
12526     return nullptr;
12527 
12528   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12529   QualType ArgType = Context.getRValueReferenceType(ClassType);
12530 
12531   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12532                                                      CXXMoveConstructor,
12533                                                      false);
12534 
12535   DeclarationName Name
12536     = Context.DeclarationNames.getCXXConstructorName(
12537                                            Context.getCanonicalType(ClassType));
12538   SourceLocation ClassLoc = ClassDecl->getLocation();
12539   DeclarationNameInfo NameInfo(Name, ClassLoc);
12540 
12541   // C++11 [class.copy]p11:
12542   //   An implicitly-declared copy/move constructor is an inline public
12543   //   member of its class.
12544   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12545       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12546       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12547       Constexpr);
12548   MoveConstructor->setAccess(AS_public);
12549   MoveConstructor->setDefaulted();
12550 
12551   if (getLangOpts().CUDA) {
12552     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12553                                             MoveConstructor,
12554                                             /* ConstRHS */ false,
12555                                             /* Diagnose */ false);
12556   }
12557 
12558   // Build an exception specification pointing back at this member.
12559   FunctionProtoType::ExtProtoInfo EPI =
12560       getImplicitMethodEPI(*this, MoveConstructor);
12561   MoveConstructor->setType(
12562       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12563 
12564   // Add the parameter to the constructor.
12565   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12566                                                ClassLoc, ClassLoc,
12567                                                /*IdentifierInfo=*/nullptr,
12568                                                ArgType, /*TInfo=*/nullptr,
12569                                                SC_None, nullptr);
12570   MoveConstructor->setParams(FromParam);
12571 
12572   MoveConstructor->setTrivial(
12573       ClassDecl->needsOverloadResolutionForMoveConstructor()
12574           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12575           : ClassDecl->hasTrivialMoveConstructor());
12576 
12577   MoveConstructor->setTrivialForCall(
12578       ClassDecl->hasAttr<TrivialABIAttr>() ||
12579       (ClassDecl->needsOverloadResolutionForMoveConstructor()
12580            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12581                                     TAH_ConsiderTrivialABI)
12582            : ClassDecl->hasTrivialMoveConstructorForCall()));
12583 
12584   // Note that we have declared this constructor.
12585   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12586 
12587   Scope *S = getScopeForContext(ClassDecl);
12588   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12589 
12590   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12591     ClassDecl->setImplicitMoveConstructorIsDeleted();
12592     SetDeclDeleted(MoveConstructor, ClassLoc);
12593   }
12594 
12595   if (S)
12596     PushOnScopeChains(MoveConstructor, S, false);
12597   ClassDecl->addDecl(MoveConstructor);
12598 
12599   return MoveConstructor;
12600 }
12601 
12602 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12603                                          CXXConstructorDecl *MoveConstructor) {
12604   assert((MoveConstructor->isDefaulted() &&
12605           MoveConstructor->isMoveConstructor() &&
12606           !MoveConstructor->doesThisDeclarationHaveABody() &&
12607           !MoveConstructor->isDeleted()) &&
12608          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12609   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12610     return;
12611 
12612   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12613   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12614 
12615   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12616 
12617   // The exception specification is needed because we are defining the
12618   // function.
12619   ResolveExceptionSpec(CurrentLocation,
12620                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12621   MarkVTableUsed(CurrentLocation, ClassDecl);
12622 
12623   // Add a context note for diagnostics produced after this point.
12624   Scope.addContextNote(CurrentLocation);
12625 
12626   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12627     MoveConstructor->setInvalidDecl();
12628   } else {
12629     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12630                              ? MoveConstructor->getLocEnd()
12631                              : MoveConstructor->getLocation();
12632     Sema::CompoundScopeRAII CompoundScope(*this);
12633     MoveConstructor->setBody(ActOnCompoundStmt(
12634         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12635     MoveConstructor->markUsed(Context);
12636   }
12637 
12638   if (ASTMutationListener *L = getASTMutationListener()) {
12639     L->CompletedImplicitDefinition(MoveConstructor);
12640   }
12641 }
12642 
12643 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12644   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12645 }
12646 
12647 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12648                             SourceLocation CurrentLocation,
12649                             CXXConversionDecl *Conv) {
12650   SynthesizedFunctionScope Scope(*this, Conv);
12651   assert(!Conv->getReturnType()->isUndeducedType());
12652 
12653   CXXRecordDecl *Lambda = Conv->getParent();
12654   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12655   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12656 
12657   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12658     CallOp = InstantiateFunctionDeclaration(
12659         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12660     if (!CallOp)
12661       return;
12662 
12663     Invoker = InstantiateFunctionDeclaration(
12664         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12665     if (!Invoker)
12666       return;
12667   }
12668 
12669   if (CallOp->isInvalidDecl())
12670     return;
12671 
12672   // Mark the call operator referenced (and add to pending instantiations
12673   // if necessary).
12674   // For both the conversion and static-invoker template specializations
12675   // we construct their body's in this function, so no need to add them
12676   // to the PendingInstantiations.
12677   MarkFunctionReferenced(CurrentLocation, CallOp);
12678 
12679   // Fill in the __invoke function with a dummy implementation. IR generation
12680   // will fill in the actual details. Update its type in case it contained
12681   // an 'auto'.
12682   Invoker->markUsed(Context);
12683   Invoker->setReferenced();
12684   Invoker->setType(Conv->getReturnType()->getPointeeType());
12685   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12686 
12687   // Construct the body of the conversion function { return __invoke; }.
12688   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12689                                        VK_LValue, Conv->getLocation()).get();
12690   assert(FunctionRef && "Can't refer to __invoke function?");
12691   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12692   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12693                                      Conv->getLocation()));
12694   Conv->markUsed(Context);
12695   Conv->setReferenced();
12696 
12697   if (ASTMutationListener *L = getASTMutationListener()) {
12698     L->CompletedImplicitDefinition(Conv);
12699     L->CompletedImplicitDefinition(Invoker);
12700   }
12701 }
12702 
12703 
12704 
12705 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12706        SourceLocation CurrentLocation,
12707        CXXConversionDecl *Conv)
12708 {
12709   assert(!Conv->getParent()->isGenericLambda());
12710 
12711   SynthesizedFunctionScope Scope(*this, Conv);
12712 
12713   // Copy-initialize the lambda object as needed to capture it.
12714   Expr *This = ActOnCXXThis(CurrentLocation).get();
12715   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12716 
12717   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12718                                                         Conv->getLocation(),
12719                                                         Conv, DerefThis);
12720 
12721   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12722   // behavior.  Note that only the general conversion function does this
12723   // (since it's unusable otherwise); in the case where we inline the
12724   // block literal, it has block literal lifetime semantics.
12725   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12726     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12727                                           CK_CopyAndAutoreleaseBlockObject,
12728                                           BuildBlock.get(), nullptr, VK_RValue);
12729 
12730   if (BuildBlock.isInvalid()) {
12731     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12732     Conv->setInvalidDecl();
12733     return;
12734   }
12735 
12736   // Create the return statement that returns the block from the conversion
12737   // function.
12738   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12739   if (Return.isInvalid()) {
12740     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12741     Conv->setInvalidDecl();
12742     return;
12743   }
12744 
12745   // Set the body of the conversion function.
12746   Stmt *ReturnS = Return.get();
12747   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12748                                      Conv->getLocation()));
12749   Conv->markUsed(Context);
12750 
12751   // We're done; notify the mutation listener, if any.
12752   if (ASTMutationListener *L = getASTMutationListener()) {
12753     L->CompletedImplicitDefinition(Conv);
12754   }
12755 }
12756 
12757 /// Determine whether the given list arguments contains exactly one
12758 /// "real" (non-default) argument.
12759 static bool hasOneRealArgument(MultiExprArg Args) {
12760   switch (Args.size()) {
12761   case 0:
12762     return false;
12763 
12764   default:
12765     if (!Args[1]->isDefaultArgument())
12766       return false;
12767 
12768     LLVM_FALLTHROUGH;
12769   case 1:
12770     return !Args[0]->isDefaultArgument();
12771   }
12772 
12773   return false;
12774 }
12775 
12776 ExprResult
12777 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12778                             NamedDecl *FoundDecl,
12779                             CXXConstructorDecl *Constructor,
12780                             MultiExprArg ExprArgs,
12781                             bool HadMultipleCandidates,
12782                             bool IsListInitialization,
12783                             bool IsStdInitListInitialization,
12784                             bool RequiresZeroInit,
12785                             unsigned ConstructKind,
12786                             SourceRange ParenRange) {
12787   bool Elidable = false;
12788 
12789   // C++0x [class.copy]p34:
12790   //   When certain criteria are met, an implementation is allowed to
12791   //   omit the copy/move construction of a class object, even if the
12792   //   copy/move constructor and/or destructor for the object have
12793   //   side effects. [...]
12794   //     - when a temporary class object that has not been bound to a
12795   //       reference (12.2) would be copied/moved to a class object
12796   //       with the same cv-unqualified type, the copy/move operation
12797   //       can be omitted by constructing the temporary object
12798   //       directly into the target of the omitted copy/move
12799   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12800       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12801     Expr *SubExpr = ExprArgs[0];
12802     Elidable = SubExpr->isTemporaryObject(
12803         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12804   }
12805 
12806   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12807                                FoundDecl, Constructor,
12808                                Elidable, ExprArgs, HadMultipleCandidates,
12809                                IsListInitialization,
12810                                IsStdInitListInitialization, RequiresZeroInit,
12811                                ConstructKind, ParenRange);
12812 }
12813 
12814 ExprResult
12815 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12816                             NamedDecl *FoundDecl,
12817                             CXXConstructorDecl *Constructor,
12818                             bool Elidable,
12819                             MultiExprArg ExprArgs,
12820                             bool HadMultipleCandidates,
12821                             bool IsListInitialization,
12822                             bool IsStdInitListInitialization,
12823                             bool RequiresZeroInit,
12824                             unsigned ConstructKind,
12825                             SourceRange ParenRange) {
12826   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12827     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12828     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12829       return ExprError();
12830   }
12831 
12832   return BuildCXXConstructExpr(
12833       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12834       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12835       RequiresZeroInit, ConstructKind, ParenRange);
12836 }
12837 
12838 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12839 /// including handling of its default argument expressions.
12840 ExprResult
12841 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12842                             CXXConstructorDecl *Constructor,
12843                             bool Elidable,
12844                             MultiExprArg ExprArgs,
12845                             bool HadMultipleCandidates,
12846                             bool IsListInitialization,
12847                             bool IsStdInitListInitialization,
12848                             bool RequiresZeroInit,
12849                             unsigned ConstructKind,
12850                             SourceRange ParenRange) {
12851   assert(declaresSameEntity(
12852              Constructor->getParent(),
12853              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12854          "given constructor for wrong type");
12855   MarkFunctionReferenced(ConstructLoc, Constructor);
12856   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12857     return ExprError();
12858 
12859   return CXXConstructExpr::Create(
12860       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12861       ExprArgs, HadMultipleCandidates, IsListInitialization,
12862       IsStdInitListInitialization, RequiresZeroInit,
12863       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12864       ParenRange);
12865 }
12866 
12867 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12868   assert(Field->hasInClassInitializer());
12869 
12870   // If we already have the in-class initializer nothing needs to be done.
12871   if (Field->getInClassInitializer())
12872     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12873 
12874   // If we might have already tried and failed to instantiate, don't try again.
12875   if (Field->isInvalidDecl())
12876     return ExprError();
12877 
12878   // Maybe we haven't instantiated the in-class initializer. Go check the
12879   // pattern FieldDecl to see if it has one.
12880   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12881 
12882   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12883     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12884     DeclContext::lookup_result Lookup =
12885         ClassPattern->lookup(Field->getDeclName());
12886 
12887     // Lookup can return at most two results: the pattern for the field, or the
12888     // injected class name of the parent record. No other member can have the
12889     // same name as the field.
12890     // In modules mode, lookup can return multiple results (coming from
12891     // different modules).
12892     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12893            "more than two lookup results for field name");
12894     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12895     if (!Pattern) {
12896       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12897              "cannot have other non-field member with same name");
12898       for (auto L : Lookup)
12899         if (isa<FieldDecl>(L)) {
12900           Pattern = cast<FieldDecl>(L);
12901           break;
12902         }
12903       assert(Pattern && "We must have set the Pattern!");
12904     }
12905 
12906     if (!Pattern->hasInClassInitializer() ||
12907         InstantiateInClassInitializer(Loc, Field, Pattern,
12908                                       getTemplateInstantiationArgs(Field))) {
12909       // Don't diagnose this again.
12910       Field->setInvalidDecl();
12911       return ExprError();
12912     }
12913     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12914   }
12915 
12916   // DR1351:
12917   //   If the brace-or-equal-initializer of a non-static data member
12918   //   invokes a defaulted default constructor of its class or of an
12919   //   enclosing class in a potentially evaluated subexpression, the
12920   //   program is ill-formed.
12921   //
12922   // This resolution is unworkable: the exception specification of the
12923   // default constructor can be needed in an unevaluated context, in
12924   // particular, in the operand of a noexcept-expression, and we can be
12925   // unable to compute an exception specification for an enclosed class.
12926   //
12927   // Any attempt to resolve the exception specification of a defaulted default
12928   // constructor before the initializer is lexically complete will ultimately
12929   // come here at which point we can diagnose it.
12930   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12931   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12932       << OutermostClass << Field;
12933   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12934   // Recover by marking the field invalid, unless we're in a SFINAE context.
12935   if (!isSFINAEContext())
12936     Field->setInvalidDecl();
12937   return ExprError();
12938 }
12939 
12940 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12941   if (VD->isInvalidDecl()) return;
12942 
12943   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12944   if (ClassDecl->isInvalidDecl()) return;
12945   if (ClassDecl->hasIrrelevantDestructor()) return;
12946   if (ClassDecl->isDependentContext()) return;
12947 
12948   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12949   MarkFunctionReferenced(VD->getLocation(), Destructor);
12950   CheckDestructorAccess(VD->getLocation(), Destructor,
12951                         PDiag(diag::err_access_dtor_var)
12952                         << VD->getDeclName()
12953                         << VD->getType());
12954   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12955 
12956   if (Destructor->isTrivial()) return;
12957   if (!VD->hasGlobalStorage()) return;
12958 
12959   // Emit warning for non-trivial dtor in global scope (a real global,
12960   // class-static, function-static).
12961   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12962 
12963   // TODO: this should be re-enabled for static locals by !CXAAtExit
12964   if (!VD->isStaticLocal())
12965     Diag(VD->getLocation(), diag::warn_global_destructor);
12966 }
12967 
12968 /// Given a constructor and the set of arguments provided for the
12969 /// constructor, convert the arguments and add any required default arguments
12970 /// to form a proper call to this constructor.
12971 ///
12972 /// \returns true if an error occurred, false otherwise.
12973 bool
12974 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12975                               MultiExprArg ArgsPtr,
12976                               SourceLocation Loc,
12977                               SmallVectorImpl<Expr*> &ConvertedArgs,
12978                               bool AllowExplicit,
12979                               bool IsListInitialization) {
12980   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12981   unsigned NumArgs = ArgsPtr.size();
12982   Expr **Args = ArgsPtr.data();
12983 
12984   const FunctionProtoType *Proto
12985     = Constructor->getType()->getAs<FunctionProtoType>();
12986   assert(Proto && "Constructor without a prototype?");
12987   unsigned NumParams = Proto->getNumParams();
12988 
12989   // If too few arguments are available, we'll fill in the rest with defaults.
12990   if (NumArgs < NumParams)
12991     ConvertedArgs.reserve(NumParams);
12992   else
12993     ConvertedArgs.reserve(NumArgs);
12994 
12995   VariadicCallType CallType =
12996     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12997   SmallVector<Expr *, 8> AllArgs;
12998   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12999                                         Proto, 0,
13000                                         llvm::makeArrayRef(Args, NumArgs),
13001                                         AllArgs,
13002                                         CallType, AllowExplicit,
13003                                         IsListInitialization);
13004   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13005 
13006   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13007 
13008   CheckConstructorCall(Constructor,
13009                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13010                        Proto, Loc);
13011 
13012   return Invalid;
13013 }
13014 
13015 static inline bool
13016 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13017                                        const FunctionDecl *FnDecl) {
13018   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13019   if (isa<NamespaceDecl>(DC)) {
13020     return SemaRef.Diag(FnDecl->getLocation(),
13021                         diag::err_operator_new_delete_declared_in_namespace)
13022       << FnDecl->getDeclName();
13023   }
13024 
13025   if (isa<TranslationUnitDecl>(DC) &&
13026       FnDecl->getStorageClass() == SC_Static) {
13027     return SemaRef.Diag(FnDecl->getLocation(),
13028                         diag::err_operator_new_delete_declared_static)
13029       << FnDecl->getDeclName();
13030   }
13031 
13032   return false;
13033 }
13034 
13035 static QualType
13036 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13037   QualType QTy = PtrTy->getPointeeType();
13038   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13039   return SemaRef.Context.getPointerType(QTy);
13040 }
13041 
13042 static inline bool
13043 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13044                             CanQualType ExpectedResultType,
13045                             CanQualType ExpectedFirstParamType,
13046                             unsigned DependentParamTypeDiag,
13047                             unsigned InvalidParamTypeDiag) {
13048   QualType ResultType =
13049       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13050 
13051   // Check that the result type is not dependent.
13052   if (ResultType->isDependentType())
13053     return SemaRef.Diag(FnDecl->getLocation(),
13054                         diag::err_operator_new_delete_dependent_result_type)
13055     << FnDecl->getDeclName() << ExpectedResultType;
13056 
13057   // OpenCL C++: the operator is valid on any address space.
13058   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13059     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13060       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13061     }
13062   }
13063 
13064   // Check that the result type is what we expect.
13065   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13066     return SemaRef.Diag(FnDecl->getLocation(),
13067                         diag::err_operator_new_delete_invalid_result_type)
13068     << FnDecl->getDeclName() << ExpectedResultType;
13069 
13070   // A function template must have at least 2 parameters.
13071   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13072     return SemaRef.Diag(FnDecl->getLocation(),
13073                       diag::err_operator_new_delete_template_too_few_parameters)
13074         << FnDecl->getDeclName();
13075 
13076   // The function decl must have at least 1 parameter.
13077   if (FnDecl->getNumParams() == 0)
13078     return SemaRef.Diag(FnDecl->getLocation(),
13079                         diag::err_operator_new_delete_too_few_parameters)
13080       << FnDecl->getDeclName();
13081 
13082   // Check the first parameter type is not dependent.
13083   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13084   if (FirstParamType->isDependentType())
13085     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13086       << FnDecl->getDeclName() << ExpectedFirstParamType;
13087 
13088   // Check that the first parameter type is what we expect.
13089   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13090     // OpenCL C++: the operator is valid on any address space.
13091     if (auto *PtrTy =
13092             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13093       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13094     }
13095   }
13096   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13097       ExpectedFirstParamType)
13098     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13099     << FnDecl->getDeclName() << ExpectedFirstParamType;
13100 
13101   return false;
13102 }
13103 
13104 static bool
13105 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13106   // C++ [basic.stc.dynamic.allocation]p1:
13107   //   A program is ill-formed if an allocation function is declared in a
13108   //   namespace scope other than global scope or declared static in global
13109   //   scope.
13110   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13111     return true;
13112 
13113   CanQualType SizeTy =
13114     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13115 
13116   // C++ [basic.stc.dynamic.allocation]p1:
13117   //  The return type shall be void*. The first parameter shall have type
13118   //  std::size_t.
13119   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13120                                   SizeTy,
13121                                   diag::err_operator_new_dependent_param_type,
13122                                   diag::err_operator_new_param_type))
13123     return true;
13124 
13125   // C++ [basic.stc.dynamic.allocation]p1:
13126   //  The first parameter shall not have an associated default argument.
13127   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13128     return SemaRef.Diag(FnDecl->getLocation(),
13129                         diag::err_operator_new_default_arg)
13130       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13131 
13132   return false;
13133 }
13134 
13135 static bool
13136 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13137   // C++ [basic.stc.dynamic.deallocation]p1:
13138   //   A program is ill-formed if deallocation functions are declared in a
13139   //   namespace scope other than global scope or declared static in global
13140   //   scope.
13141   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13142     return true;
13143 
13144   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13145 
13146   // C++ P0722:
13147   //   Within a class C, the first parameter of a destroying operator delete
13148   //   shall be of type C *. The first parameter of any other deallocation
13149   //   function shall be of type void *.
13150   CanQualType ExpectedFirstParamType =
13151       MD && MD->isDestroyingOperatorDelete()
13152           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13153                 SemaRef.Context.getRecordType(MD->getParent())))
13154           : SemaRef.Context.VoidPtrTy;
13155 
13156   // C++ [basic.stc.dynamic.deallocation]p2:
13157   //   Each deallocation function shall return void
13158   if (CheckOperatorNewDeleteTypes(
13159           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13160           diag::err_operator_delete_dependent_param_type,
13161           diag::err_operator_delete_param_type))
13162     return true;
13163 
13164   // C++ P0722:
13165   //   A destroying operator delete shall be a usual deallocation function.
13166   if (MD && !MD->getParent()->isDependentContext() &&
13167       MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
13168     SemaRef.Diag(MD->getLocation(),
13169                  diag::err_destroying_operator_delete_not_usual);
13170     return true;
13171   }
13172 
13173   return false;
13174 }
13175 
13176 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13177 /// of this overloaded operator is well-formed. If so, returns false;
13178 /// otherwise, emits appropriate diagnostics and returns true.
13179 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13180   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13181          "Expected an overloaded operator declaration");
13182 
13183   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13184 
13185   // C++ [over.oper]p5:
13186   //   The allocation and deallocation functions, operator new,
13187   //   operator new[], operator delete and operator delete[], are
13188   //   described completely in 3.7.3. The attributes and restrictions
13189   //   found in the rest of this subclause do not apply to them unless
13190   //   explicitly stated in 3.7.3.
13191   if (Op == OO_Delete || Op == OO_Array_Delete)
13192     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13193 
13194   if (Op == OO_New || Op == OO_Array_New)
13195     return CheckOperatorNewDeclaration(*this, FnDecl);
13196 
13197   // C++ [over.oper]p6:
13198   //   An operator function shall either be a non-static member
13199   //   function or be a non-member function and have at least one
13200   //   parameter whose type is a class, a reference to a class, an
13201   //   enumeration, or a reference to an enumeration.
13202   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13203     if (MethodDecl->isStatic())
13204       return Diag(FnDecl->getLocation(),
13205                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13206   } else {
13207     bool ClassOrEnumParam = false;
13208     for (auto Param : FnDecl->parameters()) {
13209       QualType ParamType = Param->getType().getNonReferenceType();
13210       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13211           ParamType->isEnumeralType()) {
13212         ClassOrEnumParam = true;
13213         break;
13214       }
13215     }
13216 
13217     if (!ClassOrEnumParam)
13218       return Diag(FnDecl->getLocation(),
13219                   diag::err_operator_overload_needs_class_or_enum)
13220         << FnDecl->getDeclName();
13221   }
13222 
13223   // C++ [over.oper]p8:
13224   //   An operator function cannot have default arguments (8.3.6),
13225   //   except where explicitly stated below.
13226   //
13227   // Only the function-call operator allows default arguments
13228   // (C++ [over.call]p1).
13229   if (Op != OO_Call) {
13230     for (auto Param : FnDecl->parameters()) {
13231       if (Param->hasDefaultArg())
13232         return Diag(Param->getLocation(),
13233                     diag::err_operator_overload_default_arg)
13234           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13235     }
13236   }
13237 
13238   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13239     { false, false, false }
13240 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13241     , { Unary, Binary, MemberOnly }
13242 #include "clang/Basic/OperatorKinds.def"
13243   };
13244 
13245   bool CanBeUnaryOperator = OperatorUses[Op][0];
13246   bool CanBeBinaryOperator = OperatorUses[Op][1];
13247   bool MustBeMemberOperator = OperatorUses[Op][2];
13248 
13249   // C++ [over.oper]p8:
13250   //   [...] Operator functions cannot have more or fewer parameters
13251   //   than the number required for the corresponding operator, as
13252   //   described in the rest of this subclause.
13253   unsigned NumParams = FnDecl->getNumParams()
13254                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13255   if (Op != OO_Call &&
13256       ((NumParams == 1 && !CanBeUnaryOperator) ||
13257        (NumParams == 2 && !CanBeBinaryOperator) ||
13258        (NumParams < 1) || (NumParams > 2))) {
13259     // We have the wrong number of parameters.
13260     unsigned ErrorKind;
13261     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13262       ErrorKind = 2;  // 2 -> unary or binary.
13263     } else if (CanBeUnaryOperator) {
13264       ErrorKind = 0;  // 0 -> unary
13265     } else {
13266       assert(CanBeBinaryOperator &&
13267              "All non-call overloaded operators are unary or binary!");
13268       ErrorKind = 1;  // 1 -> binary
13269     }
13270 
13271     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13272       << FnDecl->getDeclName() << NumParams << ErrorKind;
13273   }
13274 
13275   // Overloaded operators other than operator() cannot be variadic.
13276   if (Op != OO_Call &&
13277       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13278     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13279       << FnDecl->getDeclName();
13280   }
13281 
13282   // Some operators must be non-static member functions.
13283   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13284     return Diag(FnDecl->getLocation(),
13285                 diag::err_operator_overload_must_be_member)
13286       << FnDecl->getDeclName();
13287   }
13288 
13289   // C++ [over.inc]p1:
13290   //   The user-defined function called operator++ implements the
13291   //   prefix and postfix ++ operator. If this function is a member
13292   //   function with no parameters, or a non-member function with one
13293   //   parameter of class or enumeration type, it defines the prefix
13294   //   increment operator ++ for objects of that type. If the function
13295   //   is a member function with one parameter (which shall be of type
13296   //   int) or a non-member function with two parameters (the second
13297   //   of which shall be of type int), it defines the postfix
13298   //   increment operator ++ for objects of that type.
13299   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13300     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13301     QualType ParamType = LastParam->getType();
13302 
13303     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13304         !ParamType->isDependentType())
13305       return Diag(LastParam->getLocation(),
13306                   diag::err_operator_overload_post_incdec_must_be_int)
13307         << LastParam->getType() << (Op == OO_MinusMinus);
13308   }
13309 
13310   return false;
13311 }
13312 
13313 static bool
13314 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13315                                           FunctionTemplateDecl *TpDecl) {
13316   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13317 
13318   // Must have one or two template parameters.
13319   if (TemplateParams->size() == 1) {
13320     NonTypeTemplateParmDecl *PmDecl =
13321         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13322 
13323     // The template parameter must be a char parameter pack.
13324     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13325         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13326       return false;
13327 
13328   } else if (TemplateParams->size() == 2) {
13329     TemplateTypeParmDecl *PmType =
13330         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13331     NonTypeTemplateParmDecl *PmArgs =
13332         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13333 
13334     // The second template parameter must be a parameter pack with the
13335     // first template parameter as its type.
13336     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13337         PmArgs->isTemplateParameterPack()) {
13338       const TemplateTypeParmType *TArgs =
13339           PmArgs->getType()->getAs<TemplateTypeParmType>();
13340       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13341           TArgs->getIndex() == PmType->getIndex()) {
13342         if (!SemaRef.inTemplateInstantiation())
13343           SemaRef.Diag(TpDecl->getLocation(),
13344                        diag::ext_string_literal_operator_template);
13345         return false;
13346       }
13347     }
13348   }
13349 
13350   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13351                diag::err_literal_operator_template)
13352       << TpDecl->getTemplateParameters()->getSourceRange();
13353   return true;
13354 }
13355 
13356 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13357 /// of this literal operator function is well-formed. If so, returns
13358 /// false; otherwise, emits appropriate diagnostics and returns true.
13359 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13360   if (isa<CXXMethodDecl>(FnDecl)) {
13361     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13362       << FnDecl->getDeclName();
13363     return true;
13364   }
13365 
13366   if (FnDecl->isExternC()) {
13367     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13368     if (const LinkageSpecDecl *LSD =
13369             FnDecl->getDeclContext()->getExternCContext())
13370       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13371     return true;
13372   }
13373 
13374   // This might be the definition of a literal operator template.
13375   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13376 
13377   // This might be a specialization of a literal operator template.
13378   if (!TpDecl)
13379     TpDecl = FnDecl->getPrimaryTemplate();
13380 
13381   // template <char...> type operator "" name() and
13382   // template <class T, T...> type operator "" name() are the only valid
13383   // template signatures, and the only valid signatures with no parameters.
13384   if (TpDecl) {
13385     if (FnDecl->param_size() != 0) {
13386       Diag(FnDecl->getLocation(),
13387            diag::err_literal_operator_template_with_params);
13388       return true;
13389     }
13390 
13391     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13392       return true;
13393 
13394   } else if (FnDecl->param_size() == 1) {
13395     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13396 
13397     QualType ParamType = Param->getType().getUnqualifiedType();
13398 
13399     // Only unsigned long long int, long double, any character type, and const
13400     // char * are allowed as the only parameters.
13401     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13402         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13403         Context.hasSameType(ParamType, Context.CharTy) ||
13404         Context.hasSameType(ParamType, Context.WideCharTy) ||
13405         Context.hasSameType(ParamType, Context.Char8Ty) ||
13406         Context.hasSameType(ParamType, Context.Char16Ty) ||
13407         Context.hasSameType(ParamType, Context.Char32Ty)) {
13408     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13409       QualType InnerType = Ptr->getPointeeType();
13410 
13411       // Pointer parameter must be a const char *.
13412       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13413                                 Context.CharTy) &&
13414             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13415         Diag(Param->getSourceRange().getBegin(),
13416              diag::err_literal_operator_param)
13417             << ParamType << "'const char *'" << Param->getSourceRange();
13418         return true;
13419       }
13420 
13421     } else if (ParamType->isRealFloatingType()) {
13422       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13423           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13424       return true;
13425 
13426     } else if (ParamType->isIntegerType()) {
13427       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13428           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13429       return true;
13430 
13431     } else {
13432       Diag(Param->getSourceRange().getBegin(),
13433            diag::err_literal_operator_invalid_param)
13434           << ParamType << Param->getSourceRange();
13435       return true;
13436     }
13437 
13438   } else if (FnDecl->param_size() == 2) {
13439     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13440 
13441     // First, verify that the first parameter is correct.
13442 
13443     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13444 
13445     // Two parameter function must have a pointer to const as a
13446     // first parameter; let's strip those qualifiers.
13447     const PointerType *PT = FirstParamType->getAs<PointerType>();
13448 
13449     if (!PT) {
13450       Diag((*Param)->getSourceRange().getBegin(),
13451            diag::err_literal_operator_param)
13452           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13453       return true;
13454     }
13455 
13456     QualType PointeeType = PT->getPointeeType();
13457     // First parameter must be const
13458     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13459       Diag((*Param)->getSourceRange().getBegin(),
13460            diag::err_literal_operator_param)
13461           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13462       return true;
13463     }
13464 
13465     QualType InnerType = PointeeType.getUnqualifiedType();
13466     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13467     // const char32_t* are allowed as the first parameter to a two-parameter
13468     // function
13469     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13470           Context.hasSameType(InnerType, Context.WideCharTy) ||
13471           Context.hasSameType(InnerType, Context.Char8Ty) ||
13472           Context.hasSameType(InnerType, Context.Char16Ty) ||
13473           Context.hasSameType(InnerType, Context.Char32Ty))) {
13474       Diag((*Param)->getSourceRange().getBegin(),
13475            diag::err_literal_operator_param)
13476           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13477       return true;
13478     }
13479 
13480     // Move on to the second and final parameter.
13481     ++Param;
13482 
13483     // The second parameter must be a std::size_t.
13484     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13485     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13486       Diag((*Param)->getSourceRange().getBegin(),
13487            diag::err_literal_operator_param)
13488           << SecondParamType << Context.getSizeType()
13489           << (*Param)->getSourceRange();
13490       return true;
13491     }
13492   } else {
13493     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13494     return true;
13495   }
13496 
13497   // Parameters are good.
13498 
13499   // A parameter-declaration-clause containing a default argument is not
13500   // equivalent to any of the permitted forms.
13501   for (auto Param : FnDecl->parameters()) {
13502     if (Param->hasDefaultArg()) {
13503       Diag(Param->getDefaultArgRange().getBegin(),
13504            diag::err_literal_operator_default_argument)
13505         << Param->getDefaultArgRange();
13506       break;
13507     }
13508   }
13509 
13510   StringRef LiteralName
13511     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13512   if (LiteralName[0] != '_' &&
13513       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13514     // C++11 [usrlit.suffix]p1:
13515     //   Literal suffix identifiers that do not start with an underscore
13516     //   are reserved for future standardization.
13517     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13518       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13519   }
13520 
13521   return false;
13522 }
13523 
13524 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13525 /// linkage specification, including the language and (if present)
13526 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13527 /// language string literal. LBraceLoc, if valid, provides the location of
13528 /// the '{' brace. Otherwise, this linkage specification does not
13529 /// have any braces.
13530 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13531                                            Expr *LangStr,
13532                                            SourceLocation LBraceLoc) {
13533   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13534   if (!Lit->isAscii()) {
13535     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13536       << LangStr->getSourceRange();
13537     return nullptr;
13538   }
13539 
13540   StringRef Lang = Lit->getString();
13541   LinkageSpecDecl::LanguageIDs Language;
13542   if (Lang == "C")
13543     Language = LinkageSpecDecl::lang_c;
13544   else if (Lang == "C++")
13545     Language = LinkageSpecDecl::lang_cxx;
13546   else {
13547     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13548       << LangStr->getSourceRange();
13549     return nullptr;
13550   }
13551 
13552   // FIXME: Add all the various semantics of linkage specifications
13553 
13554   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13555                                                LangStr->getExprLoc(), Language,
13556                                                LBraceLoc.isValid());
13557   CurContext->addDecl(D);
13558   PushDeclContext(S, D);
13559   return D;
13560 }
13561 
13562 /// ActOnFinishLinkageSpecification - Complete the definition of
13563 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13564 /// valid, it's the position of the closing '}' brace in a linkage
13565 /// specification that uses braces.
13566 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13567                                             Decl *LinkageSpec,
13568                                             SourceLocation RBraceLoc) {
13569   if (RBraceLoc.isValid()) {
13570     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13571     LSDecl->setRBraceLoc(RBraceLoc);
13572   }
13573   PopDeclContext();
13574   return LinkageSpec;
13575 }
13576 
13577 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13578                                   AttributeList *AttrList,
13579                                   SourceLocation SemiLoc) {
13580   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13581   // Attribute declarations appertain to empty declaration so we handle
13582   // them here.
13583   if (AttrList)
13584     ProcessDeclAttributeList(S, ED, AttrList);
13585 
13586   CurContext->addDecl(ED);
13587   return ED;
13588 }
13589 
13590 /// Perform semantic analysis for the variable declaration that
13591 /// occurs within a C++ catch clause, returning the newly-created
13592 /// variable.
13593 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13594                                          TypeSourceInfo *TInfo,
13595                                          SourceLocation StartLoc,
13596                                          SourceLocation Loc,
13597                                          IdentifierInfo *Name) {
13598   bool Invalid = false;
13599   QualType ExDeclType = TInfo->getType();
13600 
13601   // Arrays and functions decay.
13602   if (ExDeclType->isArrayType())
13603     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13604   else if (ExDeclType->isFunctionType())
13605     ExDeclType = Context.getPointerType(ExDeclType);
13606 
13607   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13608   // The exception-declaration shall not denote a pointer or reference to an
13609   // incomplete type, other than [cv] void*.
13610   // N2844 forbids rvalue references.
13611   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13612     Diag(Loc, diag::err_catch_rvalue_ref);
13613     Invalid = true;
13614   }
13615 
13616   if (ExDeclType->isVariablyModifiedType()) {
13617     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13618     Invalid = true;
13619   }
13620 
13621   QualType BaseType = ExDeclType;
13622   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13623   unsigned DK = diag::err_catch_incomplete;
13624   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13625     BaseType = Ptr->getPointeeType();
13626     Mode = 1;
13627     DK = diag::err_catch_incomplete_ptr;
13628   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13629     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13630     BaseType = Ref->getPointeeType();
13631     Mode = 2;
13632     DK = diag::err_catch_incomplete_ref;
13633   }
13634   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13635       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13636     Invalid = true;
13637 
13638   if (!Invalid && !ExDeclType->isDependentType() &&
13639       RequireNonAbstractType(Loc, ExDeclType,
13640                              diag::err_abstract_type_in_decl,
13641                              AbstractVariableType))
13642     Invalid = true;
13643 
13644   // Only the non-fragile NeXT runtime currently supports C++ catches
13645   // of ObjC types, and no runtime supports catching ObjC types by value.
13646   if (!Invalid && getLangOpts().ObjC1) {
13647     QualType T = ExDeclType;
13648     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13649       T = RT->getPointeeType();
13650 
13651     if (T->isObjCObjectType()) {
13652       Diag(Loc, diag::err_objc_object_catch);
13653       Invalid = true;
13654     } else if (T->isObjCObjectPointerType()) {
13655       // FIXME: should this be a test for macosx-fragile specifically?
13656       if (getLangOpts().ObjCRuntime.isFragile())
13657         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13658     }
13659   }
13660 
13661   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13662                                     ExDeclType, TInfo, SC_None);
13663   ExDecl->setExceptionVariable(true);
13664 
13665   // In ARC, infer 'retaining' for variables of retainable type.
13666   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13667     Invalid = true;
13668 
13669   if (!Invalid && !ExDeclType->isDependentType()) {
13670     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13671       // Insulate this from anything else we might currently be parsing.
13672       EnterExpressionEvaluationContext scope(
13673           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13674 
13675       // C++ [except.handle]p16:
13676       //   The object declared in an exception-declaration or, if the
13677       //   exception-declaration does not specify a name, a temporary (12.2) is
13678       //   copy-initialized (8.5) from the exception object. [...]
13679       //   The object is destroyed when the handler exits, after the destruction
13680       //   of any automatic objects initialized within the handler.
13681       //
13682       // We just pretend to initialize the object with itself, then make sure
13683       // it can be destroyed later.
13684       QualType initType = Context.getExceptionObjectType(ExDeclType);
13685 
13686       InitializedEntity entity =
13687         InitializedEntity::InitializeVariable(ExDecl);
13688       InitializationKind initKind =
13689         InitializationKind::CreateCopy(Loc, SourceLocation());
13690 
13691       Expr *opaqueValue =
13692         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13693       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13694       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13695       if (result.isInvalid())
13696         Invalid = true;
13697       else {
13698         // If the constructor used was non-trivial, set this as the
13699         // "initializer".
13700         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13701         if (!construct->getConstructor()->isTrivial()) {
13702           Expr *init = MaybeCreateExprWithCleanups(construct);
13703           ExDecl->setInit(init);
13704         }
13705 
13706         // And make sure it's destructable.
13707         FinalizeVarWithDestructor(ExDecl, recordType);
13708       }
13709     }
13710   }
13711 
13712   if (Invalid)
13713     ExDecl->setInvalidDecl();
13714 
13715   return ExDecl;
13716 }
13717 
13718 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13719 /// handler.
13720 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13721   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13722   bool Invalid = D.isInvalidType();
13723 
13724   // Check for unexpanded parameter packs.
13725   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13726                                       UPPC_ExceptionType)) {
13727     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13728                                              D.getIdentifierLoc());
13729     Invalid = true;
13730   }
13731 
13732   IdentifierInfo *II = D.getIdentifier();
13733   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13734                                              LookupOrdinaryName,
13735                                              ForVisibleRedeclaration)) {
13736     // The scope should be freshly made just for us. There is just no way
13737     // it contains any previous declaration, except for function parameters in
13738     // a function-try-block's catch statement.
13739     assert(!S->isDeclScope(PrevDecl));
13740     if (isDeclInScope(PrevDecl, CurContext, S)) {
13741       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13742         << D.getIdentifier();
13743       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13744       Invalid = true;
13745     } else if (PrevDecl->isTemplateParameter())
13746       // Maybe we will complain about the shadowed template parameter.
13747       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13748   }
13749 
13750   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13751     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13752       << D.getCXXScopeSpec().getRange();
13753     Invalid = true;
13754   }
13755 
13756   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13757                                               D.getLocStart(),
13758                                               D.getIdentifierLoc(),
13759                                               D.getIdentifier());
13760   if (Invalid)
13761     ExDecl->setInvalidDecl();
13762 
13763   // Add the exception declaration into this scope.
13764   if (II)
13765     PushOnScopeChains(ExDecl, S);
13766   else
13767     CurContext->addDecl(ExDecl);
13768 
13769   ProcessDeclAttributes(S, ExDecl, D);
13770   return ExDecl;
13771 }
13772 
13773 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13774                                          Expr *AssertExpr,
13775                                          Expr *AssertMessageExpr,
13776                                          SourceLocation RParenLoc) {
13777   StringLiteral *AssertMessage =
13778       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13779 
13780   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13781     return nullptr;
13782 
13783   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13784                                       AssertMessage, RParenLoc, false);
13785 }
13786 
13787 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13788                                          Expr *AssertExpr,
13789                                          StringLiteral *AssertMessage,
13790                                          SourceLocation RParenLoc,
13791                                          bool Failed) {
13792   assert(AssertExpr != nullptr && "Expected non-null condition");
13793   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13794       !Failed) {
13795     // In a static_assert-declaration, the constant-expression shall be a
13796     // constant expression that can be contextually converted to bool.
13797     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13798     if (Converted.isInvalid())
13799       Failed = true;
13800 
13801     llvm::APSInt Cond;
13802     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13803           diag::err_static_assert_expression_is_not_constant,
13804           /*AllowFold=*/false).isInvalid())
13805       Failed = true;
13806 
13807     if (!Failed && !Cond) {
13808       SmallString<256> MsgBuffer;
13809       llvm::raw_svector_ostream Msg(MsgBuffer);
13810       if (AssertMessage)
13811         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13812 
13813       Expr *InnerCond = nullptr;
13814       std::string InnerCondDescription;
13815       std::tie(InnerCond, InnerCondDescription) =
13816         findFailedBooleanCondition(Converted.get(),
13817                                    /*AllowTopLevelCond=*/false);
13818       if (InnerCond) {
13819         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13820           << InnerCondDescription << !AssertMessage
13821           << Msg.str() << InnerCond->getSourceRange();
13822       } else {
13823         Diag(StaticAssertLoc, diag::err_static_assert_failed)
13824           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13825       }
13826       Failed = true;
13827     }
13828   }
13829 
13830   ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13831                                                   /*DiscardedValue*/false,
13832                                                   /*IsConstexpr*/true);
13833   if (FullAssertExpr.isInvalid())
13834     Failed = true;
13835   else
13836     AssertExpr = FullAssertExpr.get();
13837 
13838   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13839                                         AssertExpr, AssertMessage, RParenLoc,
13840                                         Failed);
13841 
13842   CurContext->addDecl(Decl);
13843   return Decl;
13844 }
13845 
13846 /// Perform semantic analysis of the given friend type declaration.
13847 ///
13848 /// \returns A friend declaration that.
13849 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13850                                       SourceLocation FriendLoc,
13851                                       TypeSourceInfo *TSInfo) {
13852   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13853 
13854   QualType T = TSInfo->getType();
13855   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13856 
13857   // C++03 [class.friend]p2:
13858   //   An elaborated-type-specifier shall be used in a friend declaration
13859   //   for a class.*
13860   //
13861   //   * The class-key of the elaborated-type-specifier is required.
13862   if (!CodeSynthesisContexts.empty()) {
13863     // Do not complain about the form of friend template types during any kind
13864     // of code synthesis. For template instantiation, we will have complained
13865     // when the template was defined.
13866   } else {
13867     if (!T->isElaboratedTypeSpecifier()) {
13868       // If we evaluated the type to a record type, suggest putting
13869       // a tag in front.
13870       if (const RecordType *RT = T->getAs<RecordType>()) {
13871         RecordDecl *RD = RT->getDecl();
13872 
13873         SmallString<16> InsertionText(" ");
13874         InsertionText += RD->getKindName();
13875 
13876         Diag(TypeRange.getBegin(),
13877              getLangOpts().CPlusPlus11 ?
13878                diag::warn_cxx98_compat_unelaborated_friend_type :
13879                diag::ext_unelaborated_friend_type)
13880           << (unsigned) RD->getTagKind()
13881           << T
13882           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13883                                         InsertionText);
13884       } else {
13885         Diag(FriendLoc,
13886              getLangOpts().CPlusPlus11 ?
13887                diag::warn_cxx98_compat_nonclass_type_friend :
13888                diag::ext_nonclass_type_friend)
13889           << T
13890           << TypeRange;
13891       }
13892     } else if (T->getAs<EnumType>()) {
13893       Diag(FriendLoc,
13894            getLangOpts().CPlusPlus11 ?
13895              diag::warn_cxx98_compat_enum_friend :
13896              diag::ext_enum_friend)
13897         << T
13898         << TypeRange;
13899     }
13900 
13901     // C++11 [class.friend]p3:
13902     //   A friend declaration that does not declare a function shall have one
13903     //   of the following forms:
13904     //     friend elaborated-type-specifier ;
13905     //     friend simple-type-specifier ;
13906     //     friend typename-specifier ;
13907     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13908       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13909   }
13910 
13911   //   If the type specifier in a friend declaration designates a (possibly
13912   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13913   //   the friend declaration is ignored.
13914   return FriendDecl::Create(Context, CurContext,
13915                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13916                             FriendLoc);
13917 }
13918 
13919 /// Handle a friend tag declaration where the scope specifier was
13920 /// templated.
13921 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13922                                     unsigned TagSpec, SourceLocation TagLoc,
13923                                     CXXScopeSpec &SS,
13924                                     IdentifierInfo *Name,
13925                                     SourceLocation NameLoc,
13926                                     AttributeList *Attr,
13927                                     MultiTemplateParamsArg TempParamLists) {
13928   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13929 
13930   bool IsMemberSpecialization = false;
13931   bool Invalid = false;
13932 
13933   if (TemplateParameterList *TemplateParams =
13934           MatchTemplateParametersToScopeSpecifier(
13935               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13936               IsMemberSpecialization, Invalid)) {
13937     if (TemplateParams->size() > 0) {
13938       // This is a declaration of a class template.
13939       if (Invalid)
13940         return nullptr;
13941 
13942       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13943                                 NameLoc, Attr, TemplateParams, AS_public,
13944                                 /*ModulePrivateLoc=*/SourceLocation(),
13945                                 FriendLoc, TempParamLists.size() - 1,
13946                                 TempParamLists.data()).get();
13947     } else {
13948       // The "template<>" header is extraneous.
13949       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13950         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13951       IsMemberSpecialization = true;
13952     }
13953   }
13954 
13955   if (Invalid) return nullptr;
13956 
13957   bool isAllExplicitSpecializations = true;
13958   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13959     if (TempParamLists[I]->size()) {
13960       isAllExplicitSpecializations = false;
13961       break;
13962     }
13963   }
13964 
13965   // FIXME: don't ignore attributes.
13966 
13967   // If it's explicit specializations all the way down, just forget
13968   // about the template header and build an appropriate non-templated
13969   // friend.  TODO: for source fidelity, remember the headers.
13970   if (isAllExplicitSpecializations) {
13971     if (SS.isEmpty()) {
13972       bool Owned = false;
13973       bool IsDependent = false;
13974       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13975                       Attr, AS_public,
13976                       /*ModulePrivateLoc=*/SourceLocation(),
13977                       MultiTemplateParamsArg(), Owned, IsDependent,
13978                       /*ScopedEnumKWLoc=*/SourceLocation(),
13979                       /*ScopedEnumUsesClassTag=*/false,
13980                       /*UnderlyingType=*/TypeResult(),
13981                       /*IsTypeSpecifier=*/false,
13982                       /*IsTemplateParamOrArg=*/false);
13983     }
13984 
13985     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13986     ElaboratedTypeKeyword Keyword
13987       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13988     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13989                                    *Name, NameLoc);
13990     if (T.isNull())
13991       return nullptr;
13992 
13993     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13994     if (isa<DependentNameType>(T)) {
13995       DependentNameTypeLoc TL =
13996           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13997       TL.setElaboratedKeywordLoc(TagLoc);
13998       TL.setQualifierLoc(QualifierLoc);
13999       TL.setNameLoc(NameLoc);
14000     } else {
14001       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14002       TL.setElaboratedKeywordLoc(TagLoc);
14003       TL.setQualifierLoc(QualifierLoc);
14004       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14005     }
14006 
14007     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14008                                             TSI, FriendLoc, TempParamLists);
14009     Friend->setAccess(AS_public);
14010     CurContext->addDecl(Friend);
14011     return Friend;
14012   }
14013 
14014   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14015 
14016 
14017 
14018   // Handle the case of a templated-scope friend class.  e.g.
14019   //   template <class T> class A<T>::B;
14020   // FIXME: we don't support these right now.
14021   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14022     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14023   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14024   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14025   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14026   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14027   TL.setElaboratedKeywordLoc(TagLoc);
14028   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14029   TL.setNameLoc(NameLoc);
14030 
14031   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14032                                           TSI, FriendLoc, TempParamLists);
14033   Friend->setAccess(AS_public);
14034   Friend->setUnsupportedFriend(true);
14035   CurContext->addDecl(Friend);
14036   return Friend;
14037 }
14038 
14039 
14040 /// Handle a friend type declaration.  This works in tandem with
14041 /// ActOnTag.
14042 ///
14043 /// Notes on friend class templates:
14044 ///
14045 /// We generally treat friend class declarations as if they were
14046 /// declaring a class.  So, for example, the elaborated type specifier
14047 /// in a friend declaration is required to obey the restrictions of a
14048 /// class-head (i.e. no typedefs in the scope chain), template
14049 /// parameters are required to match up with simple template-ids, &c.
14050 /// However, unlike when declaring a template specialization, it's
14051 /// okay to refer to a template specialization without an empty
14052 /// template parameter declaration, e.g.
14053 ///   friend class A<T>::B<unsigned>;
14054 /// We permit this as a special case; if there are any template
14055 /// parameters present at all, require proper matching, i.e.
14056 ///   template <> template \<class T> friend class A<int>::B;
14057 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14058                                 MultiTemplateParamsArg TempParams) {
14059   SourceLocation Loc = DS.getLocStart();
14060 
14061   assert(DS.isFriendSpecified());
14062   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14063 
14064   // Try to convert the decl specifier to a type.  This works for
14065   // friend templates because ActOnTag never produces a ClassTemplateDecl
14066   // for a TUK_Friend.
14067   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14068   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14069   QualType T = TSI->getType();
14070   if (TheDeclarator.isInvalidType())
14071     return nullptr;
14072 
14073   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14074     return nullptr;
14075 
14076   // This is definitely an error in C++98.  It's probably meant to
14077   // be forbidden in C++0x, too, but the specification is just
14078   // poorly written.
14079   //
14080   // The problem is with declarations like the following:
14081   //   template <T> friend A<T>::foo;
14082   // where deciding whether a class C is a friend or not now hinges
14083   // on whether there exists an instantiation of A that causes
14084   // 'foo' to equal C.  There are restrictions on class-heads
14085   // (which we declare (by fiat) elaborated friend declarations to
14086   // be) that makes this tractable.
14087   //
14088   // FIXME: handle "template <> friend class A<T>;", which
14089   // is possibly well-formed?  Who even knows?
14090   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14091     Diag(Loc, diag::err_tagless_friend_type_template)
14092       << DS.getSourceRange();
14093     return nullptr;
14094   }
14095 
14096   // C++98 [class.friend]p1: A friend of a class is a function
14097   //   or class that is not a member of the class . . .
14098   // This is fixed in DR77, which just barely didn't make the C++03
14099   // deadline.  It's also a very silly restriction that seriously
14100   // affects inner classes and which nobody else seems to implement;
14101   // thus we never diagnose it, not even in -pedantic.
14102   //
14103   // But note that we could warn about it: it's always useless to
14104   // friend one of your own members (it's not, however, worthless to
14105   // friend a member of an arbitrary specialization of your template).
14106 
14107   Decl *D;
14108   if (!TempParams.empty())
14109     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14110                                    TempParams,
14111                                    TSI,
14112                                    DS.getFriendSpecLoc());
14113   else
14114     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14115 
14116   if (!D)
14117     return nullptr;
14118 
14119   D->setAccess(AS_public);
14120   CurContext->addDecl(D);
14121 
14122   return D;
14123 }
14124 
14125 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14126                                         MultiTemplateParamsArg TemplateParams) {
14127   const DeclSpec &DS = D.getDeclSpec();
14128 
14129   assert(DS.isFriendSpecified());
14130   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14131 
14132   SourceLocation Loc = D.getIdentifierLoc();
14133   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14134 
14135   // C++ [class.friend]p1
14136   //   A friend of a class is a function or class....
14137   // Note that this sees through typedefs, which is intended.
14138   // It *doesn't* see through dependent types, which is correct
14139   // according to [temp.arg.type]p3:
14140   //   If a declaration acquires a function type through a
14141   //   type dependent on a template-parameter and this causes
14142   //   a declaration that does not use the syntactic form of a
14143   //   function declarator to have a function type, the program
14144   //   is ill-formed.
14145   if (!TInfo->getType()->isFunctionType()) {
14146     Diag(Loc, diag::err_unexpected_friend);
14147 
14148     // It might be worthwhile to try to recover by creating an
14149     // appropriate declaration.
14150     return nullptr;
14151   }
14152 
14153   // C++ [namespace.memdef]p3
14154   //  - If a friend declaration in a non-local class first declares a
14155   //    class or function, the friend class or function is a member
14156   //    of the innermost enclosing namespace.
14157   //  - The name of the friend is not found by simple name lookup
14158   //    until a matching declaration is provided in that namespace
14159   //    scope (either before or after the class declaration granting
14160   //    friendship).
14161   //  - If a friend function is called, its name may be found by the
14162   //    name lookup that considers functions from namespaces and
14163   //    classes associated with the types of the function arguments.
14164   //  - When looking for a prior declaration of a class or a function
14165   //    declared as a friend, scopes outside the innermost enclosing
14166   //    namespace scope are not considered.
14167 
14168   CXXScopeSpec &SS = D.getCXXScopeSpec();
14169   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14170   DeclarationName Name = NameInfo.getName();
14171   assert(Name);
14172 
14173   // Check for unexpanded parameter packs.
14174   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14175       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14176       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14177     return nullptr;
14178 
14179   // The context we found the declaration in, or in which we should
14180   // create the declaration.
14181   DeclContext *DC;
14182   Scope *DCScope = S;
14183   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14184                         ForExternalRedeclaration);
14185 
14186   // There are five cases here.
14187   //   - There's no scope specifier and we're in a local class. Only look
14188   //     for functions declared in the immediately-enclosing block scope.
14189   // We recover from invalid scope qualifiers as if they just weren't there.
14190   FunctionDecl *FunctionContainingLocalClass = nullptr;
14191   if ((SS.isInvalid() || !SS.isSet()) &&
14192       (FunctionContainingLocalClass =
14193            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14194     // C++11 [class.friend]p11:
14195     //   If a friend declaration appears in a local class and the name
14196     //   specified is an unqualified name, a prior declaration is
14197     //   looked up without considering scopes that are outside the
14198     //   innermost enclosing non-class scope. For a friend function
14199     //   declaration, if there is no prior declaration, the program is
14200     //   ill-formed.
14201 
14202     // Find the innermost enclosing non-class scope. This is the block
14203     // scope containing the local class definition (or for a nested class,
14204     // the outer local class).
14205     DCScope = S->getFnParent();
14206 
14207     // Look up the function name in the scope.
14208     Previous.clear(LookupLocalFriendName);
14209     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14210 
14211     if (!Previous.empty()) {
14212       // All possible previous declarations must have the same context:
14213       // either they were declared at block scope or they are members of
14214       // one of the enclosing local classes.
14215       DC = Previous.getRepresentativeDecl()->getDeclContext();
14216     } else {
14217       // This is ill-formed, but provide the context that we would have
14218       // declared the function in, if we were permitted to, for error recovery.
14219       DC = FunctionContainingLocalClass;
14220     }
14221     adjustContextForLocalExternDecl(DC);
14222 
14223     // C++ [class.friend]p6:
14224     //   A function can be defined in a friend declaration of a class if and
14225     //   only if the class is a non-local class (9.8), the function name is
14226     //   unqualified, and the function has namespace scope.
14227     if (D.isFunctionDefinition()) {
14228       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14229     }
14230 
14231   //   - There's no scope specifier, in which case we just go to the
14232   //     appropriate scope and look for a function or function template
14233   //     there as appropriate.
14234   } else if (SS.isInvalid() || !SS.isSet()) {
14235     // C++11 [namespace.memdef]p3:
14236     //   If the name in a friend declaration is neither qualified nor
14237     //   a template-id and the declaration is a function or an
14238     //   elaborated-type-specifier, the lookup to determine whether
14239     //   the entity has been previously declared shall not consider
14240     //   any scopes outside the innermost enclosing namespace.
14241     bool isTemplateId =
14242         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14243 
14244     // Find the appropriate context according to the above.
14245     DC = CurContext;
14246 
14247     // Skip class contexts.  If someone can cite chapter and verse
14248     // for this behavior, that would be nice --- it's what GCC and
14249     // EDG do, and it seems like a reasonable intent, but the spec
14250     // really only says that checks for unqualified existing
14251     // declarations should stop at the nearest enclosing namespace,
14252     // not that they should only consider the nearest enclosing
14253     // namespace.
14254     while (DC->isRecord())
14255       DC = DC->getParent();
14256 
14257     DeclContext *LookupDC = DC;
14258     while (LookupDC->isTransparentContext())
14259       LookupDC = LookupDC->getParent();
14260 
14261     while (true) {
14262       LookupQualifiedName(Previous, LookupDC);
14263 
14264       if (!Previous.empty()) {
14265         DC = LookupDC;
14266         break;
14267       }
14268 
14269       if (isTemplateId) {
14270         if (isa<TranslationUnitDecl>(LookupDC)) break;
14271       } else {
14272         if (LookupDC->isFileContext()) break;
14273       }
14274       LookupDC = LookupDC->getParent();
14275     }
14276 
14277     DCScope = getScopeForDeclContext(S, DC);
14278 
14279   //   - There's a non-dependent scope specifier, in which case we
14280   //     compute it and do a previous lookup there for a function
14281   //     or function template.
14282   } else if (!SS.getScopeRep()->isDependent()) {
14283     DC = computeDeclContext(SS);
14284     if (!DC) return nullptr;
14285 
14286     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14287 
14288     LookupQualifiedName(Previous, DC);
14289 
14290     // Ignore things found implicitly in the wrong scope.
14291     // TODO: better diagnostics for this case.  Suggesting the right
14292     // qualified scope would be nice...
14293     LookupResult::Filter F = Previous.makeFilter();
14294     while (F.hasNext()) {
14295       NamedDecl *D = F.next();
14296       if (!DC->InEnclosingNamespaceSetOf(
14297               D->getDeclContext()->getRedeclContext()))
14298         F.erase();
14299     }
14300     F.done();
14301 
14302     if (Previous.empty()) {
14303       D.setInvalidType();
14304       Diag(Loc, diag::err_qualified_friend_not_found)
14305           << Name << TInfo->getType();
14306       return nullptr;
14307     }
14308 
14309     // C++ [class.friend]p1: A friend of a class is a function or
14310     //   class that is not a member of the class . . .
14311     if (DC->Equals(CurContext))
14312       Diag(DS.getFriendSpecLoc(),
14313            getLangOpts().CPlusPlus11 ?
14314              diag::warn_cxx98_compat_friend_is_member :
14315              diag::err_friend_is_member);
14316 
14317     if (D.isFunctionDefinition()) {
14318       // C++ [class.friend]p6:
14319       //   A function can be defined in a friend declaration of a class if and
14320       //   only if the class is a non-local class (9.8), the function name is
14321       //   unqualified, and the function has namespace scope.
14322       SemaDiagnosticBuilder DB
14323         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14324 
14325       DB << SS.getScopeRep();
14326       if (DC->isFileContext())
14327         DB << FixItHint::CreateRemoval(SS.getRange());
14328       SS.clear();
14329     }
14330 
14331   //   - There's a scope specifier that does not match any template
14332   //     parameter lists, in which case we use some arbitrary context,
14333   //     create a method or method template, and wait for instantiation.
14334   //   - There's a scope specifier that does match some template
14335   //     parameter lists, which we don't handle right now.
14336   } else {
14337     if (D.isFunctionDefinition()) {
14338       // C++ [class.friend]p6:
14339       //   A function can be defined in a friend declaration of a class if and
14340       //   only if the class is a non-local class (9.8), the function name is
14341       //   unqualified, and the function has namespace scope.
14342       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14343         << SS.getScopeRep();
14344     }
14345 
14346     DC = CurContext;
14347     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14348   }
14349 
14350   if (!DC->isRecord()) {
14351     int DiagArg = -1;
14352     switch (D.getName().getKind()) {
14353     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14354     case UnqualifiedIdKind::IK_ConstructorName:
14355       DiagArg = 0;
14356       break;
14357     case UnqualifiedIdKind::IK_DestructorName:
14358       DiagArg = 1;
14359       break;
14360     case UnqualifiedIdKind::IK_ConversionFunctionId:
14361       DiagArg = 2;
14362       break;
14363     case UnqualifiedIdKind::IK_DeductionGuideName:
14364       DiagArg = 3;
14365       break;
14366     case UnqualifiedIdKind::IK_Identifier:
14367     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14368     case UnqualifiedIdKind::IK_LiteralOperatorId:
14369     case UnqualifiedIdKind::IK_OperatorFunctionId:
14370     case UnqualifiedIdKind::IK_TemplateId:
14371       break;
14372     }
14373     // This implies that it has to be an operator or function.
14374     if (DiagArg >= 0) {
14375       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14376       return nullptr;
14377     }
14378   }
14379 
14380   // FIXME: This is an egregious hack to cope with cases where the scope stack
14381   // does not contain the declaration context, i.e., in an out-of-line
14382   // definition of a class.
14383   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14384   if (!DCScope) {
14385     FakeDCScope.setEntity(DC);
14386     DCScope = &FakeDCScope;
14387   }
14388 
14389   bool AddToScope = true;
14390   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14391                                           TemplateParams, AddToScope);
14392   if (!ND) return nullptr;
14393 
14394   assert(ND->getLexicalDeclContext() == CurContext);
14395 
14396   // If we performed typo correction, we might have added a scope specifier
14397   // and changed the decl context.
14398   DC = ND->getDeclContext();
14399 
14400   // Add the function declaration to the appropriate lookup tables,
14401   // adjusting the redeclarations list as necessary.  We don't
14402   // want to do this yet if the friending class is dependent.
14403   //
14404   // Also update the scope-based lookup if the target context's
14405   // lookup context is in lexical scope.
14406   if (!CurContext->isDependentContext()) {
14407     DC = DC->getRedeclContext();
14408     DC->makeDeclVisibleInContext(ND);
14409     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14410       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14411   }
14412 
14413   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14414                                        D.getIdentifierLoc(), ND,
14415                                        DS.getFriendSpecLoc());
14416   FrD->setAccess(AS_public);
14417   CurContext->addDecl(FrD);
14418 
14419   if (ND->isInvalidDecl()) {
14420     FrD->setInvalidDecl();
14421   } else {
14422     if (DC->isRecord()) CheckFriendAccess(ND);
14423 
14424     FunctionDecl *FD;
14425     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14426       FD = FTD->getTemplatedDecl();
14427     else
14428       FD = cast<FunctionDecl>(ND);
14429 
14430     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14431     // default argument expression, that declaration shall be a definition
14432     // and shall be the only declaration of the function or function
14433     // template in the translation unit.
14434     if (functionDeclHasDefaultArgument(FD)) {
14435       // We can't look at FD->getPreviousDecl() because it may not have been set
14436       // if we're in a dependent context. If the function is known to be a
14437       // redeclaration, we will have narrowed Previous down to the right decl.
14438       if (D.isRedeclaration()) {
14439         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14440         Diag(Previous.getRepresentativeDecl()->getLocation(),
14441              diag::note_previous_declaration);
14442       } else if (!D.isFunctionDefinition())
14443         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14444     }
14445 
14446     // Mark templated-scope function declarations as unsupported.
14447     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14448       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14449         << SS.getScopeRep() << SS.getRange()
14450         << cast<CXXRecordDecl>(CurContext);
14451       FrD->setUnsupportedFriend(true);
14452     }
14453   }
14454 
14455   return ND;
14456 }
14457 
14458 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14459   AdjustDeclIfTemplate(Dcl);
14460 
14461   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14462   if (!Fn) {
14463     Diag(DelLoc, diag::err_deleted_non_function);
14464     return;
14465   }
14466 
14467   // Deleted function does not have a body.
14468   Fn->setWillHaveBody(false);
14469 
14470   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14471     // Don't consider the implicit declaration we generate for explicit
14472     // specializations. FIXME: Do not generate these implicit declarations.
14473     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14474          Prev->getPreviousDecl()) &&
14475         !Prev->isDefined()) {
14476       Diag(DelLoc, diag::err_deleted_decl_not_first);
14477       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14478            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14479                               : diag::note_previous_declaration);
14480     }
14481     // If the declaration wasn't the first, we delete the function anyway for
14482     // recovery.
14483     Fn = Fn->getCanonicalDecl();
14484   }
14485 
14486   // dllimport/dllexport cannot be deleted.
14487   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14488     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14489     Fn->setInvalidDecl();
14490   }
14491 
14492   if (Fn->isDeleted())
14493     return;
14494 
14495   // See if we're deleting a function which is already known to override a
14496   // non-deleted virtual function.
14497   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14498     bool IssuedDiagnostic = false;
14499     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14500       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14501         if (!IssuedDiagnostic) {
14502           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14503           IssuedDiagnostic = true;
14504         }
14505         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14506       }
14507     }
14508     // If this function was implicitly deleted because it was defaulted,
14509     // explain why it was deleted.
14510     if (IssuedDiagnostic && MD->isDefaulted())
14511       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14512                                 /*Diagnose*/true);
14513   }
14514 
14515   // C++11 [basic.start.main]p3:
14516   //   A program that defines main as deleted [...] is ill-formed.
14517   if (Fn->isMain())
14518     Diag(DelLoc, diag::err_deleted_main);
14519 
14520   // C++11 [dcl.fct.def.delete]p4:
14521   //  A deleted function is implicitly inline.
14522   Fn->setImplicitlyInline();
14523   Fn->setDeletedAsWritten();
14524 }
14525 
14526 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14527   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14528 
14529   if (MD) {
14530     if (MD->getParent()->isDependentType()) {
14531       MD->setDefaulted();
14532       MD->setExplicitlyDefaulted();
14533       return;
14534     }
14535 
14536     CXXSpecialMember Member = getSpecialMember(MD);
14537     if (Member == CXXInvalid) {
14538       if (!MD->isInvalidDecl())
14539         Diag(DefaultLoc, diag::err_default_special_members);
14540       return;
14541     }
14542 
14543     MD->setDefaulted();
14544     MD->setExplicitlyDefaulted();
14545 
14546     // Unset that we will have a body for this function. We might not,
14547     // if it turns out to be trivial, and we don't need this marking now
14548     // that we've marked it as defaulted.
14549     MD->setWillHaveBody(false);
14550 
14551     // If this definition appears within the record, do the checking when
14552     // the record is complete.
14553     const FunctionDecl *Primary = MD;
14554     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14555       // Ask the template instantiation pattern that actually had the
14556       // '= default' on it.
14557       Primary = Pattern;
14558 
14559     // If the method was defaulted on its first declaration, we will have
14560     // already performed the checking in CheckCompletedCXXClass. Such a
14561     // declaration doesn't trigger an implicit definition.
14562     if (Primary->getCanonicalDecl()->isDefaulted())
14563       return;
14564 
14565     CheckExplicitlyDefaultedSpecialMember(MD);
14566 
14567     if (!MD->isInvalidDecl())
14568       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14569   } else {
14570     Diag(DefaultLoc, diag::err_default_special_members);
14571   }
14572 }
14573 
14574 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14575   for (Stmt *SubStmt : S->children()) {
14576     if (!SubStmt)
14577       continue;
14578     if (isa<ReturnStmt>(SubStmt))
14579       Self.Diag(SubStmt->getLocStart(),
14580            diag::err_return_in_constructor_handler);
14581     if (!isa<Expr>(SubStmt))
14582       SearchForReturnInStmt(Self, SubStmt);
14583   }
14584 }
14585 
14586 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14587   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14588     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14589     SearchForReturnInStmt(*this, Handler);
14590   }
14591 }
14592 
14593 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14594                                              const CXXMethodDecl *Old) {
14595   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14596   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14597 
14598   if (OldFT->hasExtParameterInfos()) {
14599     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14600       // A parameter of the overriding method should be annotated with noescape
14601       // if the corresponding parameter of the overridden method is annotated.
14602       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14603           !NewFT->getExtParameterInfo(I).isNoEscape()) {
14604         Diag(New->getParamDecl(I)->getLocation(),
14605              diag::warn_overriding_method_missing_noescape);
14606         Diag(Old->getParamDecl(I)->getLocation(),
14607              diag::note_overridden_marked_noescape);
14608       }
14609   }
14610 
14611   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14612 
14613   // If the calling conventions match, everything is fine
14614   if (NewCC == OldCC)
14615     return false;
14616 
14617   // If the calling conventions mismatch because the new function is static,
14618   // suppress the calling convention mismatch error; the error about static
14619   // function override (err_static_overrides_virtual from
14620   // Sema::CheckFunctionDeclaration) is more clear.
14621   if (New->getStorageClass() == SC_Static)
14622     return false;
14623 
14624   Diag(New->getLocation(),
14625        diag::err_conflicting_overriding_cc_attributes)
14626     << New->getDeclName() << New->getType() << Old->getType();
14627   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14628   return true;
14629 }
14630 
14631 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14632                                              const CXXMethodDecl *Old) {
14633   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14634   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14635 
14636   if (Context.hasSameType(NewTy, OldTy) ||
14637       NewTy->isDependentType() || OldTy->isDependentType())
14638     return false;
14639 
14640   // Check if the return types are covariant
14641   QualType NewClassTy, OldClassTy;
14642 
14643   /// Both types must be pointers or references to classes.
14644   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14645     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14646       NewClassTy = NewPT->getPointeeType();
14647       OldClassTy = OldPT->getPointeeType();
14648     }
14649   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14650     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14651       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14652         NewClassTy = NewRT->getPointeeType();
14653         OldClassTy = OldRT->getPointeeType();
14654       }
14655     }
14656   }
14657 
14658   // The return types aren't either both pointers or references to a class type.
14659   if (NewClassTy.isNull()) {
14660     Diag(New->getLocation(),
14661          diag::err_different_return_type_for_overriding_virtual_function)
14662         << New->getDeclName() << NewTy << OldTy
14663         << New->getReturnTypeSourceRange();
14664     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14665         << Old->getReturnTypeSourceRange();
14666 
14667     return true;
14668   }
14669 
14670   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14671     // C++14 [class.virtual]p8:
14672     //   If the class type in the covariant return type of D::f differs from
14673     //   that of B::f, the class type in the return type of D::f shall be
14674     //   complete at the point of declaration of D::f or shall be the class
14675     //   type D.
14676     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14677       if (!RT->isBeingDefined() &&
14678           RequireCompleteType(New->getLocation(), NewClassTy,
14679                               diag::err_covariant_return_incomplete,
14680                               New->getDeclName()))
14681         return true;
14682     }
14683 
14684     // Check if the new class derives from the old class.
14685     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14686       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14687           << New->getDeclName() << NewTy << OldTy
14688           << New->getReturnTypeSourceRange();
14689       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14690           << Old->getReturnTypeSourceRange();
14691       return true;
14692     }
14693 
14694     // Check if we the conversion from derived to base is valid.
14695     if (CheckDerivedToBaseConversion(
14696             NewClassTy, OldClassTy,
14697             diag::err_covariant_return_inaccessible_base,
14698             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14699             New->getLocation(), New->getReturnTypeSourceRange(),
14700             New->getDeclName(), nullptr)) {
14701       // FIXME: this note won't trigger for delayed access control
14702       // diagnostics, and it's impossible to get an undelayed error
14703       // here from access control during the original parse because
14704       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14705       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14706           << Old->getReturnTypeSourceRange();
14707       return true;
14708     }
14709   }
14710 
14711   // The qualifiers of the return types must be the same.
14712   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14713     Diag(New->getLocation(),
14714          diag::err_covariant_return_type_different_qualifications)
14715         << New->getDeclName() << NewTy << OldTy
14716         << New->getReturnTypeSourceRange();
14717     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14718         << Old->getReturnTypeSourceRange();
14719     return true;
14720   }
14721 
14722 
14723   // The new class type must have the same or less qualifiers as the old type.
14724   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14725     Diag(New->getLocation(),
14726          diag::err_covariant_return_type_class_type_more_qualified)
14727         << New->getDeclName() << NewTy << OldTy
14728         << New->getReturnTypeSourceRange();
14729     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14730         << Old->getReturnTypeSourceRange();
14731     return true;
14732   }
14733 
14734   return false;
14735 }
14736 
14737 /// Mark the given method pure.
14738 ///
14739 /// \param Method the method to be marked pure.
14740 ///
14741 /// \param InitRange the source range that covers the "0" initializer.
14742 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14743   SourceLocation EndLoc = InitRange.getEnd();
14744   if (EndLoc.isValid())
14745     Method->setRangeEnd(EndLoc);
14746 
14747   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14748     Method->setPure();
14749     return false;
14750   }
14751 
14752   if (!Method->isInvalidDecl())
14753     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14754       << Method->getDeclName() << InitRange;
14755   return true;
14756 }
14757 
14758 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14759   if (D->getFriendObjectKind())
14760     Diag(D->getLocation(), diag::err_pure_friend);
14761   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14762     CheckPureMethod(M, ZeroLoc);
14763   else
14764     Diag(D->getLocation(), diag::err_illegal_initializer);
14765 }
14766 
14767 /// Determine whether the given declaration is a global variable or
14768 /// static data member.
14769 static bool isNonlocalVariable(const Decl *D) {
14770   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14771     return Var->hasGlobalStorage();
14772 
14773   return false;
14774 }
14775 
14776 /// Invoked when we are about to parse an initializer for the declaration
14777 /// 'Dcl'.
14778 ///
14779 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14780 /// static data member of class X, names should be looked up in the scope of
14781 /// class X. If the declaration had a scope specifier, a scope will have
14782 /// been created and passed in for this purpose. Otherwise, S will be null.
14783 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14784   // If there is no declaration, there was an error parsing it.
14785   if (!D || D->isInvalidDecl())
14786     return;
14787 
14788   // We will always have a nested name specifier here, but this declaration
14789   // might not be out of line if the specifier names the current namespace:
14790   //   extern int n;
14791   //   int ::n = 0;
14792   if (S && D->isOutOfLine())
14793     EnterDeclaratorContext(S, D->getDeclContext());
14794 
14795   // If we are parsing the initializer for a static data member, push a
14796   // new expression evaluation context that is associated with this static
14797   // data member.
14798   if (isNonlocalVariable(D))
14799     PushExpressionEvaluationContext(
14800         ExpressionEvaluationContext::PotentiallyEvaluated, D);
14801 }
14802 
14803 /// Invoked after we are finished parsing an initializer for the declaration D.
14804 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14805   // If there is no declaration, there was an error parsing it.
14806   if (!D || D->isInvalidDecl())
14807     return;
14808 
14809   if (isNonlocalVariable(D))
14810     PopExpressionEvaluationContext();
14811 
14812   if (S && D->isOutOfLine())
14813     ExitDeclaratorContext(S);
14814 }
14815 
14816 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14817 /// C++ if/switch/while/for statement.
14818 /// e.g: "if (int x = f()) {...}"
14819 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14820   // C++ 6.4p2:
14821   // The declarator shall not specify a function or an array.
14822   // The type-specifier-seq shall not contain typedef and shall not declare a
14823   // new class or enumeration.
14824   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14825          "Parser allowed 'typedef' as storage class of condition decl.");
14826 
14827   Decl *Dcl = ActOnDeclarator(S, D);
14828   if (!Dcl)
14829     return true;
14830 
14831   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14832     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14833       << D.getSourceRange();
14834     return true;
14835   }
14836 
14837   return Dcl;
14838 }
14839 
14840 void Sema::LoadExternalVTableUses() {
14841   if (!ExternalSource)
14842     return;
14843 
14844   SmallVector<ExternalVTableUse, 4> VTables;
14845   ExternalSource->ReadUsedVTables(VTables);
14846   SmallVector<VTableUse, 4> NewUses;
14847   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14848     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14849       = VTablesUsed.find(VTables[I].Record);
14850     // Even if a definition wasn't required before, it may be required now.
14851     if (Pos != VTablesUsed.end()) {
14852       if (!Pos->second && VTables[I].DefinitionRequired)
14853         Pos->second = true;
14854       continue;
14855     }
14856 
14857     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14858     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14859   }
14860 
14861   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14862 }
14863 
14864 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14865                           bool DefinitionRequired) {
14866   // Ignore any vtable uses in unevaluated operands or for classes that do
14867   // not have a vtable.
14868   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14869       CurContext->isDependentContext() || isUnevaluatedContext())
14870     return;
14871 
14872   // Try to insert this class into the map.
14873   LoadExternalVTableUses();
14874   Class = Class->getCanonicalDecl();
14875   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14876     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14877   if (!Pos.second) {
14878     // If we already had an entry, check to see if we are promoting this vtable
14879     // to require a definition. If so, we need to reappend to the VTableUses
14880     // list, since we may have already processed the first entry.
14881     if (DefinitionRequired && !Pos.first->second) {
14882       Pos.first->second = true;
14883     } else {
14884       // Otherwise, we can early exit.
14885       return;
14886     }
14887   } else {
14888     // The Microsoft ABI requires that we perform the destructor body
14889     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14890     // the deleting destructor is emitted with the vtable, not with the
14891     // destructor definition as in the Itanium ABI.
14892     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14893       CXXDestructorDecl *DD = Class->getDestructor();
14894       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14895         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14896           // If this is an out-of-line declaration, marking it referenced will
14897           // not do anything. Manually call CheckDestructor to look up operator
14898           // delete().
14899           ContextRAII SavedContext(*this, DD);
14900           CheckDestructor(DD);
14901         } else {
14902           MarkFunctionReferenced(Loc, Class->getDestructor());
14903         }
14904       }
14905     }
14906   }
14907 
14908   // Local classes need to have their virtual members marked
14909   // immediately. For all other classes, we mark their virtual members
14910   // at the end of the translation unit.
14911   if (Class->isLocalClass())
14912     MarkVirtualMembersReferenced(Loc, Class);
14913   else
14914     VTableUses.push_back(std::make_pair(Class, Loc));
14915 }
14916 
14917 bool Sema::DefineUsedVTables() {
14918   LoadExternalVTableUses();
14919   if (VTableUses.empty())
14920     return false;
14921 
14922   // Note: The VTableUses vector could grow as a result of marking
14923   // the members of a class as "used", so we check the size each
14924   // time through the loop and prefer indices (which are stable) to
14925   // iterators (which are not).
14926   bool DefinedAnything = false;
14927   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14928     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14929     if (!Class)
14930       continue;
14931     TemplateSpecializationKind ClassTSK =
14932         Class->getTemplateSpecializationKind();
14933 
14934     SourceLocation Loc = VTableUses[I].second;
14935 
14936     bool DefineVTable = true;
14937 
14938     // If this class has a key function, but that key function is
14939     // defined in another translation unit, we don't need to emit the
14940     // vtable even though we're using it.
14941     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14942     if (KeyFunction && !KeyFunction->hasBody()) {
14943       // The key function is in another translation unit.
14944       DefineVTable = false;
14945       TemplateSpecializationKind TSK =
14946           KeyFunction->getTemplateSpecializationKind();
14947       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14948              TSK != TSK_ImplicitInstantiation &&
14949              "Instantiations don't have key functions");
14950       (void)TSK;
14951     } else if (!KeyFunction) {
14952       // If we have a class with no key function that is the subject
14953       // of an explicit instantiation declaration, suppress the
14954       // vtable; it will live with the explicit instantiation
14955       // definition.
14956       bool IsExplicitInstantiationDeclaration =
14957           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14958       for (auto R : Class->redecls()) {
14959         TemplateSpecializationKind TSK
14960           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14961         if (TSK == TSK_ExplicitInstantiationDeclaration)
14962           IsExplicitInstantiationDeclaration = true;
14963         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14964           IsExplicitInstantiationDeclaration = false;
14965           break;
14966         }
14967       }
14968 
14969       if (IsExplicitInstantiationDeclaration)
14970         DefineVTable = false;
14971     }
14972 
14973     // The exception specifications for all virtual members may be needed even
14974     // if we are not providing an authoritative form of the vtable in this TU.
14975     // We may choose to emit it available_externally anyway.
14976     if (!DefineVTable) {
14977       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14978       continue;
14979     }
14980 
14981     // Mark all of the virtual members of this class as referenced, so
14982     // that we can build a vtable. Then, tell the AST consumer that a
14983     // vtable for this class is required.
14984     DefinedAnything = true;
14985     MarkVirtualMembersReferenced(Loc, Class);
14986     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
14987     if (VTablesUsed[Canonical])
14988       Consumer.HandleVTable(Class);
14989 
14990     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14991     // no key function or the key function is inlined. Don't warn in C++ ABIs
14992     // that lack key functions, since the user won't be able to make one.
14993     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14994         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14995       const FunctionDecl *KeyFunctionDef = nullptr;
14996       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14997                            KeyFunctionDef->isInlined())) {
14998         Diag(Class->getLocation(),
14999              ClassTSK == TSK_ExplicitInstantiationDefinition
15000                  ? diag::warn_weak_template_vtable
15001                  : diag::warn_weak_vtable)
15002             << Class;
15003       }
15004     }
15005   }
15006   VTableUses.clear();
15007 
15008   return DefinedAnything;
15009 }
15010 
15011 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15012                                                  const CXXRecordDecl *RD) {
15013   for (const auto *I : RD->methods())
15014     if (I->isVirtual() && !I->isPure())
15015       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15016 }
15017 
15018 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15019                                         const CXXRecordDecl *RD) {
15020   // Mark all functions which will appear in RD's vtable as used.
15021   CXXFinalOverriderMap FinalOverriders;
15022   RD->getFinalOverriders(FinalOverriders);
15023   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15024                                             E = FinalOverriders.end();
15025        I != E; ++I) {
15026     for (OverridingMethods::const_iterator OI = I->second.begin(),
15027                                            OE = I->second.end();
15028          OI != OE; ++OI) {
15029       assert(OI->second.size() > 0 && "no final overrider");
15030       CXXMethodDecl *Overrider = OI->second.front().Method;
15031 
15032       // C++ [basic.def.odr]p2:
15033       //   [...] A virtual member function is used if it is not pure. [...]
15034       if (!Overrider->isPure())
15035         MarkFunctionReferenced(Loc, Overrider);
15036     }
15037   }
15038 
15039   // Only classes that have virtual bases need a VTT.
15040   if (RD->getNumVBases() == 0)
15041     return;
15042 
15043   for (const auto &I : RD->bases()) {
15044     const CXXRecordDecl *Base =
15045         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15046     if (Base->getNumVBases() == 0)
15047       continue;
15048     MarkVirtualMembersReferenced(Loc, Base);
15049   }
15050 }
15051 
15052 /// SetIvarInitializers - This routine builds initialization ASTs for the
15053 /// Objective-C implementation whose ivars need be initialized.
15054 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15055   if (!getLangOpts().CPlusPlus)
15056     return;
15057   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15058     SmallVector<ObjCIvarDecl*, 8> ivars;
15059     CollectIvarsToConstructOrDestruct(OID, ivars);
15060     if (ivars.empty())
15061       return;
15062     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15063     for (unsigned i = 0; i < ivars.size(); i++) {
15064       FieldDecl *Field = ivars[i];
15065       if (Field->isInvalidDecl())
15066         continue;
15067 
15068       CXXCtorInitializer *Member;
15069       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15070       InitializationKind InitKind =
15071         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15072 
15073       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15074       ExprResult MemberInit =
15075         InitSeq.Perform(*this, InitEntity, InitKind, None);
15076       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15077       // Note, MemberInit could actually come back empty if no initialization
15078       // is required (e.g., because it would call a trivial default constructor)
15079       if (!MemberInit.get() || MemberInit.isInvalid())
15080         continue;
15081 
15082       Member =
15083         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15084                                          SourceLocation(),
15085                                          MemberInit.getAs<Expr>(),
15086                                          SourceLocation());
15087       AllToInit.push_back(Member);
15088 
15089       // Be sure that the destructor is accessible and is marked as referenced.
15090       if (const RecordType *RecordTy =
15091               Context.getBaseElementType(Field->getType())
15092                   ->getAs<RecordType>()) {
15093         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15094         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15095           MarkFunctionReferenced(Field->getLocation(), Destructor);
15096           CheckDestructorAccess(Field->getLocation(), Destructor,
15097                             PDiag(diag::err_access_dtor_ivar)
15098                               << Context.getBaseElementType(Field->getType()));
15099         }
15100       }
15101     }
15102     ObjCImplementation->setIvarInitializers(Context,
15103                                             AllToInit.data(), AllToInit.size());
15104   }
15105 }
15106 
15107 static
15108 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15109                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15110                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15111                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15112                            Sema &S) {
15113   if (Ctor->isInvalidDecl())
15114     return;
15115 
15116   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15117 
15118   // Target may not be determinable yet, for instance if this is a dependent
15119   // call in an uninstantiated template.
15120   if (Target) {
15121     const FunctionDecl *FNTarget = nullptr;
15122     (void)Target->hasBody(FNTarget);
15123     Target = const_cast<CXXConstructorDecl*>(
15124       cast_or_null<CXXConstructorDecl>(FNTarget));
15125   }
15126 
15127   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15128                      // Avoid dereferencing a null pointer here.
15129                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15130 
15131   if (!Current.insert(Canonical).second)
15132     return;
15133 
15134   // We know that beyond here, we aren't chaining into a cycle.
15135   if (!Target || !Target->isDelegatingConstructor() ||
15136       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15137     Valid.insert(Current.begin(), Current.end());
15138     Current.clear();
15139   // We've hit a cycle.
15140   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15141              Current.count(TCanonical)) {
15142     // If we haven't diagnosed this cycle yet, do so now.
15143     if (!Invalid.count(TCanonical)) {
15144       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15145              diag::warn_delegating_ctor_cycle)
15146         << Ctor;
15147 
15148       // Don't add a note for a function delegating directly to itself.
15149       if (TCanonical != Canonical)
15150         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15151 
15152       CXXConstructorDecl *C = Target;
15153       while (C->getCanonicalDecl() != Canonical) {
15154         const FunctionDecl *FNTarget = nullptr;
15155         (void)C->getTargetConstructor()->hasBody(FNTarget);
15156         assert(FNTarget && "Ctor cycle through bodiless function");
15157 
15158         C = const_cast<CXXConstructorDecl*>(
15159           cast<CXXConstructorDecl>(FNTarget));
15160         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15161       }
15162     }
15163 
15164     Invalid.insert(Current.begin(), Current.end());
15165     Current.clear();
15166   } else {
15167     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15168   }
15169 }
15170 
15171 
15172 void Sema::CheckDelegatingCtorCycles() {
15173   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15174 
15175   for (DelegatingCtorDeclsType::iterator
15176          I = DelegatingCtorDecls.begin(ExternalSource),
15177          E = DelegatingCtorDecls.end();
15178        I != E; ++I)
15179     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15180 
15181   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15182     (*CI)->setInvalidDecl();
15183 }
15184 
15185 namespace {
15186   /// AST visitor that finds references to the 'this' expression.
15187   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15188     Sema &S;
15189 
15190   public:
15191     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15192 
15193     bool VisitCXXThisExpr(CXXThisExpr *E) {
15194       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15195         << E->isImplicit();
15196       return false;
15197     }
15198   };
15199 }
15200 
15201 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15202   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15203   if (!TSInfo)
15204     return false;
15205 
15206   TypeLoc TL = TSInfo->getTypeLoc();
15207   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15208   if (!ProtoTL)
15209     return false;
15210 
15211   // C++11 [expr.prim.general]p3:
15212   //   [The expression this] shall not appear before the optional
15213   //   cv-qualifier-seq and it shall not appear within the declaration of a
15214   //   static member function (although its type and value category are defined
15215   //   within a static member function as they are within a non-static member
15216   //   function). [ Note: this is because declaration matching does not occur
15217   //  until the complete declarator is known. - end note ]
15218   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15219   FindCXXThisExpr Finder(*this);
15220 
15221   // If the return type came after the cv-qualifier-seq, check it now.
15222   if (Proto->hasTrailingReturn() &&
15223       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15224     return true;
15225 
15226   // Check the exception specification.
15227   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15228     return true;
15229 
15230   return checkThisInStaticMemberFunctionAttributes(Method);
15231 }
15232 
15233 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15234   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15235   if (!TSInfo)
15236     return false;
15237 
15238   TypeLoc TL = TSInfo->getTypeLoc();
15239   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15240   if (!ProtoTL)
15241     return false;
15242 
15243   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15244   FindCXXThisExpr Finder(*this);
15245 
15246   switch (Proto->getExceptionSpecType()) {
15247   case EST_Unparsed:
15248   case EST_Uninstantiated:
15249   case EST_Unevaluated:
15250   case EST_BasicNoexcept:
15251   case EST_DynamicNone:
15252   case EST_MSAny:
15253   case EST_None:
15254     break;
15255 
15256   case EST_DependentNoexcept:
15257   case EST_NoexceptFalse:
15258   case EST_NoexceptTrue:
15259     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15260       return true;
15261     LLVM_FALLTHROUGH;
15262 
15263   case EST_Dynamic:
15264     for (const auto &E : Proto->exceptions()) {
15265       if (!Finder.TraverseType(E))
15266         return true;
15267     }
15268     break;
15269   }
15270 
15271   return false;
15272 }
15273 
15274 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15275   FindCXXThisExpr Finder(*this);
15276 
15277   // Check attributes.
15278   for (const auto *A : Method->attrs()) {
15279     // FIXME: This should be emitted by tblgen.
15280     Expr *Arg = nullptr;
15281     ArrayRef<Expr *> Args;
15282     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15283       Arg = G->getArg();
15284     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15285       Arg = G->getArg();
15286     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15287       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15288     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15289       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15290     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15291       Arg = ETLF->getSuccessValue();
15292       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15293     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15294       Arg = STLF->getSuccessValue();
15295       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15296     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15297       Arg = LR->getArg();
15298     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15299       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15300     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15301       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15302     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15303       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15304     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15305       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15306     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15307       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15308 
15309     if (Arg && !Finder.TraverseStmt(Arg))
15310       return true;
15311 
15312     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15313       if (!Finder.TraverseStmt(Args[I]))
15314         return true;
15315     }
15316   }
15317 
15318   return false;
15319 }
15320 
15321 void Sema::checkExceptionSpecification(
15322     bool IsTopLevel, ExceptionSpecificationType EST,
15323     ArrayRef<ParsedType> DynamicExceptions,
15324     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15325     SmallVectorImpl<QualType> &Exceptions,
15326     FunctionProtoType::ExceptionSpecInfo &ESI) {
15327   Exceptions.clear();
15328   ESI.Type = EST;
15329   if (EST == EST_Dynamic) {
15330     Exceptions.reserve(DynamicExceptions.size());
15331     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15332       // FIXME: Preserve type source info.
15333       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15334 
15335       if (IsTopLevel) {
15336         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15337         collectUnexpandedParameterPacks(ET, Unexpanded);
15338         if (!Unexpanded.empty()) {
15339           DiagnoseUnexpandedParameterPacks(
15340               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15341               Unexpanded);
15342           continue;
15343         }
15344       }
15345 
15346       // Check that the type is valid for an exception spec, and
15347       // drop it if not.
15348       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15349         Exceptions.push_back(ET);
15350     }
15351     ESI.Exceptions = Exceptions;
15352     return;
15353   }
15354 
15355   if (isComputedNoexcept(EST)) {
15356     assert((NoexceptExpr->isTypeDependent() ||
15357             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15358             Context.BoolTy) &&
15359            "Parser should have made sure that the expression is boolean");
15360     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15361       ESI.Type = EST_BasicNoexcept;
15362       return;
15363     }
15364 
15365     ESI.NoexceptExpr = NoexceptExpr;
15366     return;
15367   }
15368 }
15369 
15370 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15371              ExceptionSpecificationType EST,
15372              SourceRange SpecificationRange,
15373              ArrayRef<ParsedType> DynamicExceptions,
15374              ArrayRef<SourceRange> DynamicExceptionRanges,
15375              Expr *NoexceptExpr) {
15376   if (!MethodD)
15377     return;
15378 
15379   // Dig out the method we're referring to.
15380   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15381     MethodD = FunTmpl->getTemplatedDecl();
15382 
15383   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15384   if (!Method)
15385     return;
15386 
15387   // Check the exception specification.
15388   llvm::SmallVector<QualType, 4> Exceptions;
15389   FunctionProtoType::ExceptionSpecInfo ESI;
15390   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15391                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15392                               ESI);
15393 
15394   // Update the exception specification on the function type.
15395   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15396 
15397   if (Method->isStatic())
15398     checkThisInStaticMemberFunctionExceptionSpec(Method);
15399 
15400   if (Method->isVirtual()) {
15401     // Check overrides, which we previously had to delay.
15402     for (const CXXMethodDecl *O : Method->overridden_methods())
15403       CheckOverridingFunctionExceptionSpec(Method, O);
15404   }
15405 }
15406 
15407 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15408 ///
15409 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15410                                        SourceLocation DeclStart,
15411                                        Declarator &D, Expr *BitWidth,
15412                                        InClassInitStyle InitStyle,
15413                                        AccessSpecifier AS,
15414                                        AttributeList *MSPropertyAttr) {
15415   IdentifierInfo *II = D.getIdentifier();
15416   if (!II) {
15417     Diag(DeclStart, diag::err_anonymous_property);
15418     return nullptr;
15419   }
15420   SourceLocation Loc = D.getIdentifierLoc();
15421 
15422   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15423   QualType T = TInfo->getType();
15424   if (getLangOpts().CPlusPlus) {
15425     CheckExtraCXXDefaultArguments(D);
15426 
15427     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15428                                         UPPC_DataMemberType)) {
15429       D.setInvalidType();
15430       T = Context.IntTy;
15431       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15432     }
15433   }
15434 
15435   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15436 
15437   if (D.getDeclSpec().isInlineSpecified())
15438     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15439         << getLangOpts().CPlusPlus17;
15440   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15441     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15442          diag::err_invalid_thread)
15443       << DeclSpec::getSpecifierName(TSCS);
15444 
15445   // Check to see if this name was declared as a member previously
15446   NamedDecl *PrevDecl = nullptr;
15447   LookupResult Previous(*this, II, Loc, LookupMemberName,
15448                         ForVisibleRedeclaration);
15449   LookupName(Previous, S);
15450   switch (Previous.getResultKind()) {
15451   case LookupResult::Found:
15452   case LookupResult::FoundUnresolvedValue:
15453     PrevDecl = Previous.getAsSingle<NamedDecl>();
15454     break;
15455 
15456   case LookupResult::FoundOverloaded:
15457     PrevDecl = Previous.getRepresentativeDecl();
15458     break;
15459 
15460   case LookupResult::NotFound:
15461   case LookupResult::NotFoundInCurrentInstantiation:
15462   case LookupResult::Ambiguous:
15463     break;
15464   }
15465 
15466   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15467     // Maybe we will complain about the shadowed template parameter.
15468     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15469     // Just pretend that we didn't see the previous declaration.
15470     PrevDecl = nullptr;
15471   }
15472 
15473   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15474     PrevDecl = nullptr;
15475 
15476   SourceLocation TSSL = D.getLocStart();
15477   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15478   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15479       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15480   ProcessDeclAttributes(TUScope, NewPD, D);
15481   NewPD->setAccess(AS);
15482 
15483   if (NewPD->isInvalidDecl())
15484     Record->setInvalidDecl();
15485 
15486   if (D.getDeclSpec().isModulePrivateSpecified())
15487     NewPD->setModulePrivate();
15488 
15489   if (NewPD->isInvalidDecl() && PrevDecl) {
15490     // Don't introduce NewFD into scope; there's already something
15491     // with the same name in the same scope.
15492   } else if (II) {
15493     PushOnScopeChains(NewPD, S);
15494   } else
15495     Record->addDecl(NewPD);
15496 
15497   return NewPD;
15498 }
15499