1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.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/ScopeExit.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include <map>
46 #include <set>
47 
48 using namespace clang;
49 
50 //===----------------------------------------------------------------------===//
51 // CheckDefaultArgumentVisitor
52 //===----------------------------------------------------------------------===//
53 
54 namespace {
55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56 /// the default argument of a parameter to determine whether it
57 /// contains any ill-formed subexpressions. For example, this will
58 /// diagnose the use of local variables or parameters within the
59 /// default argument expression.
60 class CheckDefaultArgumentVisitor
61     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62   Sema &S;
63   const Expr *DefaultArg;
64 
65 public:
66   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67       : S(S), DefaultArg(DefaultArg) {}
68 
69   bool VisitExpr(const Expr *Node);
70   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72   bool VisitLambdaExpr(const LambdaExpr *Lambda);
73   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74 };
75 
76 /// VisitExpr - Visit all of the children of this expression.
77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78   bool IsInvalid = false;
79   for (const Stmt *SubStmt : Node->children())
80     IsInvalid |= Visit(SubStmt);
81   return IsInvalid;
82 }
83 
84 /// VisitDeclRefExpr - Visit a reference to a declaration, to
85 /// determine whether this declaration can be used in the default
86 /// argument expression.
87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88   const NamedDecl *Decl = DRE->getDecl();
89   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90     // C++ [dcl.fct.default]p9:
91     //   [...] parameters of a function shall not be used in default
92     //   argument expressions, even if they are not evaluated. [...]
93     //
94     // C++17 [dcl.fct.default]p9 (by CWG 2082):
95     //   [...] A parameter shall not appear as a potentially-evaluated
96     //   expression in a default argument. [...]
97     //
98     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99       return S.Diag(DRE->getBeginLoc(),
100                     diag::err_param_default_argument_references_param)
101              << Param->getDeclName() << DefaultArg->getSourceRange();
102   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103     // C++ [dcl.fct.default]p7:
104     //   Local variables shall not be used in default argument
105     //   expressions.
106     //
107     // C++17 [dcl.fct.default]p7 (by CWG 2082):
108     //   A local variable shall not appear as a potentially-evaluated
109     //   expression in a default argument.
110     //
111     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113     //
114     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115       return S.Diag(DRE->getBeginLoc(),
116                     diag::err_param_default_argument_references_local)
117              << VDecl->getDeclName() << DefaultArg->getSourceRange();
118   }
119 
120   return false;
121 }
122 
123 /// VisitCXXThisExpr - Visit a C++ "this" expression.
124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125   // C++ [dcl.fct.default]p8:
126   //   The keyword this shall not be used in a default argument of a
127   //   member function.
128   return S.Diag(ThisE->getBeginLoc(),
129                 diag::err_param_default_argument_references_this)
130          << ThisE->getSourceRange();
131 }
132 
133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134     const PseudoObjectExpr *POE) {
135   bool Invalid = false;
136   for (const Expr *E : POE->semantics()) {
137     // Look through bindings.
138     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139       E = OVE->getSourceExpr();
140       assert(E && "pseudo-object binding without source expression?");
141     }
142 
143     Invalid |= Visit(E);
144   }
145   return Invalid;
146 }
147 
148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149   // C++11 [expr.lambda.prim]p13:
150   //   A lambda-expression appearing in a default argument shall not
151   //   implicitly or explicitly capture any entity.
152   if (Lambda->capture_begin() == Lambda->capture_end())
153     return false;
154 
155   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156 }
157 } // namespace
158 
159 void
160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161                                                  const CXXMethodDecl *Method) {
162   // If we have an MSAny spec already, don't bother.
163   if (!Method || ComputedEST == EST_MSAny)
164     return;
165 
166   const FunctionProtoType *Proto
167     = Method->getType()->getAs<FunctionProtoType>();
168   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169   if (!Proto)
170     return;
171 
172   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173 
174   // If we have a throw-all spec at this point, ignore the function.
175   if (ComputedEST == EST_None)
176     return;
177 
178   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179     EST = EST_BasicNoexcept;
180 
181   switch (EST) {
182   case EST_Unparsed:
183   case EST_Uninstantiated:
184   case EST_Unevaluated:
185     llvm_unreachable("should not see unresolved exception specs here");
186 
187   // If this function can throw any exceptions, make a note of that.
188   case EST_MSAny:
189   case EST_None:
190     // FIXME: Whichever we see last of MSAny and None determines our result.
191     // We should make a consistent, order-independent choice here.
192     ClearExceptions();
193     ComputedEST = EST;
194     return;
195   case EST_NoexceptFalse:
196     ClearExceptions();
197     ComputedEST = EST_None;
198     return;
199   // FIXME: If the call to this decl is using any of its default arguments, we
200   // need to search them for potentially-throwing calls.
201   // If this function has a basic noexcept, it doesn't affect the outcome.
202   case EST_BasicNoexcept:
203   case EST_NoexceptTrue:
204   case EST_NoThrow:
205     return;
206   // If we're still at noexcept(true) and there's a throw() callee,
207   // change to that specification.
208   case EST_DynamicNone:
209     if (ComputedEST == EST_BasicNoexcept)
210       ComputedEST = EST_DynamicNone;
211     return;
212   case EST_DependentNoexcept:
213     llvm_unreachable(
214         "should not generate implicit declarations for dependent cases");
215   case EST_Dynamic:
216     break;
217   }
218   assert(EST == EST_Dynamic && "EST case not considered earlier.");
219   assert(ComputedEST != EST_None &&
220          "Shouldn't collect exceptions when throw-all is guaranteed.");
221   ComputedEST = EST_Dynamic;
222   // Record the exceptions in this function's exception specification.
223   for (const auto &E : Proto->exceptions())
224     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225       Exceptions.push_back(E);
226 }
227 
228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229   if (!S || ComputedEST == EST_MSAny)
230     return;
231 
232   // FIXME:
233   //
234   // C++0x [except.spec]p14:
235   //   [An] implicit exception-specification specifies the type-id T if and
236   // only if T is allowed by the exception-specification of a function directly
237   // invoked by f's implicit definition; f shall allow all exceptions if any
238   // function it directly invokes allows all exceptions, and f shall allow no
239   // exceptions if every function it directly invokes allows no exceptions.
240   //
241   // Note in particular that if an implicit exception-specification is generated
242   // for a function containing a throw-expression, that specification can still
243   // be noexcept(true).
244   //
245   // Note also that 'directly invoked' is not defined in the standard, and there
246   // is no indication that we should only consider potentially-evaluated calls.
247   //
248   // Ultimately we should implement the intent of the standard: the exception
249   // specification should be the set of exceptions which can be thrown by the
250   // implicit definition. For now, we assume that any non-nothrow expression can
251   // throw any exception.
252 
253   if (Self->canThrow(S))
254     ComputedEST = EST_None;
255 }
256 
257 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
258                                              SourceLocation EqualLoc) {
259   if (RequireCompleteType(Param->getLocation(), Param->getType(),
260                           diag::err_typecheck_decl_incomplete_type))
261     return true;
262 
263   // C++ [dcl.fct.default]p5
264   //   A default argument expression is implicitly converted (clause
265   //   4) to the parameter type. The default argument expression has
266   //   the same semantic constraints as the initializer expression in
267   //   a declaration of a variable of the parameter type, using the
268   //   copy-initialization semantics (8.5).
269   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
270                                                                     Param);
271   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
272                                                            EqualLoc);
273   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
274   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
275   if (Result.isInvalid())
276     return true;
277   Arg = Result.getAs<Expr>();
278 
279   CheckCompletedExpr(Arg, EqualLoc);
280   Arg = MaybeCreateExprWithCleanups(Arg);
281 
282   return Arg;
283 }
284 
285 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
286                                    SourceLocation EqualLoc) {
287   // Add the default argument to the parameter
288   Param->setDefaultArg(Arg);
289 
290   // We have already instantiated this parameter; provide each of the
291   // instantiations with the uninstantiated default argument.
292   UnparsedDefaultArgInstantiationsMap::iterator InstPos
293     = UnparsedDefaultArgInstantiations.find(Param);
294   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
295     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
296       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
297 
298     // We're done tracking this parameter's instantiations.
299     UnparsedDefaultArgInstantiations.erase(InstPos);
300   }
301 }
302 
303 /// ActOnParamDefaultArgument - Check whether the default argument
304 /// provided for a function parameter is well-formed. If so, attach it
305 /// to the parameter declaration.
306 void
307 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
308                                 Expr *DefaultArg) {
309   if (!param || !DefaultArg)
310     return;
311 
312   ParmVarDecl *Param = cast<ParmVarDecl>(param);
313   UnparsedDefaultArgLocs.erase(Param);
314 
315   auto Fail = [&] {
316     Param->setInvalidDecl();
317     Param->setDefaultArg(new (Context) OpaqueValueExpr(
318         EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
319   };
320 
321   // Default arguments are only permitted in C++
322   if (!getLangOpts().CPlusPlus) {
323     Diag(EqualLoc, diag::err_param_default_argument)
324       << DefaultArg->getSourceRange();
325     return Fail();
326   }
327 
328   // Check for unexpanded parameter packs.
329   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
330     return Fail();
331   }
332 
333   // C++11 [dcl.fct.default]p3
334   //   A default argument expression [...] shall not be specified for a
335   //   parameter pack.
336   if (Param->isParameterPack()) {
337     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
338         << DefaultArg->getSourceRange();
339     // Recover by discarding the default argument.
340     Param->setDefaultArg(nullptr);
341     return;
342   }
343 
344   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
345   if (Result.isInvalid())
346     return Fail();
347 
348   DefaultArg = Result.getAs<Expr>();
349 
350   // Check that the default argument is well-formed
351   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
352   if (DefaultArgChecker.Visit(DefaultArg))
353     return Fail();
354 
355   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
356 }
357 
358 /// ActOnParamUnparsedDefaultArgument - We've seen a default
359 /// argument for a function parameter, but we can't parse it yet
360 /// because we're inside a class definition. Note that this default
361 /// argument will be parsed later.
362 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
363                                              SourceLocation EqualLoc,
364                                              SourceLocation ArgLoc) {
365   if (!param)
366     return;
367 
368   ParmVarDecl *Param = cast<ParmVarDecl>(param);
369   Param->setUnparsedDefaultArg();
370   UnparsedDefaultArgLocs[Param] = ArgLoc;
371 }
372 
373 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
374 /// the default argument for the parameter param failed.
375 void Sema::ActOnParamDefaultArgumentError(Decl *param,
376                                           SourceLocation EqualLoc) {
377   if (!param)
378     return;
379 
380   ParmVarDecl *Param = cast<ParmVarDecl>(param);
381   Param->setInvalidDecl();
382   UnparsedDefaultArgLocs.erase(Param);
383   Param->setDefaultArg(new(Context)
384                        OpaqueValueExpr(EqualLoc,
385                                        Param->getType().getNonReferenceType(),
386                                        VK_RValue));
387 }
388 
389 /// CheckExtraCXXDefaultArguments - Check for any extra default
390 /// arguments in the declarator, which is not a function declaration
391 /// or definition and therefore is not permitted to have default
392 /// arguments. This routine should be invoked for every declarator
393 /// that is not a function declaration or definition.
394 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
395   // C++ [dcl.fct.default]p3
396   //   A default argument expression shall be specified only in the
397   //   parameter-declaration-clause of a function declaration or in a
398   //   template-parameter (14.1). It shall not be specified for a
399   //   parameter pack. If it is specified in a
400   //   parameter-declaration-clause, it shall not occur within a
401   //   declarator or abstract-declarator of a parameter-declaration.
402   bool MightBeFunction = D.isFunctionDeclarationContext();
403   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
404     DeclaratorChunk &chunk = D.getTypeObject(i);
405     if (chunk.Kind == DeclaratorChunk::Function) {
406       if (MightBeFunction) {
407         // This is a function declaration. It can have default arguments, but
408         // keep looking in case its return type is a function type with default
409         // arguments.
410         MightBeFunction = false;
411         continue;
412       }
413       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
414            ++argIdx) {
415         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
416         if (Param->hasUnparsedDefaultArg()) {
417           std::unique_ptr<CachedTokens> Toks =
418               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
419           SourceRange SR;
420           if (Toks->size() > 1)
421             SR = SourceRange((*Toks)[1].getLocation(),
422                              Toks->back().getLocation());
423           else
424             SR = UnparsedDefaultArgLocs[Param];
425           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
426             << SR;
427         } else if (Param->getDefaultArg()) {
428           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
429             << Param->getDefaultArg()->getSourceRange();
430           Param->setDefaultArg(nullptr);
431         }
432       }
433     } else if (chunk.Kind != DeclaratorChunk::Paren) {
434       MightBeFunction = false;
435     }
436   }
437 }
438 
439 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
440   return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
441     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
442   });
443 }
444 
445 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
446 /// function, once we already know that they have the same
447 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
448 /// error, false otherwise.
449 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
450                                 Scope *S) {
451   bool Invalid = false;
452 
453   // The declaration context corresponding to the scope is the semantic
454   // parent, unless this is a local function declaration, in which case
455   // it is that surrounding function.
456   DeclContext *ScopeDC = New->isLocalExternDecl()
457                              ? New->getLexicalDeclContext()
458                              : New->getDeclContext();
459 
460   // Find the previous declaration for the purpose of default arguments.
461   FunctionDecl *PrevForDefaultArgs = Old;
462   for (/**/; PrevForDefaultArgs;
463        // Don't bother looking back past the latest decl if this is a local
464        // extern declaration; nothing else could work.
465        PrevForDefaultArgs = New->isLocalExternDecl()
466                                 ? nullptr
467                                 : PrevForDefaultArgs->getPreviousDecl()) {
468     // Ignore hidden declarations.
469     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
470       continue;
471 
472     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
473         !New->isCXXClassMember()) {
474       // Ignore default arguments of old decl if they are not in
475       // the same scope and this is not an out-of-line definition of
476       // a member function.
477       continue;
478     }
479 
480     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
481       // If only one of these is a local function declaration, then they are
482       // declared in different scopes, even though isDeclInScope may think
483       // they're in the same scope. (If both are local, the scope check is
484       // sufficient, and if neither is local, then they are in the same scope.)
485       continue;
486     }
487 
488     // We found the right previous declaration.
489     break;
490   }
491 
492   // C++ [dcl.fct.default]p4:
493   //   For non-template functions, default arguments can be added in
494   //   later declarations of a function in the same
495   //   scope. Declarations in different scopes have completely
496   //   distinct sets of default arguments. That is, declarations in
497   //   inner scopes do not acquire default arguments from
498   //   declarations in outer scopes, and vice versa. In a given
499   //   function declaration, all parameters subsequent to a
500   //   parameter with a default argument shall have default
501   //   arguments supplied in this or previous declarations. A
502   //   default argument shall not be redefined by a later
503   //   declaration (not even to the same value).
504   //
505   // C++ [dcl.fct.default]p6:
506   //   Except for member functions of class templates, the default arguments
507   //   in a member function definition that appears outside of the class
508   //   definition are added to the set of default arguments provided by the
509   //   member function declaration in the class definition.
510   for (unsigned p = 0, NumParams = PrevForDefaultArgs
511                                        ? PrevForDefaultArgs->getNumParams()
512                                        : 0;
513        p < NumParams; ++p) {
514     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
515     ParmVarDecl *NewParam = New->getParamDecl(p);
516 
517     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
518     bool NewParamHasDfl = NewParam->hasDefaultArg();
519 
520     if (OldParamHasDfl && NewParamHasDfl) {
521       unsigned DiagDefaultParamID =
522         diag::err_param_default_argument_redefinition;
523 
524       // MSVC accepts that default parameters be redefined for member functions
525       // of template class. The new default parameter's value is ignored.
526       Invalid = true;
527       if (getLangOpts().MicrosoftExt) {
528         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
529         if (MD && MD->getParent()->getDescribedClassTemplate()) {
530           // Merge the old default argument into the new parameter.
531           NewParam->setHasInheritedDefaultArg();
532           if (OldParam->hasUninstantiatedDefaultArg())
533             NewParam->setUninstantiatedDefaultArg(
534                                       OldParam->getUninstantiatedDefaultArg());
535           else
536             NewParam->setDefaultArg(OldParam->getInit());
537           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
538           Invalid = false;
539         }
540       }
541 
542       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
543       // hint here. Alternatively, we could walk the type-source information
544       // for NewParam to find the last source location in the type... but it
545       // isn't worth the effort right now. This is the kind of test case that
546       // is hard to get right:
547       //   int f(int);
548       //   void g(int (*fp)(int) = f);
549       //   void g(int (*fp)(int) = &f);
550       Diag(NewParam->getLocation(), DiagDefaultParamID)
551         << NewParam->getDefaultArgRange();
552 
553       // Look for the function declaration where the default argument was
554       // actually written, which may be a declaration prior to Old.
555       for (auto Older = PrevForDefaultArgs;
556            OldParam->hasInheritedDefaultArg(); /**/) {
557         Older = Older->getPreviousDecl();
558         OldParam = Older->getParamDecl(p);
559       }
560 
561       Diag(OldParam->getLocation(), diag::note_previous_definition)
562         << OldParam->getDefaultArgRange();
563     } else if (OldParamHasDfl) {
564       // Merge the old default argument into the new parameter unless the new
565       // function is a friend declaration in a template class. In the latter
566       // case the default arguments will be inherited when the friend
567       // declaration will be instantiated.
568       if (New->getFriendObjectKind() == Decl::FOK_None ||
569           !New->getLexicalDeclContext()->isDependentContext()) {
570         // It's important to use getInit() here;  getDefaultArg()
571         // strips off any top-level ExprWithCleanups.
572         NewParam->setHasInheritedDefaultArg();
573         if (OldParam->hasUnparsedDefaultArg())
574           NewParam->setUnparsedDefaultArg();
575         else if (OldParam->hasUninstantiatedDefaultArg())
576           NewParam->setUninstantiatedDefaultArg(
577                                        OldParam->getUninstantiatedDefaultArg());
578         else
579           NewParam->setDefaultArg(OldParam->getInit());
580       }
581     } else if (NewParamHasDfl) {
582       if (New->getDescribedFunctionTemplate()) {
583         // Paragraph 4, quoted above, only applies to non-template functions.
584         Diag(NewParam->getLocation(),
585              diag::err_param_default_argument_template_redecl)
586           << NewParam->getDefaultArgRange();
587         Diag(PrevForDefaultArgs->getLocation(),
588              diag::note_template_prev_declaration)
589             << false;
590       } else if (New->getTemplateSpecializationKind()
591                    != TSK_ImplicitInstantiation &&
592                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
593         // C++ [temp.expr.spec]p21:
594         //   Default function arguments shall not be specified in a declaration
595         //   or a definition for one of the following explicit specializations:
596         //     - the explicit specialization of a function template;
597         //     - the explicit specialization of a member function template;
598         //     - the explicit specialization of a member function of a class
599         //       template where the class template specialization to which the
600         //       member function specialization belongs is implicitly
601         //       instantiated.
602         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
603           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
604           << New->getDeclName()
605           << NewParam->getDefaultArgRange();
606       } else if (New->getDeclContext()->isDependentContext()) {
607         // C++ [dcl.fct.default]p6 (DR217):
608         //   Default arguments for a member function of a class template shall
609         //   be specified on the initial declaration of the member function
610         //   within the class template.
611         //
612         // Reading the tea leaves a bit in DR217 and its reference to DR205
613         // leads me to the conclusion that one cannot add default function
614         // arguments for an out-of-line definition of a member function of a
615         // dependent type.
616         int WhichKind = 2;
617         if (CXXRecordDecl *Record
618               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
619           if (Record->getDescribedClassTemplate())
620             WhichKind = 0;
621           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
622             WhichKind = 1;
623           else
624             WhichKind = 2;
625         }
626 
627         Diag(NewParam->getLocation(),
628              diag::err_param_default_argument_member_template_redecl)
629           << WhichKind
630           << NewParam->getDefaultArgRange();
631       }
632     }
633   }
634 
635   // DR1344: If a default argument is added outside a class definition and that
636   // default argument makes the function a special member function, the program
637   // is ill-formed. This can only happen for constructors.
638   if (isa<CXXConstructorDecl>(New) &&
639       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
640     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
641                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
642     if (NewSM != OldSM) {
643       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
644       assert(NewParam->hasDefaultArg());
645       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
646         << NewParam->getDefaultArgRange() << NewSM;
647       Diag(Old->getLocation(), diag::note_previous_declaration);
648     }
649   }
650 
651   const FunctionDecl *Def;
652   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
653   // template has a constexpr specifier then all its declarations shall
654   // contain the constexpr specifier.
655   if (New->getConstexprKind() != Old->getConstexprKind()) {
656     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
657         << New << static_cast<int>(New->getConstexprKind())
658         << static_cast<int>(Old->getConstexprKind());
659     Diag(Old->getLocation(), diag::note_previous_declaration);
660     Invalid = true;
661   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
662              Old->isDefined(Def) &&
663              // If a friend function is inlined but does not have 'inline'
664              // specifier, it is a definition. Do not report attribute conflict
665              // in this case, redefinition will be diagnosed later.
666              (New->isInlineSpecified() ||
667               New->getFriendObjectKind() == Decl::FOK_None)) {
668     // C++11 [dcl.fcn.spec]p4:
669     //   If the definition of a function appears in a translation unit before its
670     //   first declaration as inline, the program is ill-formed.
671     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672     Diag(Def->getLocation(), diag::note_previous_definition);
673     Invalid = true;
674   }
675 
676   // C++17 [temp.deduct.guide]p3:
677   //   Two deduction guide declarations in the same translation unit
678   //   for the same class template shall not have equivalent
679   //   parameter-declaration-clauses.
680   if (isa<CXXDeductionGuideDecl>(New) &&
681       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
682     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683     Diag(Old->getLocation(), diag::note_previous_declaration);
684   }
685 
686   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687   // argument expression, that declaration shall be a definition and shall be
688   // the only declaration of the function or function template in the
689   // translation unit.
690   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691       functionDeclHasDefaultArgument(Old)) {
692     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693     Diag(Old->getLocation(), diag::note_previous_declaration);
694     Invalid = true;
695   }
696 
697   // C++11 [temp.friend]p4 (DR329):
698   //   When a function is defined in a friend function declaration in a class
699   //   template, the function is instantiated when the function is odr-used.
700   //   The same restrictions on multiple declarations and definitions that
701   //   apply to non-template function declarations and definitions also apply
702   //   to these implicit definitions.
703   const FunctionDecl *OldDefinition = nullptr;
704   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
705       Old->isDefined(OldDefinition, true))
706     CheckForFunctionRedefinition(New, OldDefinition);
707 
708   return Invalid;
709 }
710 
711 NamedDecl *
712 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
713                                    MultiTemplateParamsArg TemplateParamLists) {
714   assert(D.isDecompositionDeclarator());
715   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
716 
717   // The syntax only allows a decomposition declarator as a simple-declaration,
718   // a for-range-declaration, or a condition in Clang, but we parse it in more
719   // cases than that.
720   if (!D.mayHaveDecompositionDeclarator()) {
721     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
722       << Decomp.getSourceRange();
723     return nullptr;
724   }
725 
726   if (!TemplateParamLists.empty()) {
727     // FIXME: There's no rule against this, but there are also no rules that
728     // would actually make it usable, so we reject it for now.
729     Diag(TemplateParamLists.front()->getTemplateLoc(),
730          diag::err_decomp_decl_template);
731     return nullptr;
732   }
733 
734   Diag(Decomp.getLSquareLoc(),
735        !getLangOpts().CPlusPlus17
736            ? diag::ext_decomp_decl
737            : D.getContext() == DeclaratorContext::Condition
738                  ? diag::ext_decomp_decl_cond
739                  : diag::warn_cxx14_compat_decomp_decl)
740       << Decomp.getSourceRange();
741 
742   // The semantic context is always just the current context.
743   DeclContext *const DC = CurContext;
744 
745   // C++17 [dcl.dcl]/8:
746   //   The decl-specifier-seq shall contain only the type-specifier auto
747   //   and cv-qualifiers.
748   // C++2a [dcl.dcl]/8:
749   //   If decl-specifier-seq contains any decl-specifier other than static,
750   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
751   auto &DS = D.getDeclSpec();
752   {
753     SmallVector<StringRef, 8> BadSpecifiers;
754     SmallVector<SourceLocation, 8> BadSpecifierLocs;
755     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
756     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
757     if (auto SCS = DS.getStorageClassSpec()) {
758       if (SCS == DeclSpec::SCS_static) {
759         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
760         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
761       } else {
762         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
763         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
764       }
765     }
766     if (auto TSCS = DS.getThreadStorageClassSpec()) {
767       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
768       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
769     }
770     if (DS.hasConstexprSpecifier()) {
771       BadSpecifiers.push_back(
772           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
773       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
774     }
775     if (DS.isInlineSpecified()) {
776       BadSpecifiers.push_back("inline");
777       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
778     }
779     if (!BadSpecifiers.empty()) {
780       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
781       Err << (int)BadSpecifiers.size()
782           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
783       // Don't add FixItHints to remove the specifiers; we do still respect
784       // them when building the underlying variable.
785       for (auto Loc : BadSpecifierLocs)
786         Err << SourceRange(Loc, Loc);
787     } else if (!CPlusPlus20Specifiers.empty()) {
788       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
789                          getLangOpts().CPlusPlus20
790                              ? diag::warn_cxx17_compat_decomp_decl_spec
791                              : diag::ext_decomp_decl_spec);
792       Warn << (int)CPlusPlus20Specifiers.size()
793            << llvm::join(CPlusPlus20Specifiers.begin(),
794                          CPlusPlus20Specifiers.end(), " ");
795       for (auto Loc : CPlusPlus20SpecifierLocs)
796         Warn << SourceRange(Loc, Loc);
797     }
798     // We can't recover from it being declared as a typedef.
799     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
800       return nullptr;
801   }
802 
803   // C++2a [dcl.struct.bind]p1:
804   //   A cv that includes volatile is deprecated
805   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
806       getLangOpts().CPlusPlus20)
807     Diag(DS.getVolatileSpecLoc(),
808          diag::warn_deprecated_volatile_structured_binding);
809 
810   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
811   QualType R = TInfo->getType();
812 
813   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
814                                       UPPC_DeclarationType))
815     D.setInvalidType();
816 
817   // The syntax only allows a single ref-qualifier prior to the decomposition
818   // declarator. No other declarator chunks are permitted. Also check the type
819   // specifier here.
820   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
821       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
822       (D.getNumTypeObjects() == 1 &&
823        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
824     Diag(Decomp.getLSquareLoc(),
825          (D.hasGroupingParens() ||
826           (D.getNumTypeObjects() &&
827            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
828              ? diag::err_decomp_decl_parens
829              : diag::err_decomp_decl_type)
830         << R;
831 
832     // In most cases, there's no actual problem with an explicitly-specified
833     // type, but a function type won't work here, and ActOnVariableDeclarator
834     // shouldn't be called for such a type.
835     if (R->isFunctionType())
836       D.setInvalidType();
837   }
838 
839   // Build the BindingDecls.
840   SmallVector<BindingDecl*, 8> Bindings;
841 
842   // Build the BindingDecls.
843   for (auto &B : D.getDecompositionDeclarator().bindings()) {
844     // Check for name conflicts.
845     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
846     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847                           ForVisibleRedeclaration);
848     LookupName(Previous, S,
849                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
850 
851     // It's not permitted to shadow a template parameter name.
852     if (Previous.isSingleResult() &&
853         Previous.getFoundDecl()->isTemplateParameter()) {
854       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
855                                       Previous.getFoundDecl());
856       Previous.clear();
857     }
858 
859     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
860 
861     // Find the shadowed declaration before filtering for scope.
862     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
863                                   ? getShadowedDeclaration(BD, Previous)
864                                   : nullptr;
865 
866     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
867                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
868     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
869                          /*AllowInlineNamespace*/false);
870 
871     if (!Previous.empty()) {
872       auto *Old = Previous.getRepresentativeDecl();
873       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
874       Diag(Old->getLocation(), diag::note_previous_definition);
875     } else if (ShadowedDecl && !D.isRedeclaration()) {
876       CheckShadow(BD, ShadowedDecl, Previous);
877     }
878     PushOnScopeChains(BD, S, true);
879     Bindings.push_back(BD);
880     ParsingInitForAutoVars.insert(BD);
881   }
882 
883   // There are no prior lookup results for the variable itself, because it
884   // is unnamed.
885   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
886                                Decomp.getLSquareLoc());
887   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
888                         ForVisibleRedeclaration);
889 
890   // Build the variable that holds the non-decomposed object.
891   bool AddToScope = true;
892   NamedDecl *New =
893       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
894                               MultiTemplateParamsArg(), AddToScope, Bindings);
895   if (AddToScope) {
896     S->AddDecl(New);
897     CurContext->addHiddenDecl(New);
898   }
899 
900   if (isInOpenMPDeclareTargetContext())
901     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
902 
903   return New;
904 }
905 
906 static bool checkSimpleDecomposition(
907     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
908     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
909     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
910   if ((int64_t)Bindings.size() != NumElems) {
911     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
912         << DecompType << (unsigned)Bindings.size()
913         << (unsigned)NumElems.getLimitedValue(UINT_MAX) << NumElems.toString(10)
914         << (NumElems < Bindings.size());
915     return true;
916   }
917 
918   unsigned I = 0;
919   for (auto *B : Bindings) {
920     SourceLocation Loc = B->getLocation();
921     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
922     if (E.isInvalid())
923       return true;
924     E = GetInit(Loc, E.get(), I++);
925     if (E.isInvalid())
926       return true;
927     B->setBinding(ElemType, E.get());
928   }
929 
930   return false;
931 }
932 
933 static bool checkArrayLikeDecomposition(Sema &S,
934                                         ArrayRef<BindingDecl *> Bindings,
935                                         ValueDecl *Src, QualType DecompType,
936                                         const llvm::APSInt &NumElems,
937                                         QualType ElemType) {
938   return checkSimpleDecomposition(
939       S, Bindings, Src, DecompType, NumElems, ElemType,
940       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
941         ExprResult E = S.ActOnIntegerConstant(Loc, I);
942         if (E.isInvalid())
943           return ExprError();
944         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
945       });
946 }
947 
948 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
949                                     ValueDecl *Src, QualType DecompType,
950                                     const ConstantArrayType *CAT) {
951   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
952                                      llvm::APSInt(CAT->getSize()),
953                                      CAT->getElementType());
954 }
955 
956 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
957                                      ValueDecl *Src, QualType DecompType,
958                                      const VectorType *VT) {
959   return checkArrayLikeDecomposition(
960       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
961       S.Context.getQualifiedType(VT->getElementType(),
962                                  DecompType.getQualifiers()));
963 }
964 
965 static bool checkComplexDecomposition(Sema &S,
966                                       ArrayRef<BindingDecl *> Bindings,
967                                       ValueDecl *Src, QualType DecompType,
968                                       const ComplexType *CT) {
969   return checkSimpleDecomposition(
970       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
971       S.Context.getQualifiedType(CT->getElementType(),
972                                  DecompType.getQualifiers()),
973       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
974         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
975       });
976 }
977 
978 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
979                                      TemplateArgumentListInfo &Args) {
980   SmallString<128> SS;
981   llvm::raw_svector_ostream OS(SS);
982   bool First = true;
983   for (auto &Arg : Args.arguments()) {
984     if (!First)
985       OS << ", ";
986     Arg.getArgument().print(PrintingPolicy, OS);
987     First = false;
988   }
989   return std::string(OS.str());
990 }
991 
992 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
993                                      SourceLocation Loc, StringRef Trait,
994                                      TemplateArgumentListInfo &Args,
995                                      unsigned DiagID) {
996   auto DiagnoseMissing = [&] {
997     if (DiagID)
998       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
999                                                Args);
1000     return true;
1001   };
1002 
1003   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1004   NamespaceDecl *Std = S.getStdNamespace();
1005   if (!Std)
1006     return DiagnoseMissing();
1007 
1008   // Look up the trait itself, within namespace std. We can diagnose various
1009   // problems with this lookup even if we've been asked to not diagnose a
1010   // missing specialization, because this can only fail if the user has been
1011   // declaring their own names in namespace std or we don't support the
1012   // standard library implementation in use.
1013   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1014                       Loc, Sema::LookupOrdinaryName);
1015   if (!S.LookupQualifiedName(Result, Std))
1016     return DiagnoseMissing();
1017   if (Result.isAmbiguous())
1018     return true;
1019 
1020   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1021   if (!TraitTD) {
1022     Result.suppressDiagnostics();
1023     NamedDecl *Found = *Result.begin();
1024     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1025     S.Diag(Found->getLocation(), diag::note_declared_at);
1026     return true;
1027   }
1028 
1029   // Build the template-id.
1030   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1031   if (TraitTy.isNull())
1032     return true;
1033   if (!S.isCompleteType(Loc, TraitTy)) {
1034     if (DiagID)
1035       S.RequireCompleteType(
1036           Loc, TraitTy, DiagID,
1037           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1038     return true;
1039   }
1040 
1041   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1042   assert(RD && "specialization of class template is not a class?");
1043 
1044   // Look up the member of the trait type.
1045   S.LookupQualifiedName(TraitMemberLookup, RD);
1046   return TraitMemberLookup.isAmbiguous();
1047 }
1048 
1049 static TemplateArgumentLoc
1050 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1051                                    uint64_t I) {
1052   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1053   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1054 }
1055 
1056 static TemplateArgumentLoc
1057 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1058   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1059 }
1060 
1061 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1062 
1063 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1064                                llvm::APSInt &Size) {
1065   EnterExpressionEvaluationContext ContextRAII(
1066       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1067 
1068   DeclarationName Value = S.PP.getIdentifierInfo("value");
1069   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1070 
1071   // Form template argument list for tuple_size<T>.
1072   TemplateArgumentListInfo Args(Loc, Loc);
1073   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1074 
1075   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1076   // it's not tuple-like.
1077   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1078       R.empty())
1079     return IsTupleLike::NotTupleLike;
1080 
1081   // If we get this far, we've committed to the tuple interpretation, but
1082   // we can still fail if there actually isn't a usable ::value.
1083 
1084   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1085     LookupResult &R;
1086     TemplateArgumentListInfo &Args;
1087     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1088         : R(R), Args(Args) {}
1089     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1090                                                SourceLocation Loc) override {
1091       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1092           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1093     }
1094   } Diagnoser(R, Args);
1095 
1096   ExprResult E =
1097       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1098   if (E.isInvalid())
1099     return IsTupleLike::Error;
1100 
1101   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1102   if (E.isInvalid())
1103     return IsTupleLike::Error;
1104 
1105   return IsTupleLike::TupleLike;
1106 }
1107 
1108 /// \return std::tuple_element<I, T>::type.
1109 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1110                                         unsigned I, QualType T) {
1111   // Form template argument list for tuple_element<I, T>.
1112   TemplateArgumentListInfo Args(Loc, Loc);
1113   Args.addArgument(
1114       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1115   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1116 
1117   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1118   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1119   if (lookupStdTypeTraitMember(
1120           S, R, Loc, "tuple_element", Args,
1121           diag::err_decomp_decl_std_tuple_element_not_specialized))
1122     return QualType();
1123 
1124   auto *TD = R.getAsSingle<TypeDecl>();
1125   if (!TD) {
1126     R.suppressDiagnostics();
1127     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1128       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1129     if (!R.empty())
1130       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1131     return QualType();
1132   }
1133 
1134   return S.Context.getTypeDeclType(TD);
1135 }
1136 
1137 namespace {
1138 struct InitializingBinding {
1139   Sema &S;
1140   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1141     Sema::CodeSynthesisContext Ctx;
1142     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1143     Ctx.PointOfInstantiation = BD->getLocation();
1144     Ctx.Entity = BD;
1145     S.pushCodeSynthesisContext(Ctx);
1146   }
1147   ~InitializingBinding() {
1148     S.popCodeSynthesisContext();
1149   }
1150 };
1151 }
1152 
1153 static bool checkTupleLikeDecomposition(Sema &S,
1154                                         ArrayRef<BindingDecl *> Bindings,
1155                                         VarDecl *Src, QualType DecompType,
1156                                         const llvm::APSInt &TupleSize) {
1157   if ((int64_t)Bindings.size() != TupleSize) {
1158     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1159         << DecompType << (unsigned)Bindings.size()
1160         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1161         << TupleSize.toString(10) << (TupleSize < Bindings.size());
1162     return true;
1163   }
1164 
1165   if (Bindings.empty())
1166     return false;
1167 
1168   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1169 
1170   // [dcl.decomp]p3:
1171   //   The unqualified-id get is looked up in the scope of E by class member
1172   //   access lookup ...
1173   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1174   bool UseMemberGet = false;
1175   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1176     if (auto *RD = DecompType->getAsCXXRecordDecl())
1177       S.LookupQualifiedName(MemberGet, RD);
1178     if (MemberGet.isAmbiguous())
1179       return true;
1180     //   ... and if that finds at least one declaration that is a function
1181     //   template whose first template parameter is a non-type parameter ...
1182     for (NamedDecl *D : MemberGet) {
1183       if (FunctionTemplateDecl *FTD =
1184               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1185         TemplateParameterList *TPL = FTD->getTemplateParameters();
1186         if (TPL->size() != 0 &&
1187             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1188           //   ... the initializer is e.get<i>().
1189           UseMemberGet = true;
1190           break;
1191         }
1192       }
1193     }
1194   }
1195 
1196   unsigned I = 0;
1197   for (auto *B : Bindings) {
1198     InitializingBinding InitContext(S, B);
1199     SourceLocation Loc = B->getLocation();
1200 
1201     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1202     if (E.isInvalid())
1203       return true;
1204 
1205     //   e is an lvalue if the type of the entity is an lvalue reference and
1206     //   an xvalue otherwise
1207     if (!Src->getType()->isLValueReferenceType())
1208       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1209                                    E.get(), nullptr, VK_XValue,
1210                                    FPOptionsOverride());
1211 
1212     TemplateArgumentListInfo Args(Loc, Loc);
1213     Args.addArgument(
1214         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1215 
1216     if (UseMemberGet) {
1217       //   if [lookup of member get] finds at least one declaration, the
1218       //   initializer is e.get<i-1>().
1219       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1220                                      CXXScopeSpec(), SourceLocation(), nullptr,
1221                                      MemberGet, &Args, nullptr);
1222       if (E.isInvalid())
1223         return true;
1224 
1225       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1226     } else {
1227       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1228       //   in the associated namespaces.
1229       Expr *Get = UnresolvedLookupExpr::Create(
1230           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1231           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1232           UnresolvedSetIterator(), UnresolvedSetIterator());
1233 
1234       Expr *Arg = E.get();
1235       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1236     }
1237     if (E.isInvalid())
1238       return true;
1239     Expr *Init = E.get();
1240 
1241     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1242     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1243     if (T.isNull())
1244       return true;
1245 
1246     //   each vi is a variable of type "reference to T" initialized with the
1247     //   initializer, where the reference is an lvalue reference if the
1248     //   initializer is an lvalue and an rvalue reference otherwise
1249     QualType RefType =
1250         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1251     if (RefType.isNull())
1252       return true;
1253     auto *RefVD = VarDecl::Create(
1254         S.Context, Src->getDeclContext(), Loc, Loc,
1255         B->getDeclName().getAsIdentifierInfo(), RefType,
1256         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1257     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1258     RefVD->setTSCSpec(Src->getTSCSpec());
1259     RefVD->setImplicit();
1260     if (Src->isInlineSpecified())
1261       RefVD->setInlineSpecified();
1262     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1263 
1264     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1265     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1266     InitializationSequence Seq(S, Entity, Kind, Init);
1267     E = Seq.Perform(S, Entity, Kind, Init);
1268     if (E.isInvalid())
1269       return true;
1270     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1271     if (E.isInvalid())
1272       return true;
1273     RefVD->setInit(E.get());
1274     S.CheckCompleteVariableDeclaration(RefVD);
1275 
1276     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1277                                    DeclarationNameInfo(B->getDeclName(), Loc),
1278                                    RefVD);
1279     if (E.isInvalid())
1280       return true;
1281 
1282     B->setBinding(T, E.get());
1283     I++;
1284   }
1285 
1286   return false;
1287 }
1288 
1289 /// Find the base class to decompose in a built-in decomposition of a class type.
1290 /// This base class search is, unfortunately, not quite like any other that we
1291 /// perform anywhere else in C++.
1292 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1293                                                 const CXXRecordDecl *RD,
1294                                                 CXXCastPath &BasePath) {
1295   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1296                           CXXBasePath &Path) {
1297     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1298   };
1299 
1300   const CXXRecordDecl *ClassWithFields = nullptr;
1301   AccessSpecifier AS = AS_public;
1302   if (RD->hasDirectFields())
1303     // [dcl.decomp]p4:
1304     //   Otherwise, all of E's non-static data members shall be public direct
1305     //   members of E ...
1306     ClassWithFields = RD;
1307   else {
1308     //   ... or of ...
1309     CXXBasePaths Paths;
1310     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1311     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1312       // If no classes have fields, just decompose RD itself. (This will work
1313       // if and only if zero bindings were provided.)
1314       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1315     }
1316 
1317     CXXBasePath *BestPath = nullptr;
1318     for (auto &P : Paths) {
1319       if (!BestPath)
1320         BestPath = &P;
1321       else if (!S.Context.hasSameType(P.back().Base->getType(),
1322                                       BestPath->back().Base->getType())) {
1323         //   ... the same ...
1324         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1325           << false << RD << BestPath->back().Base->getType()
1326           << P.back().Base->getType();
1327         return DeclAccessPair();
1328       } else if (P.Access < BestPath->Access) {
1329         BestPath = &P;
1330       }
1331     }
1332 
1333     //   ... unambiguous ...
1334     QualType BaseType = BestPath->back().Base->getType();
1335     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1336       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1337         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1338       return DeclAccessPair();
1339     }
1340 
1341     //   ... [accessible, implied by other rules] base class of E.
1342     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1343                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1344     AS = BestPath->Access;
1345 
1346     ClassWithFields = BaseType->getAsCXXRecordDecl();
1347     S.BuildBasePathArray(Paths, BasePath);
1348   }
1349 
1350   // The above search did not check whether the selected class itself has base
1351   // classes with fields, so check that now.
1352   CXXBasePaths Paths;
1353   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1354     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1355       << (ClassWithFields == RD) << RD << ClassWithFields
1356       << Paths.front().back().Base->getType();
1357     return DeclAccessPair();
1358   }
1359 
1360   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1361 }
1362 
1363 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1364                                      ValueDecl *Src, QualType DecompType,
1365                                      const CXXRecordDecl *OrigRD) {
1366   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1367                             diag::err_incomplete_type))
1368     return true;
1369 
1370   CXXCastPath BasePath;
1371   DeclAccessPair BasePair =
1372       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1373   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1374   if (!RD)
1375     return true;
1376   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1377                                                  DecompType.getQualifiers());
1378 
1379   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1380     unsigned NumFields =
1381         std::count_if(RD->field_begin(), RD->field_end(),
1382                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1383     assert(Bindings.size() != NumFields);
1384     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1385         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1386         << (NumFields < Bindings.size());
1387     return true;
1388   };
1389 
1390   //   all of E's non-static data members shall be [...] well-formed
1391   //   when named as e.name in the context of the structured binding,
1392   //   E shall not have an anonymous union member, ...
1393   unsigned I = 0;
1394   for (auto *FD : RD->fields()) {
1395     if (FD->isUnnamedBitfield())
1396       continue;
1397 
1398     // All the non-static data members are required to be nameable, so they
1399     // must all have names.
1400     if (!FD->getDeclName()) {
1401       if (RD->isLambda()) {
1402         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1403         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1404         return true;
1405       }
1406 
1407       if (FD->isAnonymousStructOrUnion()) {
1408         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1409           << DecompType << FD->getType()->isUnionType();
1410         S.Diag(FD->getLocation(), diag::note_declared_at);
1411         return true;
1412       }
1413 
1414       // FIXME: Are there any other ways we could have an anonymous member?
1415     }
1416 
1417     // We have a real field to bind.
1418     if (I >= Bindings.size())
1419       return DiagnoseBadNumberOfBindings();
1420     auto *B = Bindings[I++];
1421     SourceLocation Loc = B->getLocation();
1422 
1423     // The field must be accessible in the context of the structured binding.
1424     // We already checked that the base class is accessible.
1425     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1426     // const_cast here.
1427     S.CheckStructuredBindingMemberAccess(
1428         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1429         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1430                                      BasePair.getAccess(), FD->getAccess())));
1431 
1432     // Initialize the binding to Src.FD.
1433     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1434     if (E.isInvalid())
1435       return true;
1436     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1437                             VK_LValue, &BasePath);
1438     if (E.isInvalid())
1439       return true;
1440     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1441                                   CXXScopeSpec(), FD,
1442                                   DeclAccessPair::make(FD, FD->getAccess()),
1443                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1444     if (E.isInvalid())
1445       return true;
1446 
1447     // If the type of the member is T, the referenced type is cv T, where cv is
1448     // the cv-qualification of the decomposition expression.
1449     //
1450     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1451     // 'const' to the type of the field.
1452     Qualifiers Q = DecompType.getQualifiers();
1453     if (FD->isMutable())
1454       Q.removeConst();
1455     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1456   }
1457 
1458   if (I != Bindings.size())
1459     return DiagnoseBadNumberOfBindings();
1460 
1461   return false;
1462 }
1463 
1464 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1465   QualType DecompType = DD->getType();
1466 
1467   // If the type of the decomposition is dependent, then so is the type of
1468   // each binding.
1469   if (DecompType->isDependentType()) {
1470     for (auto *B : DD->bindings())
1471       B->setType(Context.DependentTy);
1472     return;
1473   }
1474 
1475   DecompType = DecompType.getNonReferenceType();
1476   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1477 
1478   // C++1z [dcl.decomp]/2:
1479   //   If E is an array type [...]
1480   // As an extension, we also support decomposition of built-in complex and
1481   // vector types.
1482   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1483     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1484       DD->setInvalidDecl();
1485     return;
1486   }
1487   if (auto *VT = DecompType->getAs<VectorType>()) {
1488     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1489       DD->setInvalidDecl();
1490     return;
1491   }
1492   if (auto *CT = DecompType->getAs<ComplexType>()) {
1493     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1494       DD->setInvalidDecl();
1495     return;
1496   }
1497 
1498   // C++1z [dcl.decomp]/3:
1499   //   if the expression std::tuple_size<E>::value is a well-formed integral
1500   //   constant expression, [...]
1501   llvm::APSInt TupleSize(32);
1502   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1503   case IsTupleLike::Error:
1504     DD->setInvalidDecl();
1505     return;
1506 
1507   case IsTupleLike::TupleLike:
1508     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1509       DD->setInvalidDecl();
1510     return;
1511 
1512   case IsTupleLike::NotTupleLike:
1513     break;
1514   }
1515 
1516   // C++1z [dcl.dcl]/8:
1517   //   [E shall be of array or non-union class type]
1518   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1519   if (!RD || RD->isUnion()) {
1520     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1521         << DD << !RD << DecompType;
1522     DD->setInvalidDecl();
1523     return;
1524   }
1525 
1526   // C++1z [dcl.decomp]/4:
1527   //   all of E's non-static data members shall be [...] direct members of
1528   //   E or of the same unambiguous public base class of E, ...
1529   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1530     DD->setInvalidDecl();
1531 }
1532 
1533 /// Merge the exception specifications of two variable declarations.
1534 ///
1535 /// This is called when there's a redeclaration of a VarDecl. The function
1536 /// checks if the redeclaration might have an exception specification and
1537 /// validates compatibility and merges the specs if necessary.
1538 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1539   // Shortcut if exceptions are disabled.
1540   if (!getLangOpts().CXXExceptions)
1541     return;
1542 
1543   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1544          "Should only be called if types are otherwise the same.");
1545 
1546   QualType NewType = New->getType();
1547   QualType OldType = Old->getType();
1548 
1549   // We're only interested in pointers and references to functions, as well
1550   // as pointers to member functions.
1551   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1552     NewType = R->getPointeeType();
1553     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1554   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1555     NewType = P->getPointeeType();
1556     OldType = OldType->castAs<PointerType>()->getPointeeType();
1557   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1558     NewType = M->getPointeeType();
1559     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1560   }
1561 
1562   if (!NewType->isFunctionProtoType())
1563     return;
1564 
1565   // There's lots of special cases for functions. For function pointers, system
1566   // libraries are hopefully not as broken so that we don't need these
1567   // workarounds.
1568   if (CheckEquivalentExceptionSpec(
1569         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1570         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1571     New->setInvalidDecl();
1572   }
1573 }
1574 
1575 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1576 /// function declaration are well-formed according to C++
1577 /// [dcl.fct.default].
1578 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1579   unsigned NumParams = FD->getNumParams();
1580   unsigned ParamIdx = 0;
1581 
1582   // This checking doesn't make sense for explicit specializations; their
1583   // default arguments are determined by the declaration we're specializing,
1584   // not by FD.
1585   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1586     return;
1587   if (auto *FTD = FD->getDescribedFunctionTemplate())
1588     if (FTD->isMemberSpecialization())
1589       return;
1590 
1591   // Find first parameter with a default argument
1592   for (; ParamIdx < NumParams; ++ParamIdx) {
1593     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1594     if (Param->hasDefaultArg())
1595       break;
1596   }
1597 
1598   // C++20 [dcl.fct.default]p4:
1599   //   In a given function declaration, each parameter subsequent to a parameter
1600   //   with a default argument shall have a default argument supplied in this or
1601   //   a previous declaration, unless the parameter was expanded from a
1602   //   parameter pack, or shall be a function parameter pack.
1603   for (; ParamIdx < NumParams; ++ParamIdx) {
1604     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1605     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1606         !(CurrentInstantiationScope &&
1607           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1608       if (Param->isInvalidDecl())
1609         /* We already complained about this parameter. */;
1610       else if (Param->getIdentifier())
1611         Diag(Param->getLocation(),
1612              diag::err_param_default_argument_missing_name)
1613           << Param->getIdentifier();
1614       else
1615         Diag(Param->getLocation(),
1616              diag::err_param_default_argument_missing);
1617     }
1618   }
1619 }
1620 
1621 /// Check that the given type is a literal type. Issue a diagnostic if not,
1622 /// if Kind is Diagnose.
1623 /// \return \c true if a problem has been found (and optionally diagnosed).
1624 template <typename... Ts>
1625 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1626                              SourceLocation Loc, QualType T, unsigned DiagID,
1627                              Ts &&...DiagArgs) {
1628   if (T->isDependentType())
1629     return false;
1630 
1631   switch (Kind) {
1632   case Sema::CheckConstexprKind::Diagnose:
1633     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1634                                       std::forward<Ts>(DiagArgs)...);
1635 
1636   case Sema::CheckConstexprKind::CheckValid:
1637     return !T->isLiteralType(SemaRef.Context);
1638   }
1639 
1640   llvm_unreachable("unknown CheckConstexprKind");
1641 }
1642 
1643 /// Determine whether a destructor cannot be constexpr due to
1644 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1645                                                const CXXDestructorDecl *DD,
1646                                                Sema::CheckConstexprKind Kind) {
1647   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1648     const CXXRecordDecl *RD =
1649         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1650     if (!RD || RD->hasConstexprDestructor())
1651       return true;
1652 
1653     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1654       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1655           << static_cast<int>(DD->getConstexprKind()) << !FD
1656           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1657       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1658           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1659     }
1660     return false;
1661   };
1662 
1663   const CXXRecordDecl *RD = DD->getParent();
1664   for (const CXXBaseSpecifier &B : RD->bases())
1665     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1666       return false;
1667   for (const FieldDecl *FD : RD->fields())
1668     if (!Check(FD->getLocation(), FD->getType(), FD))
1669       return false;
1670   return true;
1671 }
1672 
1673 /// Check whether a function's parameter types are all literal types. If so,
1674 /// return true. If not, produce a suitable diagnostic and return false.
1675 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1676                                          const FunctionDecl *FD,
1677                                          Sema::CheckConstexprKind Kind) {
1678   unsigned ArgIndex = 0;
1679   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1680   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1681                                               e = FT->param_type_end();
1682        i != e; ++i, ++ArgIndex) {
1683     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1684     SourceLocation ParamLoc = PD->getLocation();
1685     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1686                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1687                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1688                          FD->isConsteval()))
1689       return false;
1690   }
1691   return true;
1692 }
1693 
1694 /// Check whether a function's return type is a literal type. If so, return
1695 /// true. If not, produce a suitable diagnostic and return false.
1696 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1697                                      Sema::CheckConstexprKind Kind) {
1698   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1699                        diag::err_constexpr_non_literal_return,
1700                        FD->isConsteval()))
1701     return false;
1702   return true;
1703 }
1704 
1705 /// Get diagnostic %select index for tag kind for
1706 /// record diagnostic message.
1707 /// WARNING: Indexes apply to particular diagnostics only!
1708 ///
1709 /// \returns diagnostic %select index.
1710 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1711   switch (Tag) {
1712   case TTK_Struct: return 0;
1713   case TTK_Interface: return 1;
1714   case TTK_Class:  return 2;
1715   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1716   }
1717 }
1718 
1719 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1720                                        Stmt *Body,
1721                                        Sema::CheckConstexprKind Kind);
1722 
1723 // Check whether a function declaration satisfies the requirements of a
1724 // constexpr function definition or a constexpr constructor definition. If so,
1725 // return true. If not, produce appropriate diagnostics (unless asked not to by
1726 // Kind) and return false.
1727 //
1728 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1729 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1730                                             CheckConstexprKind Kind) {
1731   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1732   if (MD && MD->isInstance()) {
1733     // C++11 [dcl.constexpr]p4:
1734     //  The definition of a constexpr constructor shall satisfy the following
1735     //  constraints:
1736     //  - the class shall not have any virtual base classes;
1737     //
1738     // FIXME: This only applies to constructors and destructors, not arbitrary
1739     // member functions.
1740     const CXXRecordDecl *RD = MD->getParent();
1741     if (RD->getNumVBases()) {
1742       if (Kind == CheckConstexprKind::CheckValid)
1743         return false;
1744 
1745       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1746         << isa<CXXConstructorDecl>(NewFD)
1747         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1748       for (const auto &I : RD->vbases())
1749         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1750             << I.getSourceRange();
1751       return false;
1752     }
1753   }
1754 
1755   if (!isa<CXXConstructorDecl>(NewFD)) {
1756     // C++11 [dcl.constexpr]p3:
1757     //  The definition of a constexpr function shall satisfy the following
1758     //  constraints:
1759     // - it shall not be virtual; (removed in C++20)
1760     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1761     if (Method && Method->isVirtual()) {
1762       if (getLangOpts().CPlusPlus20) {
1763         if (Kind == CheckConstexprKind::Diagnose)
1764           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1765       } else {
1766         if (Kind == CheckConstexprKind::CheckValid)
1767           return false;
1768 
1769         Method = Method->getCanonicalDecl();
1770         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1771 
1772         // If it's not obvious why this function is virtual, find an overridden
1773         // function which uses the 'virtual' keyword.
1774         const CXXMethodDecl *WrittenVirtual = Method;
1775         while (!WrittenVirtual->isVirtualAsWritten())
1776           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1777         if (WrittenVirtual != Method)
1778           Diag(WrittenVirtual->getLocation(),
1779                diag::note_overridden_virtual_function);
1780         return false;
1781       }
1782     }
1783 
1784     // - its return type shall be a literal type;
1785     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1786       return false;
1787   }
1788 
1789   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1790     // A destructor can be constexpr only if the defaulted destructor could be;
1791     // we don't need to check the members and bases if we already know they all
1792     // have constexpr destructors.
1793     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1794       if (Kind == CheckConstexprKind::CheckValid)
1795         return false;
1796       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1797         return false;
1798     }
1799   }
1800 
1801   // - each of its parameter types shall be a literal type;
1802   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1803     return false;
1804 
1805   Stmt *Body = NewFD->getBody();
1806   assert(Body &&
1807          "CheckConstexprFunctionDefinition called on function with no body");
1808   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1809 }
1810 
1811 /// Check the given declaration statement is legal within a constexpr function
1812 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1813 ///
1814 /// \return true if the body is OK (maybe only as an extension), false if we
1815 ///         have diagnosed a problem.
1816 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1817                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1818                                    Sema::CheckConstexprKind Kind) {
1819   // C++11 [dcl.constexpr]p3 and p4:
1820   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1821   //  contain only
1822   for (const auto *DclIt : DS->decls()) {
1823     switch (DclIt->getKind()) {
1824     case Decl::StaticAssert:
1825     case Decl::Using:
1826     case Decl::UsingShadow:
1827     case Decl::UsingDirective:
1828     case Decl::UnresolvedUsingTypename:
1829     case Decl::UnresolvedUsingValue:
1830       //   - static_assert-declarations
1831       //   - using-declarations,
1832       //   - using-directives,
1833       continue;
1834 
1835     case Decl::Typedef:
1836     case Decl::TypeAlias: {
1837       //   - typedef declarations and alias-declarations that do not define
1838       //     classes or enumerations,
1839       const auto *TN = cast<TypedefNameDecl>(DclIt);
1840       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1841         // Don't allow variably-modified types in constexpr functions.
1842         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1843           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1844           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1845             << TL.getSourceRange() << TL.getType()
1846             << isa<CXXConstructorDecl>(Dcl);
1847         }
1848         return false;
1849       }
1850       continue;
1851     }
1852 
1853     case Decl::Enum:
1854     case Decl::CXXRecord:
1855       // C++1y allows types to be defined, not just declared.
1856       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1857         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1858           SemaRef.Diag(DS->getBeginLoc(),
1859                        SemaRef.getLangOpts().CPlusPlus14
1860                            ? diag::warn_cxx11_compat_constexpr_type_definition
1861                            : diag::ext_constexpr_type_definition)
1862               << isa<CXXConstructorDecl>(Dcl);
1863         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1864           return false;
1865         }
1866       }
1867       continue;
1868 
1869     case Decl::EnumConstant:
1870     case Decl::IndirectField:
1871     case Decl::ParmVar:
1872       // These can only appear with other declarations which are banned in
1873       // C++11 and permitted in C++1y, so ignore them.
1874       continue;
1875 
1876     case Decl::Var:
1877     case Decl::Decomposition: {
1878       // C++1y [dcl.constexpr]p3 allows anything except:
1879       //   a definition of a variable of non-literal type or of static or
1880       //   thread storage duration or [before C++2a] for which no
1881       //   initialization is performed.
1882       const auto *VD = cast<VarDecl>(DclIt);
1883       if (VD->isThisDeclarationADefinition()) {
1884         if (VD->isStaticLocal()) {
1885           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1886             SemaRef.Diag(VD->getLocation(),
1887                          diag::err_constexpr_local_var_static)
1888               << isa<CXXConstructorDecl>(Dcl)
1889               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1890           }
1891           return false;
1892         }
1893         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1894                              diag::err_constexpr_local_var_non_literal_type,
1895                              isa<CXXConstructorDecl>(Dcl)))
1896           return false;
1897         if (!VD->getType()->isDependentType() &&
1898             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1899           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900             SemaRef.Diag(
1901                 VD->getLocation(),
1902                 SemaRef.getLangOpts().CPlusPlus20
1903                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1904                     : diag::ext_constexpr_local_var_no_init)
1905                 << isa<CXXConstructorDecl>(Dcl);
1906           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1907             return false;
1908           }
1909           continue;
1910         }
1911       }
1912       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1913         SemaRef.Diag(VD->getLocation(),
1914                      SemaRef.getLangOpts().CPlusPlus14
1915                       ? diag::warn_cxx11_compat_constexpr_local_var
1916                       : diag::ext_constexpr_local_var)
1917           << isa<CXXConstructorDecl>(Dcl);
1918       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1919         return false;
1920       }
1921       continue;
1922     }
1923 
1924     case Decl::NamespaceAlias:
1925     case Decl::Function:
1926       // These are disallowed in C++11 and permitted in C++1y. Allow them
1927       // everywhere as an extension.
1928       if (!Cxx1yLoc.isValid())
1929         Cxx1yLoc = DS->getBeginLoc();
1930       continue;
1931 
1932     default:
1933       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1934         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1935             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1936       }
1937       return false;
1938     }
1939   }
1940 
1941   return true;
1942 }
1943 
1944 /// Check that the given field is initialized within a constexpr constructor.
1945 ///
1946 /// \param Dcl The constexpr constructor being checked.
1947 /// \param Field The field being checked. This may be a member of an anonymous
1948 ///        struct or union nested within the class being checked.
1949 /// \param Inits All declarations, including anonymous struct/union members and
1950 ///        indirect members, for which any initialization was provided.
1951 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1952 ///        multiple notes for different members to the same error.
1953 /// \param Kind Whether we're diagnosing a constructor as written or determining
1954 ///        whether the formal requirements are satisfied.
1955 /// \return \c false if we're checking for validity and the constructor does
1956 ///         not satisfy the requirements on a constexpr constructor.
1957 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1958                                           const FunctionDecl *Dcl,
1959                                           FieldDecl *Field,
1960                                           llvm::SmallSet<Decl*, 16> &Inits,
1961                                           bool &Diagnosed,
1962                                           Sema::CheckConstexprKind Kind) {
1963   // In C++20 onwards, there's nothing to check for validity.
1964   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1965       SemaRef.getLangOpts().CPlusPlus20)
1966     return true;
1967 
1968   if (Field->isInvalidDecl())
1969     return true;
1970 
1971   if (Field->isUnnamedBitfield())
1972     return true;
1973 
1974   // Anonymous unions with no variant members and empty anonymous structs do not
1975   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1976   // indirect fields don't need initializing.
1977   if (Field->isAnonymousStructOrUnion() &&
1978       (Field->getType()->isUnionType()
1979            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1980            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1981     return true;
1982 
1983   if (!Inits.count(Field)) {
1984     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1985       if (!Diagnosed) {
1986         SemaRef.Diag(Dcl->getLocation(),
1987                      SemaRef.getLangOpts().CPlusPlus20
1988                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1989                          : diag::ext_constexpr_ctor_missing_init);
1990         Diagnosed = true;
1991       }
1992       SemaRef.Diag(Field->getLocation(),
1993                    diag::note_constexpr_ctor_missing_init);
1994     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1995       return false;
1996     }
1997   } else if (Field->isAnonymousStructOrUnion()) {
1998     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1999     for (auto *I : RD->fields())
2000       // If an anonymous union contains an anonymous struct of which any member
2001       // is initialized, all members must be initialized.
2002       if (!RD->isUnion() || Inits.count(I))
2003         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2004                                            Kind))
2005           return false;
2006   }
2007   return true;
2008 }
2009 
2010 /// Check the provided statement is allowed in a constexpr function
2011 /// definition.
2012 static bool
2013 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2014                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2015                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2016                            Sema::CheckConstexprKind Kind) {
2017   // - its function-body shall be [...] a compound-statement that contains only
2018   switch (S->getStmtClass()) {
2019   case Stmt::NullStmtClass:
2020     //   - null statements,
2021     return true;
2022 
2023   case Stmt::DeclStmtClass:
2024     //   - static_assert-declarations
2025     //   - using-declarations,
2026     //   - using-directives,
2027     //   - typedef declarations and alias-declarations that do not define
2028     //     classes or enumerations,
2029     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2030       return false;
2031     return true;
2032 
2033   case Stmt::ReturnStmtClass:
2034     //   - and exactly one return statement;
2035     if (isa<CXXConstructorDecl>(Dcl)) {
2036       // C++1y allows return statements in constexpr constructors.
2037       if (!Cxx1yLoc.isValid())
2038         Cxx1yLoc = S->getBeginLoc();
2039       return true;
2040     }
2041 
2042     ReturnStmts.push_back(S->getBeginLoc());
2043     return true;
2044 
2045   case Stmt::CompoundStmtClass: {
2046     // C++1y allows compound-statements.
2047     if (!Cxx1yLoc.isValid())
2048       Cxx1yLoc = S->getBeginLoc();
2049 
2050     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2051     for (auto *BodyIt : CompStmt->body()) {
2052       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2053                                       Cxx1yLoc, Cxx2aLoc, Kind))
2054         return false;
2055     }
2056     return true;
2057   }
2058 
2059   case Stmt::AttributedStmtClass:
2060     if (!Cxx1yLoc.isValid())
2061       Cxx1yLoc = S->getBeginLoc();
2062     return true;
2063 
2064   case Stmt::IfStmtClass: {
2065     // C++1y allows if-statements.
2066     if (!Cxx1yLoc.isValid())
2067       Cxx1yLoc = S->getBeginLoc();
2068 
2069     IfStmt *If = cast<IfStmt>(S);
2070     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2071                                     Cxx1yLoc, Cxx2aLoc, Kind))
2072       return false;
2073     if (If->getElse() &&
2074         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2075                                     Cxx1yLoc, Cxx2aLoc, Kind))
2076       return false;
2077     return true;
2078   }
2079 
2080   case Stmt::WhileStmtClass:
2081   case Stmt::DoStmtClass:
2082   case Stmt::ForStmtClass:
2083   case Stmt::CXXForRangeStmtClass:
2084   case Stmt::ContinueStmtClass:
2085     // C++1y allows all of these. We don't allow them as extensions in C++11,
2086     // because they don't make sense without variable mutation.
2087     if (!SemaRef.getLangOpts().CPlusPlus14)
2088       break;
2089     if (!Cxx1yLoc.isValid())
2090       Cxx1yLoc = S->getBeginLoc();
2091     for (Stmt *SubStmt : S->children())
2092       if (SubStmt &&
2093           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2094                                       Cxx1yLoc, Cxx2aLoc, Kind))
2095         return false;
2096     return true;
2097 
2098   case Stmt::SwitchStmtClass:
2099   case Stmt::CaseStmtClass:
2100   case Stmt::DefaultStmtClass:
2101   case Stmt::BreakStmtClass:
2102     // C++1y allows switch-statements, and since they don't need variable
2103     // mutation, we can reasonably allow them in C++11 as an extension.
2104     if (!Cxx1yLoc.isValid())
2105       Cxx1yLoc = S->getBeginLoc();
2106     for (Stmt *SubStmt : S->children())
2107       if (SubStmt &&
2108           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2109                                       Cxx1yLoc, Cxx2aLoc, Kind))
2110         return false;
2111     return true;
2112 
2113   case Stmt::GCCAsmStmtClass:
2114   case Stmt::MSAsmStmtClass:
2115     // C++2a allows inline assembly statements.
2116   case Stmt::CXXTryStmtClass:
2117     if (Cxx2aLoc.isInvalid())
2118       Cxx2aLoc = S->getBeginLoc();
2119     for (Stmt *SubStmt : S->children()) {
2120       if (SubStmt &&
2121           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2122                                       Cxx1yLoc, Cxx2aLoc, Kind))
2123         return false;
2124     }
2125     return true;
2126 
2127   case Stmt::CXXCatchStmtClass:
2128     // Do not bother checking the language mode (already covered by the
2129     // try block check).
2130     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2131                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2132                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2133       return false;
2134     return true;
2135 
2136   default:
2137     if (!isa<Expr>(S))
2138       break;
2139 
2140     // C++1y allows expression-statements.
2141     if (!Cxx1yLoc.isValid())
2142       Cxx1yLoc = S->getBeginLoc();
2143     return true;
2144   }
2145 
2146   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2147     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2148         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2149   }
2150   return false;
2151 }
2152 
2153 /// Check the body for the given constexpr function declaration only contains
2154 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2155 ///
2156 /// \return true if the body is OK, false if we have found or diagnosed a
2157 /// problem.
2158 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2159                                        Stmt *Body,
2160                                        Sema::CheckConstexprKind Kind) {
2161   SmallVector<SourceLocation, 4> ReturnStmts;
2162 
2163   if (isa<CXXTryStmt>(Body)) {
2164     // C++11 [dcl.constexpr]p3:
2165     //  The definition of a constexpr function shall satisfy the following
2166     //  constraints: [...]
2167     // - its function-body shall be = delete, = default, or a
2168     //   compound-statement
2169     //
2170     // C++11 [dcl.constexpr]p4:
2171     //  In the definition of a constexpr constructor, [...]
2172     // - its function-body shall not be a function-try-block;
2173     //
2174     // This restriction is lifted in C++2a, as long as inner statements also
2175     // apply the general constexpr rules.
2176     switch (Kind) {
2177     case Sema::CheckConstexprKind::CheckValid:
2178       if (!SemaRef.getLangOpts().CPlusPlus20)
2179         return false;
2180       break;
2181 
2182     case Sema::CheckConstexprKind::Diagnose:
2183       SemaRef.Diag(Body->getBeginLoc(),
2184            !SemaRef.getLangOpts().CPlusPlus20
2185                ? diag::ext_constexpr_function_try_block_cxx20
2186                : diag::warn_cxx17_compat_constexpr_function_try_block)
2187           << isa<CXXConstructorDecl>(Dcl);
2188       break;
2189     }
2190   }
2191 
2192   // - its function-body shall be [...] a compound-statement that contains only
2193   //   [... list of cases ...]
2194   //
2195   // Note that walking the children here is enough to properly check for
2196   // CompoundStmt and CXXTryStmt body.
2197   SourceLocation Cxx1yLoc, Cxx2aLoc;
2198   for (Stmt *SubStmt : Body->children()) {
2199     if (SubStmt &&
2200         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2201                                     Cxx1yLoc, Cxx2aLoc, Kind))
2202       return false;
2203   }
2204 
2205   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2206     // If this is only valid as an extension, report that we don't satisfy the
2207     // constraints of the current language.
2208     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2209         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2210       return false;
2211   } else if (Cxx2aLoc.isValid()) {
2212     SemaRef.Diag(Cxx2aLoc,
2213          SemaRef.getLangOpts().CPlusPlus20
2214            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2215            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2216       << isa<CXXConstructorDecl>(Dcl);
2217   } else if (Cxx1yLoc.isValid()) {
2218     SemaRef.Diag(Cxx1yLoc,
2219          SemaRef.getLangOpts().CPlusPlus14
2220            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2221            : diag::ext_constexpr_body_invalid_stmt)
2222       << isa<CXXConstructorDecl>(Dcl);
2223   }
2224 
2225   if (const CXXConstructorDecl *Constructor
2226         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2227     const CXXRecordDecl *RD = Constructor->getParent();
2228     // DR1359:
2229     // - every non-variant non-static data member and base class sub-object
2230     //   shall be initialized;
2231     // DR1460:
2232     // - if the class is a union having variant members, exactly one of them
2233     //   shall be initialized;
2234     if (RD->isUnion()) {
2235       if (Constructor->getNumCtorInitializers() == 0 &&
2236           RD->hasVariantMembers()) {
2237         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2238           SemaRef.Diag(
2239               Dcl->getLocation(),
2240               SemaRef.getLangOpts().CPlusPlus20
2241                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2242                   : diag::ext_constexpr_union_ctor_no_init);
2243         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2244           return false;
2245         }
2246       }
2247     } else if (!Constructor->isDependentContext() &&
2248                !Constructor->isDelegatingConstructor()) {
2249       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2250 
2251       // Skip detailed checking if we have enough initializers, and we would
2252       // allow at most one initializer per member.
2253       bool AnyAnonStructUnionMembers = false;
2254       unsigned Fields = 0;
2255       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2256            E = RD->field_end(); I != E; ++I, ++Fields) {
2257         if (I->isAnonymousStructOrUnion()) {
2258           AnyAnonStructUnionMembers = true;
2259           break;
2260         }
2261       }
2262       // DR1460:
2263       // - if the class is a union-like class, but is not a union, for each of
2264       //   its anonymous union members having variant members, exactly one of
2265       //   them shall be initialized;
2266       if (AnyAnonStructUnionMembers ||
2267           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2268         // Check initialization of non-static data members. Base classes are
2269         // always initialized so do not need to be checked. Dependent bases
2270         // might not have initializers in the member initializer list.
2271         llvm::SmallSet<Decl*, 16> Inits;
2272         for (const auto *I: Constructor->inits()) {
2273           if (FieldDecl *FD = I->getMember())
2274             Inits.insert(FD);
2275           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2276             Inits.insert(ID->chain_begin(), ID->chain_end());
2277         }
2278 
2279         bool Diagnosed = false;
2280         for (auto *I : RD->fields())
2281           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2282                                              Kind))
2283             return false;
2284       }
2285     }
2286   } else {
2287     if (ReturnStmts.empty()) {
2288       // C++1y doesn't require constexpr functions to contain a 'return'
2289       // statement. We still do, unless the return type might be void, because
2290       // otherwise if there's no return statement, the function cannot
2291       // be used in a core constant expression.
2292       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2293                 (Dcl->getReturnType()->isVoidType() ||
2294                  Dcl->getReturnType()->isDependentType());
2295       switch (Kind) {
2296       case Sema::CheckConstexprKind::Diagnose:
2297         SemaRef.Diag(Dcl->getLocation(),
2298                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2299                         : diag::err_constexpr_body_no_return)
2300             << Dcl->isConsteval();
2301         if (!OK)
2302           return false;
2303         break;
2304 
2305       case Sema::CheckConstexprKind::CheckValid:
2306         // The formal requirements don't include this rule in C++14, even
2307         // though the "must be able to produce a constant expression" rules
2308         // still imply it in some cases.
2309         if (!SemaRef.getLangOpts().CPlusPlus14)
2310           return false;
2311         break;
2312       }
2313     } else if (ReturnStmts.size() > 1) {
2314       switch (Kind) {
2315       case Sema::CheckConstexprKind::Diagnose:
2316         SemaRef.Diag(
2317             ReturnStmts.back(),
2318             SemaRef.getLangOpts().CPlusPlus14
2319                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2320                 : diag::ext_constexpr_body_multiple_return);
2321         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2322           SemaRef.Diag(ReturnStmts[I],
2323                        diag::note_constexpr_body_previous_return);
2324         break;
2325 
2326       case Sema::CheckConstexprKind::CheckValid:
2327         if (!SemaRef.getLangOpts().CPlusPlus14)
2328           return false;
2329         break;
2330       }
2331     }
2332   }
2333 
2334   // C++11 [dcl.constexpr]p5:
2335   //   if no function argument values exist such that the function invocation
2336   //   substitution would produce a constant expression, the program is
2337   //   ill-formed; no diagnostic required.
2338   // C++11 [dcl.constexpr]p3:
2339   //   - every constructor call and implicit conversion used in initializing the
2340   //     return value shall be one of those allowed in a constant expression.
2341   // C++11 [dcl.constexpr]p4:
2342   //   - every constructor involved in initializing non-static data members and
2343   //     base class sub-objects shall be a constexpr constructor.
2344   //
2345   // Note that this rule is distinct from the "requirements for a constexpr
2346   // function", so is not checked in CheckValid mode.
2347   SmallVector<PartialDiagnosticAt, 8> Diags;
2348   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2349       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2350     SemaRef.Diag(Dcl->getLocation(),
2351                  diag::ext_constexpr_function_never_constant_expr)
2352         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2353     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2354       SemaRef.Diag(Diags[I].first, Diags[I].second);
2355     // Don't return false here: we allow this for compatibility in
2356     // system headers.
2357   }
2358 
2359   return true;
2360 }
2361 
2362 /// Get the class that is directly named by the current context. This is the
2363 /// class for which an unqualified-id in this scope could name a constructor
2364 /// or destructor.
2365 ///
2366 /// If the scope specifier denotes a class, this will be that class.
2367 /// If the scope specifier is empty, this will be the class whose
2368 /// member-specification we are currently within. Otherwise, there
2369 /// is no such class.
2370 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2371   assert(getLangOpts().CPlusPlus && "No class names in C!");
2372 
2373   if (SS && SS->isInvalid())
2374     return nullptr;
2375 
2376   if (SS && SS->isNotEmpty()) {
2377     DeclContext *DC = computeDeclContext(*SS, true);
2378     return dyn_cast_or_null<CXXRecordDecl>(DC);
2379   }
2380 
2381   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2382 }
2383 
2384 /// isCurrentClassName - Determine whether the identifier II is the
2385 /// name of the class type currently being defined. In the case of
2386 /// nested classes, this will only return true if II is the name of
2387 /// the innermost class.
2388 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2389                               const CXXScopeSpec *SS) {
2390   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2391   return CurDecl && &II == CurDecl->getIdentifier();
2392 }
2393 
2394 /// Determine whether the identifier II is a typo for the name of
2395 /// the class type currently being defined. If so, update it to the identifier
2396 /// that should have been used.
2397 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2398   assert(getLangOpts().CPlusPlus && "No class names in C!");
2399 
2400   if (!getLangOpts().SpellChecking)
2401     return false;
2402 
2403   CXXRecordDecl *CurDecl;
2404   if (SS && SS->isSet() && !SS->isInvalid()) {
2405     DeclContext *DC = computeDeclContext(*SS, true);
2406     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2407   } else
2408     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2409 
2410   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2411       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2412           < II->getLength()) {
2413     II = CurDecl->getIdentifier();
2414     return true;
2415   }
2416 
2417   return false;
2418 }
2419 
2420 /// Determine whether the given class is a base class of the given
2421 /// class, including looking at dependent bases.
2422 static bool findCircularInheritance(const CXXRecordDecl *Class,
2423                                     const CXXRecordDecl *Current) {
2424   SmallVector<const CXXRecordDecl*, 8> Queue;
2425 
2426   Class = Class->getCanonicalDecl();
2427   while (true) {
2428     for (const auto &I : Current->bases()) {
2429       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2430       if (!Base)
2431         continue;
2432 
2433       Base = Base->getDefinition();
2434       if (!Base)
2435         continue;
2436 
2437       if (Base->getCanonicalDecl() == Class)
2438         return true;
2439 
2440       Queue.push_back(Base);
2441     }
2442 
2443     if (Queue.empty())
2444       return false;
2445 
2446     Current = Queue.pop_back_val();
2447   }
2448 
2449   return false;
2450 }
2451 
2452 /// Check the validity of a C++ base class specifier.
2453 ///
2454 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2455 /// and returns NULL otherwise.
2456 CXXBaseSpecifier *
2457 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2458                          SourceRange SpecifierRange,
2459                          bool Virtual, AccessSpecifier Access,
2460                          TypeSourceInfo *TInfo,
2461                          SourceLocation EllipsisLoc) {
2462   QualType BaseType = TInfo->getType();
2463   if (BaseType->containsErrors()) {
2464     // Already emitted a diagnostic when parsing the error type.
2465     return nullptr;
2466   }
2467   // C++ [class.union]p1:
2468   //   A union shall not have base classes.
2469   if (Class->isUnion()) {
2470     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2471       << SpecifierRange;
2472     return nullptr;
2473   }
2474 
2475   if (EllipsisLoc.isValid() &&
2476       !TInfo->getType()->containsUnexpandedParameterPack()) {
2477     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2478       << TInfo->getTypeLoc().getSourceRange();
2479     EllipsisLoc = SourceLocation();
2480   }
2481 
2482   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2483 
2484   if (BaseType->isDependentType()) {
2485     // Make sure that we don't have circular inheritance among our dependent
2486     // bases. For non-dependent bases, the check for completeness below handles
2487     // this.
2488     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2489       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2490           ((BaseDecl = BaseDecl->getDefinition()) &&
2491            findCircularInheritance(Class, BaseDecl))) {
2492         Diag(BaseLoc, diag::err_circular_inheritance)
2493           << BaseType << Context.getTypeDeclType(Class);
2494 
2495         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2496           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2497             << BaseType;
2498 
2499         return nullptr;
2500       }
2501     }
2502 
2503     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2504                                           Class->getTagKind() == TTK_Class,
2505                                           Access, TInfo, EllipsisLoc);
2506   }
2507 
2508   // Base specifiers must be record types.
2509   if (!BaseType->isRecordType()) {
2510     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2511     return nullptr;
2512   }
2513 
2514   // C++ [class.union]p1:
2515   //   A union shall not be used as a base class.
2516   if (BaseType->isUnionType()) {
2517     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2518     return nullptr;
2519   }
2520 
2521   // For the MS ABI, propagate DLL attributes to base class templates.
2522   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2523     if (Attr *ClassAttr = getDLLAttr(Class)) {
2524       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2525               BaseType->getAsCXXRecordDecl())) {
2526         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2527                                             BaseLoc);
2528       }
2529     }
2530   }
2531 
2532   // C++ [class.derived]p2:
2533   //   The class-name in a base-specifier shall not be an incompletely
2534   //   defined class.
2535   if (RequireCompleteType(BaseLoc, BaseType,
2536                           diag::err_incomplete_base_class, SpecifierRange)) {
2537     Class->setInvalidDecl();
2538     return nullptr;
2539   }
2540 
2541   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2542   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2543   assert(BaseDecl && "Record type has no declaration");
2544   BaseDecl = BaseDecl->getDefinition();
2545   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2546   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2547   assert(CXXBaseDecl && "Base type is not a C++ type");
2548 
2549   // Microsoft docs say:
2550   // "If a base-class has a code_seg attribute, derived classes must have the
2551   // same attribute."
2552   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2553   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2554   if ((DerivedCSA || BaseCSA) &&
2555       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2556     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2557     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2558       << CXXBaseDecl;
2559     return nullptr;
2560   }
2561 
2562   // A class which contains a flexible array member is not suitable for use as a
2563   // base class:
2564   //   - If the layout determines that a base comes before another base,
2565   //     the flexible array member would index into the subsequent base.
2566   //   - If the layout determines that base comes before the derived class,
2567   //     the flexible array member would index into the derived class.
2568   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2569     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2570       << CXXBaseDecl->getDeclName();
2571     return nullptr;
2572   }
2573 
2574   // C++ [class]p3:
2575   //   If a class is marked final and it appears as a base-type-specifier in
2576   //   base-clause, the program is ill-formed.
2577   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2578     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2579       << CXXBaseDecl->getDeclName()
2580       << FA->isSpelledAsSealed();
2581     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2582         << CXXBaseDecl->getDeclName() << FA->getRange();
2583     return nullptr;
2584   }
2585 
2586   if (BaseDecl->isInvalidDecl())
2587     Class->setInvalidDecl();
2588 
2589   // Create the base specifier.
2590   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2591                                         Class->getTagKind() == TTK_Class,
2592                                         Access, TInfo, EllipsisLoc);
2593 }
2594 
2595 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2596 /// one entry in the base class list of a class specifier, for
2597 /// example:
2598 ///    class foo : public bar, virtual private baz {
2599 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2600 BaseResult
2601 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2602                          ParsedAttributes &Attributes,
2603                          bool Virtual, AccessSpecifier Access,
2604                          ParsedType basetype, SourceLocation BaseLoc,
2605                          SourceLocation EllipsisLoc) {
2606   if (!classdecl)
2607     return true;
2608 
2609   AdjustDeclIfTemplate(classdecl);
2610   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2611   if (!Class)
2612     return true;
2613 
2614   // We haven't yet attached the base specifiers.
2615   Class->setIsParsingBaseSpecifiers();
2616 
2617   // We do not support any C++11 attributes on base-specifiers yet.
2618   // Diagnose any attributes we see.
2619   for (const ParsedAttr &AL : Attributes) {
2620     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2621       continue;
2622     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2623                           ? (unsigned)diag::warn_unknown_attribute_ignored
2624                           : (unsigned)diag::err_base_specifier_attribute)
2625         << AL << AL.getRange();
2626   }
2627 
2628   TypeSourceInfo *TInfo = nullptr;
2629   GetTypeFromParser(basetype, &TInfo);
2630 
2631   if (EllipsisLoc.isInvalid() &&
2632       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2633                                       UPPC_BaseType))
2634     return true;
2635 
2636   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2637                                                       Virtual, Access, TInfo,
2638                                                       EllipsisLoc))
2639     return BaseSpec;
2640   else
2641     Class->setInvalidDecl();
2642 
2643   return true;
2644 }
2645 
2646 /// Use small set to collect indirect bases.  As this is only used
2647 /// locally, there's no need to abstract the small size parameter.
2648 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2649 
2650 /// Recursively add the bases of Type.  Don't add Type itself.
2651 static void
2652 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2653                   const QualType &Type)
2654 {
2655   // Even though the incoming type is a base, it might not be
2656   // a class -- it could be a template parm, for instance.
2657   if (auto Rec = Type->getAs<RecordType>()) {
2658     auto Decl = Rec->getAsCXXRecordDecl();
2659 
2660     // Iterate over its bases.
2661     for (const auto &BaseSpec : Decl->bases()) {
2662       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2663         .getUnqualifiedType();
2664       if (Set.insert(Base).second)
2665         // If we've not already seen it, recurse.
2666         NoteIndirectBases(Context, Set, Base);
2667     }
2668   }
2669 }
2670 
2671 /// Performs the actual work of attaching the given base class
2672 /// specifiers to a C++ class.
2673 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2674                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2675  if (Bases.empty())
2676     return false;
2677 
2678   // Used to keep track of which base types we have already seen, so
2679   // that we can properly diagnose redundant direct base types. Note
2680   // that the key is always the unqualified canonical type of the base
2681   // class.
2682   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2683 
2684   // Used to track indirect bases so we can see if a direct base is
2685   // ambiguous.
2686   IndirectBaseSet IndirectBaseTypes;
2687 
2688   // Copy non-redundant base specifiers into permanent storage.
2689   unsigned NumGoodBases = 0;
2690   bool Invalid = false;
2691   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2692     QualType NewBaseType
2693       = Context.getCanonicalType(Bases[idx]->getType());
2694     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2695 
2696     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2697     if (KnownBase) {
2698       // C++ [class.mi]p3:
2699       //   A class shall not be specified as a direct base class of a
2700       //   derived class more than once.
2701       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2702           << KnownBase->getType() << Bases[idx]->getSourceRange();
2703 
2704       // Delete the duplicate base class specifier; we're going to
2705       // overwrite its pointer later.
2706       Context.Deallocate(Bases[idx]);
2707 
2708       Invalid = true;
2709     } else {
2710       // Okay, add this new base class.
2711       KnownBase = Bases[idx];
2712       Bases[NumGoodBases++] = Bases[idx];
2713 
2714       // Note this base's direct & indirect bases, if there could be ambiguity.
2715       if (Bases.size() > 1)
2716         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2717 
2718       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2719         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2720         if (Class->isInterface() &&
2721               (!RD->isInterfaceLike() ||
2722                KnownBase->getAccessSpecifier() != AS_public)) {
2723           // The Microsoft extension __interface does not permit bases that
2724           // are not themselves public interfaces.
2725           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2726               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2727               << RD->getSourceRange();
2728           Invalid = true;
2729         }
2730         if (RD->hasAttr<WeakAttr>())
2731           Class->addAttr(WeakAttr::CreateImplicit(Context));
2732       }
2733     }
2734   }
2735 
2736   // Attach the remaining base class specifiers to the derived class.
2737   Class->setBases(Bases.data(), NumGoodBases);
2738 
2739   // Check that the only base classes that are duplicate are virtual.
2740   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2741     // Check whether this direct base is inaccessible due to ambiguity.
2742     QualType BaseType = Bases[idx]->getType();
2743 
2744     // Skip all dependent types in templates being used as base specifiers.
2745     // Checks below assume that the base specifier is a CXXRecord.
2746     if (BaseType->isDependentType())
2747       continue;
2748 
2749     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2750       .getUnqualifiedType();
2751 
2752     if (IndirectBaseTypes.count(CanonicalBase)) {
2753       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2754                          /*DetectVirtual=*/true);
2755       bool found
2756         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2757       assert(found);
2758       (void)found;
2759 
2760       if (Paths.isAmbiguous(CanonicalBase))
2761         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2762             << BaseType << getAmbiguousPathsDisplayString(Paths)
2763             << Bases[idx]->getSourceRange();
2764       else
2765         assert(Bases[idx]->isVirtual());
2766     }
2767 
2768     // Delete the base class specifier, since its data has been copied
2769     // into the CXXRecordDecl.
2770     Context.Deallocate(Bases[idx]);
2771   }
2772 
2773   return Invalid;
2774 }
2775 
2776 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2777 /// class, after checking whether there are any duplicate base
2778 /// classes.
2779 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2780                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2781   if (!ClassDecl || Bases.empty())
2782     return;
2783 
2784   AdjustDeclIfTemplate(ClassDecl);
2785   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2786 }
2787 
2788 /// Determine whether the type \p Derived is a C++ class that is
2789 /// derived from the type \p Base.
2790 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2791   if (!getLangOpts().CPlusPlus)
2792     return false;
2793 
2794   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2795   if (!DerivedRD)
2796     return false;
2797 
2798   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2799   if (!BaseRD)
2800     return false;
2801 
2802   // If either the base or the derived type is invalid, don't try to
2803   // check whether one is derived from the other.
2804   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2805     return false;
2806 
2807   // FIXME: In a modules build, do we need the entire path to be visible for us
2808   // to be able to use the inheritance relationship?
2809   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2810     return false;
2811 
2812   return DerivedRD->isDerivedFrom(BaseRD);
2813 }
2814 
2815 /// Determine whether the type \p Derived is a C++ class that is
2816 /// derived from the type \p Base.
2817 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2818                          CXXBasePaths &Paths) {
2819   if (!getLangOpts().CPlusPlus)
2820     return false;
2821 
2822   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2823   if (!DerivedRD)
2824     return false;
2825 
2826   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2827   if (!BaseRD)
2828     return false;
2829 
2830   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2831     return false;
2832 
2833   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2834 }
2835 
2836 static void BuildBasePathArray(const CXXBasePath &Path,
2837                                CXXCastPath &BasePathArray) {
2838   // We first go backward and check if we have a virtual base.
2839   // FIXME: It would be better if CXXBasePath had the base specifier for
2840   // the nearest virtual base.
2841   unsigned Start = 0;
2842   for (unsigned I = Path.size(); I != 0; --I) {
2843     if (Path[I - 1].Base->isVirtual()) {
2844       Start = I - 1;
2845       break;
2846     }
2847   }
2848 
2849   // Now add all bases.
2850   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2851     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2852 }
2853 
2854 
2855 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2856                               CXXCastPath &BasePathArray) {
2857   assert(BasePathArray.empty() && "Base path array must be empty!");
2858   assert(Paths.isRecordingPaths() && "Must record paths!");
2859   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2860 }
2861 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2862 /// conversion (where Derived and Base are class types) is
2863 /// well-formed, meaning that the conversion is unambiguous (and
2864 /// that all of the base classes are accessible). Returns true
2865 /// and emits a diagnostic if the code is ill-formed, returns false
2866 /// otherwise. Loc is the location where this routine should point to
2867 /// if there is an error, and Range is the source range to highlight
2868 /// if there is an error.
2869 ///
2870 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2871 /// diagnostic for the respective type of error will be suppressed, but the
2872 /// check for ill-formed code will still be performed.
2873 bool
2874 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2875                                    unsigned InaccessibleBaseID,
2876                                    unsigned AmbiguousBaseConvID,
2877                                    SourceLocation Loc, SourceRange Range,
2878                                    DeclarationName Name,
2879                                    CXXCastPath *BasePath,
2880                                    bool IgnoreAccess) {
2881   // First, determine whether the path from Derived to Base is
2882   // ambiguous. This is slightly more expensive than checking whether
2883   // the Derived to Base conversion exists, because here we need to
2884   // explore multiple paths to determine if there is an ambiguity.
2885   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2886                      /*DetectVirtual=*/false);
2887   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2888   if (!DerivationOkay)
2889     return true;
2890 
2891   const CXXBasePath *Path = nullptr;
2892   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2893     Path = &Paths.front();
2894 
2895   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2896   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2897   // user to access such bases.
2898   if (!Path && getLangOpts().MSVCCompat) {
2899     for (const CXXBasePath &PossiblePath : Paths) {
2900       if (PossiblePath.size() == 1) {
2901         Path = &PossiblePath;
2902         if (AmbiguousBaseConvID)
2903           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2904               << Base << Derived << Range;
2905         break;
2906       }
2907     }
2908   }
2909 
2910   if (Path) {
2911     if (!IgnoreAccess) {
2912       // Check that the base class can be accessed.
2913       switch (
2914           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2915       case AR_inaccessible:
2916         return true;
2917       case AR_accessible:
2918       case AR_dependent:
2919       case AR_delayed:
2920         break;
2921       }
2922     }
2923 
2924     // Build a base path if necessary.
2925     if (BasePath)
2926       ::BuildBasePathArray(*Path, *BasePath);
2927     return false;
2928   }
2929 
2930   if (AmbiguousBaseConvID) {
2931     // We know that the derived-to-base conversion is ambiguous, and
2932     // we're going to produce a diagnostic. Perform the derived-to-base
2933     // search just one more time to compute all of the possible paths so
2934     // that we can print them out. This is more expensive than any of
2935     // the previous derived-to-base checks we've done, but at this point
2936     // performance isn't as much of an issue.
2937     Paths.clear();
2938     Paths.setRecordingPaths(true);
2939     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2940     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2941     (void)StillOkay;
2942 
2943     // Build up a textual representation of the ambiguous paths, e.g.,
2944     // D -> B -> A, that will be used to illustrate the ambiguous
2945     // conversions in the diagnostic. We only print one of the paths
2946     // to each base class subobject.
2947     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2948 
2949     Diag(Loc, AmbiguousBaseConvID)
2950     << Derived << Base << PathDisplayStr << Range << Name;
2951   }
2952   return true;
2953 }
2954 
2955 bool
2956 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2957                                    SourceLocation Loc, SourceRange Range,
2958                                    CXXCastPath *BasePath,
2959                                    bool IgnoreAccess) {
2960   return CheckDerivedToBaseConversion(
2961       Derived, Base, diag::err_upcast_to_inaccessible_base,
2962       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2963       BasePath, IgnoreAccess);
2964 }
2965 
2966 
2967 /// Builds a string representing ambiguous paths from a
2968 /// specific derived class to different subobjects of the same base
2969 /// class.
2970 ///
2971 /// This function builds a string that can be used in error messages
2972 /// to show the different paths that one can take through the
2973 /// inheritance hierarchy to go from the derived class to different
2974 /// subobjects of a base class. The result looks something like this:
2975 /// @code
2976 /// struct D -> struct B -> struct A
2977 /// struct D -> struct C -> struct A
2978 /// @endcode
2979 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2980   std::string PathDisplayStr;
2981   std::set<unsigned> DisplayedPaths;
2982   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2983        Path != Paths.end(); ++Path) {
2984     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2985       // We haven't displayed a path to this particular base
2986       // class subobject yet.
2987       PathDisplayStr += "\n    ";
2988       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2989       for (CXXBasePath::const_iterator Element = Path->begin();
2990            Element != Path->end(); ++Element)
2991         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2992     }
2993   }
2994 
2995   return PathDisplayStr;
2996 }
2997 
2998 //===----------------------------------------------------------------------===//
2999 // C++ class member Handling
3000 //===----------------------------------------------------------------------===//
3001 
3002 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3003 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3004                                 SourceLocation ColonLoc,
3005                                 const ParsedAttributesView &Attrs) {
3006   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3007   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3008                                                   ASLoc, ColonLoc);
3009   CurContext->addHiddenDecl(ASDecl);
3010   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3011 }
3012 
3013 /// CheckOverrideControl - Check C++11 override control semantics.
3014 void Sema::CheckOverrideControl(NamedDecl *D) {
3015   if (D->isInvalidDecl())
3016     return;
3017 
3018   // We only care about "override" and "final" declarations.
3019   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3020     return;
3021 
3022   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3023 
3024   // We can't check dependent instance methods.
3025   if (MD && MD->isInstance() &&
3026       (MD->getParent()->hasAnyDependentBases() ||
3027        MD->getType()->isDependentType()))
3028     return;
3029 
3030   if (MD && !MD->isVirtual()) {
3031     // If we have a non-virtual method, check if if hides a virtual method.
3032     // (In that case, it's most likely the method has the wrong type.)
3033     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3034     FindHiddenVirtualMethods(MD, OverloadedMethods);
3035 
3036     if (!OverloadedMethods.empty()) {
3037       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3038         Diag(OA->getLocation(),
3039              diag::override_keyword_hides_virtual_member_function)
3040           << "override" << (OverloadedMethods.size() > 1);
3041       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3042         Diag(FA->getLocation(),
3043              diag::override_keyword_hides_virtual_member_function)
3044           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3045           << (OverloadedMethods.size() > 1);
3046       }
3047       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3048       MD->setInvalidDecl();
3049       return;
3050     }
3051     // Fall through into the general case diagnostic.
3052     // FIXME: We might want to attempt typo correction here.
3053   }
3054 
3055   if (!MD || !MD->isVirtual()) {
3056     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3057       Diag(OA->getLocation(),
3058            diag::override_keyword_only_allowed_on_virtual_member_functions)
3059         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3060       D->dropAttr<OverrideAttr>();
3061     }
3062     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3063       Diag(FA->getLocation(),
3064            diag::override_keyword_only_allowed_on_virtual_member_functions)
3065         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3066         << FixItHint::CreateRemoval(FA->getLocation());
3067       D->dropAttr<FinalAttr>();
3068     }
3069     return;
3070   }
3071 
3072   // C++11 [class.virtual]p5:
3073   //   If a function is marked with the virt-specifier override and
3074   //   does not override a member function of a base class, the program is
3075   //   ill-formed.
3076   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3077   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3078     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3079       << MD->getDeclName();
3080 }
3081 
3082 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3083   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3084     return;
3085   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3086   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3087     return;
3088 
3089   SourceLocation Loc = MD->getLocation();
3090   SourceLocation SpellingLoc = Loc;
3091   if (getSourceManager().isMacroArgExpansion(Loc))
3092     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3093   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3094   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3095       return;
3096 
3097   if (MD->size_overridden_methods() > 0) {
3098     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3099       unsigned DiagID =
3100           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3101               ? DiagInconsistent
3102               : DiagSuggest;
3103       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3104       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3105       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3106     };
3107     if (isa<CXXDestructorDecl>(MD))
3108       EmitDiag(
3109           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3110           diag::warn_suggest_destructor_marked_not_override_overriding);
3111     else
3112       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3113                diag::warn_suggest_function_marked_not_override_overriding);
3114   }
3115 }
3116 
3117 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3118 /// function overrides a virtual member function marked 'final', according to
3119 /// C++11 [class.virtual]p4.
3120 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3121                                                   const CXXMethodDecl *Old) {
3122   FinalAttr *FA = Old->getAttr<FinalAttr>();
3123   if (!FA)
3124     return false;
3125 
3126   Diag(New->getLocation(), diag::err_final_function_overridden)
3127     << New->getDeclName()
3128     << FA->isSpelledAsSealed();
3129   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3130   return true;
3131 }
3132 
3133 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3134   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3135   // FIXME: Destruction of ObjC lifetime types has side-effects.
3136   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3137     return !RD->isCompleteDefinition() ||
3138            !RD->hasTrivialDefaultConstructor() ||
3139            !RD->hasTrivialDestructor();
3140   return false;
3141 }
3142 
3143 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3144   ParsedAttributesView::const_iterator Itr =
3145       llvm::find_if(list, [](const ParsedAttr &AL) {
3146         return AL.isDeclspecPropertyAttribute();
3147       });
3148   if (Itr != list.end())
3149     return &*Itr;
3150   return nullptr;
3151 }
3152 
3153 // Check if there is a field shadowing.
3154 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3155                                       DeclarationName FieldName,
3156                                       const CXXRecordDecl *RD,
3157                                       bool DeclIsField) {
3158   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3159     return;
3160 
3161   // To record a shadowed field in a base
3162   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3163   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3164                            CXXBasePath &Path) {
3165     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3166     // Record an ambiguous path directly
3167     if (Bases.find(Base) != Bases.end())
3168       return true;
3169     for (const auto Field : Base->lookup(FieldName)) {
3170       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3171           Field->getAccess() != AS_private) {
3172         assert(Field->getAccess() != AS_none);
3173         assert(Bases.find(Base) == Bases.end());
3174         Bases[Base] = Field;
3175         return true;
3176       }
3177     }
3178     return false;
3179   };
3180 
3181   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3182                      /*DetectVirtual=*/true);
3183   if (!RD->lookupInBases(FieldShadowed, Paths))
3184     return;
3185 
3186   for (const auto &P : Paths) {
3187     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3188     auto It = Bases.find(Base);
3189     // Skip duplicated bases
3190     if (It == Bases.end())
3191       continue;
3192     auto BaseField = It->second;
3193     assert(BaseField->getAccess() != AS_private);
3194     if (AS_none !=
3195         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3196       Diag(Loc, diag::warn_shadow_field)
3197         << FieldName << RD << Base << DeclIsField;
3198       Diag(BaseField->getLocation(), diag::note_shadow_field);
3199       Bases.erase(It);
3200     }
3201   }
3202 }
3203 
3204 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3205 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3206 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3207 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3208 /// present (but parsing it has been deferred).
3209 NamedDecl *
3210 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3211                                MultiTemplateParamsArg TemplateParameterLists,
3212                                Expr *BW, const VirtSpecifiers &VS,
3213                                InClassInitStyle InitStyle) {
3214   const DeclSpec &DS = D.getDeclSpec();
3215   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3216   DeclarationName Name = NameInfo.getName();
3217   SourceLocation Loc = NameInfo.getLoc();
3218 
3219   // For anonymous bitfields, the location should point to the type.
3220   if (Loc.isInvalid())
3221     Loc = D.getBeginLoc();
3222 
3223   Expr *BitWidth = static_cast<Expr*>(BW);
3224 
3225   assert(isa<CXXRecordDecl>(CurContext));
3226   assert(!DS.isFriendSpecified());
3227 
3228   bool isFunc = D.isDeclarationOfFunction();
3229   const ParsedAttr *MSPropertyAttr =
3230       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3231 
3232   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3233     // The Microsoft extension __interface only permits public member functions
3234     // and prohibits constructors, destructors, operators, non-public member
3235     // functions, static methods and data members.
3236     unsigned InvalidDecl;
3237     bool ShowDeclName = true;
3238     if (!isFunc &&
3239         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3240       InvalidDecl = 0;
3241     else if (!isFunc)
3242       InvalidDecl = 1;
3243     else if (AS != AS_public)
3244       InvalidDecl = 2;
3245     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3246       InvalidDecl = 3;
3247     else switch (Name.getNameKind()) {
3248       case DeclarationName::CXXConstructorName:
3249         InvalidDecl = 4;
3250         ShowDeclName = false;
3251         break;
3252 
3253       case DeclarationName::CXXDestructorName:
3254         InvalidDecl = 5;
3255         ShowDeclName = false;
3256         break;
3257 
3258       case DeclarationName::CXXOperatorName:
3259       case DeclarationName::CXXConversionFunctionName:
3260         InvalidDecl = 6;
3261         break;
3262 
3263       default:
3264         InvalidDecl = 0;
3265         break;
3266     }
3267 
3268     if (InvalidDecl) {
3269       if (ShowDeclName)
3270         Diag(Loc, diag::err_invalid_member_in_interface)
3271           << (InvalidDecl-1) << Name;
3272       else
3273         Diag(Loc, diag::err_invalid_member_in_interface)
3274           << (InvalidDecl-1) << "";
3275       return nullptr;
3276     }
3277   }
3278 
3279   // C++ 9.2p6: A member shall not be declared to have automatic storage
3280   // duration (auto, register) or with the extern storage-class-specifier.
3281   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3282   // data members and cannot be applied to names declared const or static,
3283   // and cannot be applied to reference members.
3284   switch (DS.getStorageClassSpec()) {
3285   case DeclSpec::SCS_unspecified:
3286   case DeclSpec::SCS_typedef:
3287   case DeclSpec::SCS_static:
3288     break;
3289   case DeclSpec::SCS_mutable:
3290     if (isFunc) {
3291       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3292 
3293       // FIXME: It would be nicer if the keyword was ignored only for this
3294       // declarator. Otherwise we could get follow-up errors.
3295       D.getMutableDeclSpec().ClearStorageClassSpecs();
3296     }
3297     break;
3298   default:
3299     Diag(DS.getStorageClassSpecLoc(),
3300          diag::err_storageclass_invalid_for_member);
3301     D.getMutableDeclSpec().ClearStorageClassSpecs();
3302     break;
3303   }
3304 
3305   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3306                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3307                       !isFunc);
3308 
3309   if (DS.hasConstexprSpecifier() && isInstField) {
3310     SemaDiagnosticBuilder B =
3311         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3312     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3313     if (InitStyle == ICIS_NoInit) {
3314       B << 0 << 0;
3315       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3316         B << FixItHint::CreateRemoval(ConstexprLoc);
3317       else {
3318         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3319         D.getMutableDeclSpec().ClearConstexprSpec();
3320         const char *PrevSpec;
3321         unsigned DiagID;
3322         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3323             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3324         (void)Failed;
3325         assert(!Failed && "Making a constexpr member const shouldn't fail");
3326       }
3327     } else {
3328       B << 1;
3329       const char *PrevSpec;
3330       unsigned DiagID;
3331       if (D.getMutableDeclSpec().SetStorageClassSpec(
3332           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3333           Context.getPrintingPolicy())) {
3334         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3335                "This is the only DeclSpec that should fail to be applied");
3336         B << 1;
3337       } else {
3338         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3339         isInstField = false;
3340       }
3341     }
3342   }
3343 
3344   NamedDecl *Member;
3345   if (isInstField) {
3346     CXXScopeSpec &SS = D.getCXXScopeSpec();
3347 
3348     // Data members must have identifiers for names.
3349     if (!Name.isIdentifier()) {
3350       Diag(Loc, diag::err_bad_variable_name)
3351         << Name;
3352       return nullptr;
3353     }
3354 
3355     IdentifierInfo *II = Name.getAsIdentifierInfo();
3356 
3357     // Member field could not be with "template" keyword.
3358     // So TemplateParameterLists should be empty in this case.
3359     if (TemplateParameterLists.size()) {
3360       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3361       if (TemplateParams->size()) {
3362         // There is no such thing as a member field template.
3363         Diag(D.getIdentifierLoc(), diag::err_template_member)
3364             << II
3365             << SourceRange(TemplateParams->getTemplateLoc(),
3366                 TemplateParams->getRAngleLoc());
3367       } else {
3368         // There is an extraneous 'template<>' for this member.
3369         Diag(TemplateParams->getTemplateLoc(),
3370             diag::err_template_member_noparams)
3371             << II
3372             << SourceRange(TemplateParams->getTemplateLoc(),
3373                 TemplateParams->getRAngleLoc());
3374       }
3375       return nullptr;
3376     }
3377 
3378     if (SS.isSet() && !SS.isInvalid()) {
3379       // The user provided a superfluous scope specifier inside a class
3380       // definition:
3381       //
3382       // class X {
3383       //   int X::member;
3384       // };
3385       if (DeclContext *DC = computeDeclContext(SS, false))
3386         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3387                                      D.getName().getKind() ==
3388                                          UnqualifiedIdKind::IK_TemplateId);
3389       else
3390         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3391           << Name << SS.getRange();
3392 
3393       SS.clear();
3394     }
3395 
3396     if (MSPropertyAttr) {
3397       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3398                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3399       if (!Member)
3400         return nullptr;
3401       isInstField = false;
3402     } else {
3403       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3404                                 BitWidth, InitStyle, AS);
3405       if (!Member)
3406         return nullptr;
3407     }
3408 
3409     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3410   } else {
3411     Member = HandleDeclarator(S, D, TemplateParameterLists);
3412     if (!Member)
3413       return nullptr;
3414 
3415     // Non-instance-fields can't have a bitfield.
3416     if (BitWidth) {
3417       if (Member->isInvalidDecl()) {
3418         // don't emit another diagnostic.
3419       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3420         // C++ 9.6p3: A bit-field shall not be a static member.
3421         // "static member 'A' cannot be a bit-field"
3422         Diag(Loc, diag::err_static_not_bitfield)
3423           << Name << BitWidth->getSourceRange();
3424       } else if (isa<TypedefDecl>(Member)) {
3425         // "typedef member 'x' cannot be a bit-field"
3426         Diag(Loc, diag::err_typedef_not_bitfield)
3427           << Name << BitWidth->getSourceRange();
3428       } else {
3429         // A function typedef ("typedef int f(); f a;").
3430         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3431         Diag(Loc, diag::err_not_integral_type_bitfield)
3432           << Name << cast<ValueDecl>(Member)->getType()
3433           << BitWidth->getSourceRange();
3434       }
3435 
3436       BitWidth = nullptr;
3437       Member->setInvalidDecl();
3438     }
3439 
3440     NamedDecl *NonTemplateMember = Member;
3441     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3442       NonTemplateMember = FunTmpl->getTemplatedDecl();
3443     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3444       NonTemplateMember = VarTmpl->getTemplatedDecl();
3445 
3446     Member->setAccess(AS);
3447 
3448     // If we have declared a member function template or static data member
3449     // template, set the access of the templated declaration as well.
3450     if (NonTemplateMember != Member)
3451       NonTemplateMember->setAccess(AS);
3452 
3453     // C++ [temp.deduct.guide]p3:
3454     //   A deduction guide [...] for a member class template [shall be
3455     //   declared] with the same access [as the template].
3456     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3457       auto *TD = DG->getDeducedTemplate();
3458       // Access specifiers are only meaningful if both the template and the
3459       // deduction guide are from the same scope.
3460       if (AS != TD->getAccess() &&
3461           TD->getDeclContext()->getRedeclContext()->Equals(
3462               DG->getDeclContext()->getRedeclContext())) {
3463         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3464         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3465             << TD->getAccess();
3466         const AccessSpecDecl *LastAccessSpec = nullptr;
3467         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3468           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3469             LastAccessSpec = AccessSpec;
3470         }
3471         assert(LastAccessSpec && "differing access with no access specifier");
3472         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3473             << AS;
3474       }
3475     }
3476   }
3477 
3478   if (VS.isOverrideSpecified())
3479     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3480                                          AttributeCommonInfo::AS_Keyword));
3481   if (VS.isFinalSpecified())
3482     Member->addAttr(FinalAttr::Create(
3483         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3484         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3485 
3486   if (VS.getLastLocation().isValid()) {
3487     // Update the end location of a method that has a virt-specifiers.
3488     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3489       MD->setRangeEnd(VS.getLastLocation());
3490   }
3491 
3492   CheckOverrideControl(Member);
3493 
3494   assert((Name || isInstField) && "No identifier for non-field ?");
3495 
3496   if (isInstField) {
3497     FieldDecl *FD = cast<FieldDecl>(Member);
3498     FieldCollector->Add(FD);
3499 
3500     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3501       // Remember all explicit private FieldDecls that have a name, no side
3502       // effects and are not part of a dependent type declaration.
3503       if (!FD->isImplicit() && FD->getDeclName() &&
3504           FD->getAccess() == AS_private &&
3505           !FD->hasAttr<UnusedAttr>() &&
3506           !FD->getParent()->isDependentContext() &&
3507           !InitializationHasSideEffects(*FD))
3508         UnusedPrivateFields.insert(FD);
3509     }
3510   }
3511 
3512   return Member;
3513 }
3514 
3515 namespace {
3516   class UninitializedFieldVisitor
3517       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3518     Sema &S;
3519     // List of Decls to generate a warning on.  Also remove Decls that become
3520     // initialized.
3521     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3522     // List of base classes of the record.  Classes are removed after their
3523     // initializers.
3524     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3525     // Vector of decls to be removed from the Decl set prior to visiting the
3526     // nodes.  These Decls may have been initialized in the prior initializer.
3527     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3528     // If non-null, add a note to the warning pointing back to the constructor.
3529     const CXXConstructorDecl *Constructor;
3530     // Variables to hold state when processing an initializer list.  When
3531     // InitList is true, special case initialization of FieldDecls matching
3532     // InitListFieldDecl.
3533     bool InitList;
3534     FieldDecl *InitListFieldDecl;
3535     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3536 
3537   public:
3538     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3539     UninitializedFieldVisitor(Sema &S,
3540                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3541                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3542       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3543         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3544 
3545     // Returns true if the use of ME is not an uninitialized use.
3546     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3547                                          bool CheckReferenceOnly) {
3548       llvm::SmallVector<FieldDecl*, 4> Fields;
3549       bool ReferenceField = false;
3550       while (ME) {
3551         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3552         if (!FD)
3553           return false;
3554         Fields.push_back(FD);
3555         if (FD->getType()->isReferenceType())
3556           ReferenceField = true;
3557         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3558       }
3559 
3560       // Binding a reference to an uninitialized field is not an
3561       // uninitialized use.
3562       if (CheckReferenceOnly && !ReferenceField)
3563         return true;
3564 
3565       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3566       // Discard the first field since it is the field decl that is being
3567       // initialized.
3568       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3569         UsedFieldIndex.push_back((*I)->getFieldIndex());
3570       }
3571 
3572       for (auto UsedIter = UsedFieldIndex.begin(),
3573                 UsedEnd = UsedFieldIndex.end(),
3574                 OrigIter = InitFieldIndex.begin(),
3575                 OrigEnd = InitFieldIndex.end();
3576            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3577         if (*UsedIter < *OrigIter)
3578           return true;
3579         if (*UsedIter > *OrigIter)
3580           break;
3581       }
3582 
3583       return false;
3584     }
3585 
3586     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3587                           bool AddressOf) {
3588       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3589         return;
3590 
3591       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3592       // or union.
3593       MemberExpr *FieldME = ME;
3594 
3595       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3596 
3597       Expr *Base = ME;
3598       while (MemberExpr *SubME =
3599                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3600 
3601         if (isa<VarDecl>(SubME->getMemberDecl()))
3602           return;
3603 
3604         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3605           if (!FD->isAnonymousStructOrUnion())
3606             FieldME = SubME;
3607 
3608         if (!FieldME->getType().isPODType(S.Context))
3609           AllPODFields = false;
3610 
3611         Base = SubME->getBase();
3612       }
3613 
3614       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3615         Visit(Base);
3616         return;
3617       }
3618 
3619       if (AddressOf && AllPODFields)
3620         return;
3621 
3622       ValueDecl* FoundVD = FieldME->getMemberDecl();
3623 
3624       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3625         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3626           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3627         }
3628 
3629         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3630           QualType T = BaseCast->getType();
3631           if (T->isPointerType() &&
3632               BaseClasses.count(T->getPointeeType())) {
3633             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3634                 << T->getPointeeType() << FoundVD;
3635           }
3636         }
3637       }
3638 
3639       if (!Decls.count(FoundVD))
3640         return;
3641 
3642       const bool IsReference = FoundVD->getType()->isReferenceType();
3643 
3644       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3645         // Special checking for initializer lists.
3646         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3647           return;
3648         }
3649       } else {
3650         // Prevent double warnings on use of unbounded references.
3651         if (CheckReferenceOnly && !IsReference)
3652           return;
3653       }
3654 
3655       unsigned diag = IsReference
3656           ? diag::warn_reference_field_is_uninit
3657           : diag::warn_field_is_uninit;
3658       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3659       if (Constructor)
3660         S.Diag(Constructor->getLocation(),
3661                diag::note_uninit_in_this_constructor)
3662           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3663 
3664     }
3665 
3666     void HandleValue(Expr *E, bool AddressOf) {
3667       E = E->IgnoreParens();
3668 
3669       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3670         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3671                          AddressOf /*AddressOf*/);
3672         return;
3673       }
3674 
3675       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3676         Visit(CO->getCond());
3677         HandleValue(CO->getTrueExpr(), AddressOf);
3678         HandleValue(CO->getFalseExpr(), AddressOf);
3679         return;
3680       }
3681 
3682       if (BinaryConditionalOperator *BCO =
3683               dyn_cast<BinaryConditionalOperator>(E)) {
3684         Visit(BCO->getCond());
3685         HandleValue(BCO->getFalseExpr(), AddressOf);
3686         return;
3687       }
3688 
3689       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3690         HandleValue(OVE->getSourceExpr(), AddressOf);
3691         return;
3692       }
3693 
3694       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3695         switch (BO->getOpcode()) {
3696         default:
3697           break;
3698         case(BO_PtrMemD):
3699         case(BO_PtrMemI):
3700           HandleValue(BO->getLHS(), AddressOf);
3701           Visit(BO->getRHS());
3702           return;
3703         case(BO_Comma):
3704           Visit(BO->getLHS());
3705           HandleValue(BO->getRHS(), AddressOf);
3706           return;
3707         }
3708       }
3709 
3710       Visit(E);
3711     }
3712 
3713     void CheckInitListExpr(InitListExpr *ILE) {
3714       InitFieldIndex.push_back(0);
3715       for (auto Child : ILE->children()) {
3716         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3717           CheckInitListExpr(SubList);
3718         } else {
3719           Visit(Child);
3720         }
3721         ++InitFieldIndex.back();
3722       }
3723       InitFieldIndex.pop_back();
3724     }
3725 
3726     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3727                           FieldDecl *Field, const Type *BaseClass) {
3728       // Remove Decls that may have been initialized in the previous
3729       // initializer.
3730       for (ValueDecl* VD : DeclsToRemove)
3731         Decls.erase(VD);
3732       DeclsToRemove.clear();
3733 
3734       Constructor = FieldConstructor;
3735       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3736 
3737       if (ILE && Field) {
3738         InitList = true;
3739         InitListFieldDecl = Field;
3740         InitFieldIndex.clear();
3741         CheckInitListExpr(ILE);
3742       } else {
3743         InitList = false;
3744         Visit(E);
3745       }
3746 
3747       if (Field)
3748         Decls.erase(Field);
3749       if (BaseClass)
3750         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3751     }
3752 
3753     void VisitMemberExpr(MemberExpr *ME) {
3754       // All uses of unbounded reference fields will warn.
3755       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3756     }
3757 
3758     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3759       if (E->getCastKind() == CK_LValueToRValue) {
3760         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3761         return;
3762       }
3763 
3764       Inherited::VisitImplicitCastExpr(E);
3765     }
3766 
3767     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3768       if (E->getConstructor()->isCopyConstructor()) {
3769         Expr *ArgExpr = E->getArg(0);
3770         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3771           if (ILE->getNumInits() == 1)
3772             ArgExpr = ILE->getInit(0);
3773         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3774           if (ICE->getCastKind() == CK_NoOp)
3775             ArgExpr = ICE->getSubExpr();
3776         HandleValue(ArgExpr, false /*AddressOf*/);
3777         return;
3778       }
3779       Inherited::VisitCXXConstructExpr(E);
3780     }
3781 
3782     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3783       Expr *Callee = E->getCallee();
3784       if (isa<MemberExpr>(Callee)) {
3785         HandleValue(Callee, false /*AddressOf*/);
3786         for (auto Arg : E->arguments())
3787           Visit(Arg);
3788         return;
3789       }
3790 
3791       Inherited::VisitCXXMemberCallExpr(E);
3792     }
3793 
3794     void VisitCallExpr(CallExpr *E) {
3795       // Treat std::move as a use.
3796       if (E->isCallToStdMove()) {
3797         HandleValue(E->getArg(0), /*AddressOf=*/false);
3798         return;
3799       }
3800 
3801       Inherited::VisitCallExpr(E);
3802     }
3803 
3804     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3805       Expr *Callee = E->getCallee();
3806 
3807       if (isa<UnresolvedLookupExpr>(Callee))
3808         return Inherited::VisitCXXOperatorCallExpr(E);
3809 
3810       Visit(Callee);
3811       for (auto Arg : E->arguments())
3812         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3813     }
3814 
3815     void VisitBinaryOperator(BinaryOperator *E) {
3816       // If a field assignment is detected, remove the field from the
3817       // uninitiailized field set.
3818       if (E->getOpcode() == BO_Assign)
3819         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3820           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3821             if (!FD->getType()->isReferenceType())
3822               DeclsToRemove.push_back(FD);
3823 
3824       if (E->isCompoundAssignmentOp()) {
3825         HandleValue(E->getLHS(), false /*AddressOf*/);
3826         Visit(E->getRHS());
3827         return;
3828       }
3829 
3830       Inherited::VisitBinaryOperator(E);
3831     }
3832 
3833     void VisitUnaryOperator(UnaryOperator *E) {
3834       if (E->isIncrementDecrementOp()) {
3835         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3836         return;
3837       }
3838       if (E->getOpcode() == UO_AddrOf) {
3839         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3840           HandleValue(ME->getBase(), true /*AddressOf*/);
3841           return;
3842         }
3843       }
3844 
3845       Inherited::VisitUnaryOperator(E);
3846     }
3847   };
3848 
3849   // Diagnose value-uses of fields to initialize themselves, e.g.
3850   //   foo(foo)
3851   // where foo is not also a parameter to the constructor.
3852   // Also diagnose across field uninitialized use such as
3853   //   x(y), y(x)
3854   // TODO: implement -Wuninitialized and fold this into that framework.
3855   static void DiagnoseUninitializedFields(
3856       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3857 
3858     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3859                                            Constructor->getLocation())) {
3860       return;
3861     }
3862 
3863     if (Constructor->isInvalidDecl())
3864       return;
3865 
3866     const CXXRecordDecl *RD = Constructor->getParent();
3867 
3868     if (RD->isDependentContext())
3869       return;
3870 
3871     // Holds fields that are uninitialized.
3872     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3873 
3874     // At the beginning, all fields are uninitialized.
3875     for (auto *I : RD->decls()) {
3876       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3877         UninitializedFields.insert(FD);
3878       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3879         UninitializedFields.insert(IFD->getAnonField());
3880       }
3881     }
3882 
3883     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3884     for (auto I : RD->bases())
3885       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3886 
3887     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3888       return;
3889 
3890     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3891                                                    UninitializedFields,
3892                                                    UninitializedBaseClasses);
3893 
3894     for (const auto *FieldInit : Constructor->inits()) {
3895       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3896         break;
3897 
3898       Expr *InitExpr = FieldInit->getInit();
3899       if (!InitExpr)
3900         continue;
3901 
3902       if (CXXDefaultInitExpr *Default =
3903               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3904         InitExpr = Default->getExpr();
3905         if (!InitExpr)
3906           continue;
3907         // In class initializers will point to the constructor.
3908         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3909                                               FieldInit->getAnyMember(),
3910                                               FieldInit->getBaseClass());
3911       } else {
3912         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3913                                               FieldInit->getAnyMember(),
3914                                               FieldInit->getBaseClass());
3915       }
3916     }
3917   }
3918 } // namespace
3919 
3920 /// Enter a new C++ default initializer scope. After calling this, the
3921 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3922 /// parsing or instantiating the initializer failed.
3923 void Sema::ActOnStartCXXInClassMemberInitializer() {
3924   // Create a synthetic function scope to represent the call to the constructor
3925   // that notionally surrounds a use of this initializer.
3926   PushFunctionScope();
3927 }
3928 
3929 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3930   if (!D.isFunctionDeclarator())
3931     return;
3932   auto &FTI = D.getFunctionTypeInfo();
3933   if (!FTI.Params)
3934     return;
3935   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3936                                                           FTI.NumParams)) {
3937     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3938     if (ParamDecl->getDeclName())
3939       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3940   }
3941 }
3942 
3943 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3944   return ActOnRequiresClause(ConstraintExpr);
3945 }
3946 
3947 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3948   if (ConstraintExpr.isInvalid())
3949     return ExprError();
3950 
3951   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3952   if (ConstraintExpr.isInvalid())
3953     return ExprError();
3954 
3955   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3956                                       UPPC_RequiresClause))
3957     return ExprError();
3958 
3959   return ConstraintExpr;
3960 }
3961 
3962 /// This is invoked after parsing an in-class initializer for a
3963 /// non-static C++ class member, and after instantiating an in-class initializer
3964 /// in a class template. Such actions are deferred until the class is complete.
3965 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3966                                                   SourceLocation InitLoc,
3967                                                   Expr *InitExpr) {
3968   // Pop the notional constructor scope we created earlier.
3969   PopFunctionScopeInfo(nullptr, D);
3970 
3971   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3972   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3973          "must set init style when field is created");
3974 
3975   if (!InitExpr) {
3976     D->setInvalidDecl();
3977     if (FD)
3978       FD->removeInClassInitializer();
3979     return;
3980   }
3981 
3982   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3983     FD->setInvalidDecl();
3984     FD->removeInClassInitializer();
3985     return;
3986   }
3987 
3988   ExprResult Init = InitExpr;
3989   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3990     InitializedEntity Entity =
3991         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3992     InitializationKind Kind =
3993         FD->getInClassInitStyle() == ICIS_ListInit
3994             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3995                                                    InitExpr->getBeginLoc(),
3996                                                    InitExpr->getEndLoc())
3997             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3998     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3999     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4000     if (Init.isInvalid()) {
4001       FD->setInvalidDecl();
4002       return;
4003     }
4004   }
4005 
4006   // C++11 [class.base.init]p7:
4007   //   The initialization of each base and member constitutes a
4008   //   full-expression.
4009   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4010   if (Init.isInvalid()) {
4011     FD->setInvalidDecl();
4012     return;
4013   }
4014 
4015   InitExpr = Init.get();
4016 
4017   FD->setInClassInitializer(InitExpr);
4018 }
4019 
4020 /// Find the direct and/or virtual base specifiers that
4021 /// correspond to the given base type, for use in base initialization
4022 /// within a constructor.
4023 static bool FindBaseInitializer(Sema &SemaRef,
4024                                 CXXRecordDecl *ClassDecl,
4025                                 QualType BaseType,
4026                                 const CXXBaseSpecifier *&DirectBaseSpec,
4027                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4028   // First, check for a direct base class.
4029   DirectBaseSpec = nullptr;
4030   for (const auto &Base : ClassDecl->bases()) {
4031     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4032       // We found a direct base of this type. That's what we're
4033       // initializing.
4034       DirectBaseSpec = &Base;
4035       break;
4036     }
4037   }
4038 
4039   // Check for a virtual base class.
4040   // FIXME: We might be able to short-circuit this if we know in advance that
4041   // there are no virtual bases.
4042   VirtualBaseSpec = nullptr;
4043   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4044     // We haven't found a base yet; search the class hierarchy for a
4045     // virtual base class.
4046     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4047                        /*DetectVirtual=*/false);
4048     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4049                               SemaRef.Context.getTypeDeclType(ClassDecl),
4050                               BaseType, Paths)) {
4051       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4052            Path != Paths.end(); ++Path) {
4053         if (Path->back().Base->isVirtual()) {
4054           VirtualBaseSpec = Path->back().Base;
4055           break;
4056         }
4057       }
4058     }
4059   }
4060 
4061   return DirectBaseSpec || VirtualBaseSpec;
4062 }
4063 
4064 /// Handle a C++ member initializer using braced-init-list syntax.
4065 MemInitResult
4066 Sema::ActOnMemInitializer(Decl *ConstructorD,
4067                           Scope *S,
4068                           CXXScopeSpec &SS,
4069                           IdentifierInfo *MemberOrBase,
4070                           ParsedType TemplateTypeTy,
4071                           const DeclSpec &DS,
4072                           SourceLocation IdLoc,
4073                           Expr *InitList,
4074                           SourceLocation EllipsisLoc) {
4075   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4076                              DS, IdLoc, InitList,
4077                              EllipsisLoc);
4078 }
4079 
4080 /// Handle a C++ member initializer using parentheses syntax.
4081 MemInitResult
4082 Sema::ActOnMemInitializer(Decl *ConstructorD,
4083                           Scope *S,
4084                           CXXScopeSpec &SS,
4085                           IdentifierInfo *MemberOrBase,
4086                           ParsedType TemplateTypeTy,
4087                           const DeclSpec &DS,
4088                           SourceLocation IdLoc,
4089                           SourceLocation LParenLoc,
4090                           ArrayRef<Expr *> Args,
4091                           SourceLocation RParenLoc,
4092                           SourceLocation EllipsisLoc) {
4093   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4094   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4095                              DS, IdLoc, List, EllipsisLoc);
4096 }
4097 
4098 namespace {
4099 
4100 // Callback to only accept typo corrections that can be a valid C++ member
4101 // intializer: either a non-static field member or a base class.
4102 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4103 public:
4104   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4105       : ClassDecl(ClassDecl) {}
4106 
4107   bool ValidateCandidate(const TypoCorrection &candidate) override {
4108     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4109       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4110         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4111       return isa<TypeDecl>(ND);
4112     }
4113     return false;
4114   }
4115 
4116   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4117     return std::make_unique<MemInitializerValidatorCCC>(*this);
4118   }
4119 
4120 private:
4121   CXXRecordDecl *ClassDecl;
4122 };
4123 
4124 }
4125 
4126 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4127                                              CXXScopeSpec &SS,
4128                                              ParsedType TemplateTypeTy,
4129                                              IdentifierInfo *MemberOrBase) {
4130   if (SS.getScopeRep() || TemplateTypeTy)
4131     return nullptr;
4132   for (auto *D : ClassDecl->lookup(MemberOrBase))
4133     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4134       return cast<ValueDecl>(D);
4135   return nullptr;
4136 }
4137 
4138 /// Handle a C++ member initializer.
4139 MemInitResult
4140 Sema::BuildMemInitializer(Decl *ConstructorD,
4141                           Scope *S,
4142                           CXXScopeSpec &SS,
4143                           IdentifierInfo *MemberOrBase,
4144                           ParsedType TemplateTypeTy,
4145                           const DeclSpec &DS,
4146                           SourceLocation IdLoc,
4147                           Expr *Init,
4148                           SourceLocation EllipsisLoc) {
4149   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4150   if (!Res.isUsable())
4151     return true;
4152   Init = Res.get();
4153 
4154   if (!ConstructorD)
4155     return true;
4156 
4157   AdjustDeclIfTemplate(ConstructorD);
4158 
4159   CXXConstructorDecl *Constructor
4160     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4161   if (!Constructor) {
4162     // The user wrote a constructor initializer on a function that is
4163     // not a C++ constructor. Ignore the error for now, because we may
4164     // have more member initializers coming; we'll diagnose it just
4165     // once in ActOnMemInitializers.
4166     return true;
4167   }
4168 
4169   CXXRecordDecl *ClassDecl = Constructor->getParent();
4170 
4171   // C++ [class.base.init]p2:
4172   //   Names in a mem-initializer-id are looked up in the scope of the
4173   //   constructor's class and, if not found in that scope, are looked
4174   //   up in the scope containing the constructor's definition.
4175   //   [Note: if the constructor's class contains a member with the
4176   //   same name as a direct or virtual base class of the class, a
4177   //   mem-initializer-id naming the member or base class and composed
4178   //   of a single identifier refers to the class member. A
4179   //   mem-initializer-id for the hidden base class may be specified
4180   //   using a qualified name. ]
4181 
4182   // Look for a member, first.
4183   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4184           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4185     if (EllipsisLoc.isValid())
4186       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4187           << MemberOrBase
4188           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4189 
4190     return BuildMemberInitializer(Member, Init, IdLoc);
4191   }
4192   // It didn't name a member, so see if it names a class.
4193   QualType BaseType;
4194   TypeSourceInfo *TInfo = nullptr;
4195 
4196   if (TemplateTypeTy) {
4197     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4198     if (BaseType.isNull())
4199       return true;
4200   } else if (DS.getTypeSpecType() == TST_decltype) {
4201     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4202   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4203     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4204     return true;
4205   } else {
4206     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4207     LookupParsedName(R, S, &SS);
4208 
4209     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4210     if (!TyD) {
4211       if (R.isAmbiguous()) return true;
4212 
4213       // We don't want access-control diagnostics here.
4214       R.suppressDiagnostics();
4215 
4216       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4217         bool NotUnknownSpecialization = false;
4218         DeclContext *DC = computeDeclContext(SS, false);
4219         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4220           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4221 
4222         if (!NotUnknownSpecialization) {
4223           // When the scope specifier can refer to a member of an unknown
4224           // specialization, we take it as a type name.
4225           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4226                                        SS.getWithLocInContext(Context),
4227                                        *MemberOrBase, IdLoc);
4228           if (BaseType.isNull())
4229             return true;
4230 
4231           TInfo = Context.CreateTypeSourceInfo(BaseType);
4232           DependentNameTypeLoc TL =
4233               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4234           if (!TL.isNull()) {
4235             TL.setNameLoc(IdLoc);
4236             TL.setElaboratedKeywordLoc(SourceLocation());
4237             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4238           }
4239 
4240           R.clear();
4241           R.setLookupName(MemberOrBase);
4242         }
4243       }
4244 
4245       // If no results were found, try to correct typos.
4246       TypoCorrection Corr;
4247       MemInitializerValidatorCCC CCC(ClassDecl);
4248       if (R.empty() && BaseType.isNull() &&
4249           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4250                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4251         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4252           // We have found a non-static data member with a similar
4253           // name to what was typed; complain and initialize that
4254           // member.
4255           diagnoseTypo(Corr,
4256                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4257                          << MemberOrBase << true);
4258           return BuildMemberInitializer(Member, Init, IdLoc);
4259         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4260           const CXXBaseSpecifier *DirectBaseSpec;
4261           const CXXBaseSpecifier *VirtualBaseSpec;
4262           if (FindBaseInitializer(*this, ClassDecl,
4263                                   Context.getTypeDeclType(Type),
4264                                   DirectBaseSpec, VirtualBaseSpec)) {
4265             // We have found a direct or virtual base class with a
4266             // similar name to what was typed; complain and initialize
4267             // that base class.
4268             diagnoseTypo(Corr,
4269                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4270                            << MemberOrBase << false,
4271                          PDiag() /*Suppress note, we provide our own.*/);
4272 
4273             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4274                                                               : VirtualBaseSpec;
4275             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4276                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4277 
4278             TyD = Type;
4279           }
4280         }
4281       }
4282 
4283       if (!TyD && BaseType.isNull()) {
4284         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4285           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4286         return true;
4287       }
4288     }
4289 
4290     if (BaseType.isNull()) {
4291       BaseType = Context.getTypeDeclType(TyD);
4292       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4293       if (SS.isSet()) {
4294         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4295                                              BaseType);
4296         TInfo = Context.CreateTypeSourceInfo(BaseType);
4297         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4298         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4299         TL.setElaboratedKeywordLoc(SourceLocation());
4300         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4301       }
4302     }
4303   }
4304 
4305   if (!TInfo)
4306     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4307 
4308   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4309 }
4310 
4311 MemInitResult
4312 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4313                              SourceLocation IdLoc) {
4314   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4315   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4316   assert((DirectMember || IndirectMember) &&
4317          "Member must be a FieldDecl or IndirectFieldDecl");
4318 
4319   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4320     return true;
4321 
4322   if (Member->isInvalidDecl())
4323     return true;
4324 
4325   MultiExprArg Args;
4326   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4327     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4328   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4329     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4330   } else {
4331     // Template instantiation doesn't reconstruct ParenListExprs for us.
4332     Args = Init;
4333   }
4334 
4335   SourceRange InitRange = Init->getSourceRange();
4336 
4337   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4338     // Can't check initialization for a member of dependent type or when
4339     // any of the arguments are type-dependent expressions.
4340     DiscardCleanupsInEvaluationContext();
4341   } else {
4342     bool InitList = false;
4343     if (isa<InitListExpr>(Init)) {
4344       InitList = true;
4345       Args = Init;
4346     }
4347 
4348     // Initialize the member.
4349     InitializedEntity MemberEntity =
4350       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4351                    : InitializedEntity::InitializeMember(IndirectMember,
4352                                                          nullptr);
4353     InitializationKind Kind =
4354         InitList ? InitializationKind::CreateDirectList(
4355                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4356                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4357                                                     InitRange.getEnd());
4358 
4359     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4360     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4361                                             nullptr);
4362     if (MemberInit.isInvalid())
4363       return true;
4364 
4365     // C++11 [class.base.init]p7:
4366     //   The initialization of each base and member constitutes a
4367     //   full-expression.
4368     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4369                                      /*DiscardedValue*/ false);
4370     if (MemberInit.isInvalid())
4371       return true;
4372 
4373     Init = MemberInit.get();
4374   }
4375 
4376   if (DirectMember) {
4377     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4378                                             InitRange.getBegin(), Init,
4379                                             InitRange.getEnd());
4380   } else {
4381     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4382                                             InitRange.getBegin(), Init,
4383                                             InitRange.getEnd());
4384   }
4385 }
4386 
4387 MemInitResult
4388 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4389                                  CXXRecordDecl *ClassDecl) {
4390   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4391   if (!LangOpts.CPlusPlus11)
4392     return Diag(NameLoc, diag::err_delegating_ctor)
4393       << TInfo->getTypeLoc().getLocalSourceRange();
4394   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4395 
4396   bool InitList = true;
4397   MultiExprArg Args = Init;
4398   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4399     InitList = false;
4400     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4401   }
4402 
4403   SourceRange InitRange = Init->getSourceRange();
4404   // Initialize the object.
4405   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4406                                      QualType(ClassDecl->getTypeForDecl(), 0));
4407   InitializationKind Kind =
4408       InitList ? InitializationKind::CreateDirectList(
4409                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4410                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4411                                                   InitRange.getEnd());
4412   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4413   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4414                                               Args, nullptr);
4415   if (DelegationInit.isInvalid())
4416     return true;
4417 
4418   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4419          "Delegating constructor with no target?");
4420 
4421   // C++11 [class.base.init]p7:
4422   //   The initialization of each base and member constitutes a
4423   //   full-expression.
4424   DelegationInit = ActOnFinishFullExpr(
4425       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4426   if (DelegationInit.isInvalid())
4427     return true;
4428 
4429   // If we are in a dependent context, template instantiation will
4430   // perform this type-checking again. Just save the arguments that we
4431   // received in a ParenListExpr.
4432   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4433   // of the information that we have about the base
4434   // initializer. However, deconstructing the ASTs is a dicey process,
4435   // and this approach is far more likely to get the corner cases right.
4436   if (CurContext->isDependentContext())
4437     DelegationInit = Init;
4438 
4439   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4440                                           DelegationInit.getAs<Expr>(),
4441                                           InitRange.getEnd());
4442 }
4443 
4444 MemInitResult
4445 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4446                            Expr *Init, CXXRecordDecl *ClassDecl,
4447                            SourceLocation EllipsisLoc) {
4448   SourceLocation BaseLoc
4449     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4450 
4451   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4452     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4453              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4454 
4455   // C++ [class.base.init]p2:
4456   //   [...] Unless the mem-initializer-id names a nonstatic data
4457   //   member of the constructor's class or a direct or virtual base
4458   //   of that class, the mem-initializer is ill-formed. A
4459   //   mem-initializer-list can initialize a base class using any
4460   //   name that denotes that base class type.
4461   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4462 
4463   SourceRange InitRange = Init->getSourceRange();
4464   if (EllipsisLoc.isValid()) {
4465     // This is a pack expansion.
4466     if (!BaseType->containsUnexpandedParameterPack())  {
4467       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4468         << SourceRange(BaseLoc, InitRange.getEnd());
4469 
4470       EllipsisLoc = SourceLocation();
4471     }
4472   } else {
4473     // Check for any unexpanded parameter packs.
4474     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4475       return true;
4476 
4477     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4478       return true;
4479   }
4480 
4481   // Check for direct and virtual base classes.
4482   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4483   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4484   if (!Dependent) {
4485     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4486                                        BaseType))
4487       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4488 
4489     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4490                         VirtualBaseSpec);
4491 
4492     // C++ [base.class.init]p2:
4493     // Unless the mem-initializer-id names a nonstatic data member of the
4494     // constructor's class or a direct or virtual base of that class, the
4495     // mem-initializer is ill-formed.
4496     if (!DirectBaseSpec && !VirtualBaseSpec) {
4497       // If the class has any dependent bases, then it's possible that
4498       // one of those types will resolve to the same type as
4499       // BaseType. Therefore, just treat this as a dependent base
4500       // class initialization.  FIXME: Should we try to check the
4501       // initialization anyway? It seems odd.
4502       if (ClassDecl->hasAnyDependentBases())
4503         Dependent = true;
4504       else
4505         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4506           << BaseType << Context.getTypeDeclType(ClassDecl)
4507           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4508     }
4509   }
4510 
4511   if (Dependent) {
4512     DiscardCleanupsInEvaluationContext();
4513 
4514     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4515                                             /*IsVirtual=*/false,
4516                                             InitRange.getBegin(), Init,
4517                                             InitRange.getEnd(), EllipsisLoc);
4518   }
4519 
4520   // C++ [base.class.init]p2:
4521   //   If a mem-initializer-id is ambiguous because it designates both
4522   //   a direct non-virtual base class and an inherited virtual base
4523   //   class, the mem-initializer is ill-formed.
4524   if (DirectBaseSpec && VirtualBaseSpec)
4525     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4526       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4527 
4528   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4529   if (!BaseSpec)
4530     BaseSpec = VirtualBaseSpec;
4531 
4532   // Initialize the base.
4533   bool InitList = true;
4534   MultiExprArg Args = Init;
4535   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4536     InitList = false;
4537     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4538   }
4539 
4540   InitializedEntity BaseEntity =
4541     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4542   InitializationKind Kind =
4543       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4544                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4545                                                   InitRange.getEnd());
4546   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4547   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4548   if (BaseInit.isInvalid())
4549     return true;
4550 
4551   // C++11 [class.base.init]p7:
4552   //   The initialization of each base and member constitutes a
4553   //   full-expression.
4554   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4555                                  /*DiscardedValue*/ false);
4556   if (BaseInit.isInvalid())
4557     return true;
4558 
4559   // If we are in a dependent context, template instantiation will
4560   // perform this type-checking again. Just save the arguments that we
4561   // received in a ParenListExpr.
4562   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4563   // of the information that we have about the base
4564   // initializer. However, deconstructing the ASTs is a dicey process,
4565   // and this approach is far more likely to get the corner cases right.
4566   if (CurContext->isDependentContext())
4567     BaseInit = Init;
4568 
4569   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4570                                           BaseSpec->isVirtual(),
4571                                           InitRange.getBegin(),
4572                                           BaseInit.getAs<Expr>(),
4573                                           InitRange.getEnd(), EllipsisLoc);
4574 }
4575 
4576 // Create a static_cast\<T&&>(expr).
4577 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4578   if (T.isNull()) T = E->getType();
4579   QualType TargetType = SemaRef.BuildReferenceType(
4580       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4581   SourceLocation ExprLoc = E->getBeginLoc();
4582   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4583       TargetType, ExprLoc);
4584 
4585   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4586                                    SourceRange(ExprLoc, ExprLoc),
4587                                    E->getSourceRange()).get();
4588 }
4589 
4590 /// ImplicitInitializerKind - How an implicit base or member initializer should
4591 /// initialize its base or member.
4592 enum ImplicitInitializerKind {
4593   IIK_Default,
4594   IIK_Copy,
4595   IIK_Move,
4596   IIK_Inherit
4597 };
4598 
4599 static bool
4600 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4601                              ImplicitInitializerKind ImplicitInitKind,
4602                              CXXBaseSpecifier *BaseSpec,
4603                              bool IsInheritedVirtualBase,
4604                              CXXCtorInitializer *&CXXBaseInit) {
4605   InitializedEntity InitEntity
4606     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4607                                         IsInheritedVirtualBase);
4608 
4609   ExprResult BaseInit;
4610 
4611   switch (ImplicitInitKind) {
4612   case IIK_Inherit:
4613   case IIK_Default: {
4614     InitializationKind InitKind
4615       = InitializationKind::CreateDefault(Constructor->getLocation());
4616     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4617     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4618     break;
4619   }
4620 
4621   case IIK_Move:
4622   case IIK_Copy: {
4623     bool Moving = ImplicitInitKind == IIK_Move;
4624     ParmVarDecl *Param = Constructor->getParamDecl(0);
4625     QualType ParamType = Param->getType().getNonReferenceType();
4626 
4627     Expr *CopyCtorArg =
4628       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4629                           SourceLocation(), Param, false,
4630                           Constructor->getLocation(), ParamType,
4631                           VK_LValue, nullptr);
4632 
4633     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4634 
4635     // Cast to the base class to avoid ambiguities.
4636     QualType ArgTy =
4637       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4638                                        ParamType.getQualifiers());
4639 
4640     if (Moving) {
4641       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4642     }
4643 
4644     CXXCastPath BasePath;
4645     BasePath.push_back(BaseSpec);
4646     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4647                                             CK_UncheckedDerivedToBase,
4648                                             Moving ? VK_XValue : VK_LValue,
4649                                             &BasePath).get();
4650 
4651     InitializationKind InitKind
4652       = InitializationKind::CreateDirect(Constructor->getLocation(),
4653                                          SourceLocation(), SourceLocation());
4654     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4655     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4656     break;
4657   }
4658   }
4659 
4660   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4661   if (BaseInit.isInvalid())
4662     return true;
4663 
4664   CXXBaseInit =
4665     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4666                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4667                                                         SourceLocation()),
4668                                              BaseSpec->isVirtual(),
4669                                              SourceLocation(),
4670                                              BaseInit.getAs<Expr>(),
4671                                              SourceLocation(),
4672                                              SourceLocation());
4673 
4674   return false;
4675 }
4676 
4677 static bool RefersToRValueRef(Expr *MemRef) {
4678   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4679   return Referenced->getType()->isRValueReferenceType();
4680 }
4681 
4682 static bool
4683 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4684                                ImplicitInitializerKind ImplicitInitKind,
4685                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4686                                CXXCtorInitializer *&CXXMemberInit) {
4687   if (Field->isInvalidDecl())
4688     return true;
4689 
4690   SourceLocation Loc = Constructor->getLocation();
4691 
4692   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4693     bool Moving = ImplicitInitKind == IIK_Move;
4694     ParmVarDecl *Param = Constructor->getParamDecl(0);
4695     QualType ParamType = Param->getType().getNonReferenceType();
4696 
4697     // Suppress copying zero-width bitfields.
4698     if (Field->isZeroLengthBitField(SemaRef.Context))
4699       return false;
4700 
4701     Expr *MemberExprBase =
4702       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4703                           SourceLocation(), Param, false,
4704                           Loc, ParamType, VK_LValue, nullptr);
4705 
4706     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4707 
4708     if (Moving) {
4709       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4710     }
4711 
4712     // Build a reference to this field within the parameter.
4713     CXXScopeSpec SS;
4714     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4715                               Sema::LookupMemberName);
4716     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4717                                   : cast<ValueDecl>(Field), AS_public);
4718     MemberLookup.resolveKind();
4719     ExprResult CtorArg
4720       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4721                                          ParamType, Loc,
4722                                          /*IsArrow=*/false,
4723                                          SS,
4724                                          /*TemplateKWLoc=*/SourceLocation(),
4725                                          /*FirstQualifierInScope=*/nullptr,
4726                                          MemberLookup,
4727                                          /*TemplateArgs=*/nullptr,
4728                                          /*S*/nullptr);
4729     if (CtorArg.isInvalid())
4730       return true;
4731 
4732     // C++11 [class.copy]p15:
4733     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4734     //     with static_cast<T&&>(x.m);
4735     if (RefersToRValueRef(CtorArg.get())) {
4736       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4737     }
4738 
4739     InitializedEntity Entity =
4740         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4741                                                        /*Implicit*/ true)
4742                  : InitializedEntity::InitializeMember(Field, nullptr,
4743                                                        /*Implicit*/ true);
4744 
4745     // Direct-initialize to use the copy constructor.
4746     InitializationKind InitKind =
4747       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4748 
4749     Expr *CtorArgE = CtorArg.getAs<Expr>();
4750     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4751     ExprResult MemberInit =
4752         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4753     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4754     if (MemberInit.isInvalid())
4755       return true;
4756 
4757     if (Indirect)
4758       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4759           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4760     else
4761       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4762           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4763     return false;
4764   }
4765 
4766   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4767          "Unhandled implicit init kind!");
4768 
4769   QualType FieldBaseElementType =
4770     SemaRef.Context.getBaseElementType(Field->getType());
4771 
4772   if (FieldBaseElementType->isRecordType()) {
4773     InitializedEntity InitEntity =
4774         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4775                                                        /*Implicit*/ true)
4776                  : InitializedEntity::InitializeMember(Field, nullptr,
4777                                                        /*Implicit*/ true);
4778     InitializationKind InitKind =
4779       InitializationKind::CreateDefault(Loc);
4780 
4781     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4782     ExprResult MemberInit =
4783       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4784 
4785     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4786     if (MemberInit.isInvalid())
4787       return true;
4788 
4789     if (Indirect)
4790       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4791                                                                Indirect, Loc,
4792                                                                Loc,
4793                                                                MemberInit.get(),
4794                                                                Loc);
4795     else
4796       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4797                                                                Field, Loc, Loc,
4798                                                                MemberInit.get(),
4799                                                                Loc);
4800     return false;
4801   }
4802 
4803   if (!Field->getParent()->isUnion()) {
4804     if (FieldBaseElementType->isReferenceType()) {
4805       SemaRef.Diag(Constructor->getLocation(),
4806                    diag::err_uninitialized_member_in_ctor)
4807       << (int)Constructor->isImplicit()
4808       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4809       << 0 << Field->getDeclName();
4810       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4811       return true;
4812     }
4813 
4814     if (FieldBaseElementType.isConstQualified()) {
4815       SemaRef.Diag(Constructor->getLocation(),
4816                    diag::err_uninitialized_member_in_ctor)
4817       << (int)Constructor->isImplicit()
4818       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4819       << 1 << Field->getDeclName();
4820       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4821       return true;
4822     }
4823   }
4824 
4825   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4826     // ARC and Weak:
4827     //   Default-initialize Objective-C pointers to NULL.
4828     CXXMemberInit
4829       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4830                                                  Loc, Loc,
4831                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4832                                                  Loc);
4833     return false;
4834   }
4835 
4836   // Nothing to initialize.
4837   CXXMemberInit = nullptr;
4838   return false;
4839 }
4840 
4841 namespace {
4842 struct BaseAndFieldInfo {
4843   Sema &S;
4844   CXXConstructorDecl *Ctor;
4845   bool AnyErrorsInInits;
4846   ImplicitInitializerKind IIK;
4847   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4848   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4849   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4850 
4851   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4852     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4853     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4854     if (Ctor->getInheritedConstructor())
4855       IIK = IIK_Inherit;
4856     else if (Generated && Ctor->isCopyConstructor())
4857       IIK = IIK_Copy;
4858     else if (Generated && Ctor->isMoveConstructor())
4859       IIK = IIK_Move;
4860     else
4861       IIK = IIK_Default;
4862   }
4863 
4864   bool isImplicitCopyOrMove() const {
4865     switch (IIK) {
4866     case IIK_Copy:
4867     case IIK_Move:
4868       return true;
4869 
4870     case IIK_Default:
4871     case IIK_Inherit:
4872       return false;
4873     }
4874 
4875     llvm_unreachable("Invalid ImplicitInitializerKind!");
4876   }
4877 
4878   bool addFieldInitializer(CXXCtorInitializer *Init) {
4879     AllToInit.push_back(Init);
4880 
4881     // Check whether this initializer makes the field "used".
4882     if (Init->getInit()->HasSideEffects(S.Context))
4883       S.UnusedPrivateFields.remove(Init->getAnyMember());
4884 
4885     return false;
4886   }
4887 
4888   bool isInactiveUnionMember(FieldDecl *Field) {
4889     RecordDecl *Record = Field->getParent();
4890     if (!Record->isUnion())
4891       return false;
4892 
4893     if (FieldDecl *Active =
4894             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4895       return Active != Field->getCanonicalDecl();
4896 
4897     // In an implicit copy or move constructor, ignore any in-class initializer.
4898     if (isImplicitCopyOrMove())
4899       return true;
4900 
4901     // If there's no explicit initialization, the field is active only if it
4902     // has an in-class initializer...
4903     if (Field->hasInClassInitializer())
4904       return false;
4905     // ... or it's an anonymous struct or union whose class has an in-class
4906     // initializer.
4907     if (!Field->isAnonymousStructOrUnion())
4908       return true;
4909     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4910     return !FieldRD->hasInClassInitializer();
4911   }
4912 
4913   /// Determine whether the given field is, or is within, a union member
4914   /// that is inactive (because there was an initializer given for a different
4915   /// member of the union, or because the union was not initialized at all).
4916   bool isWithinInactiveUnionMember(FieldDecl *Field,
4917                                    IndirectFieldDecl *Indirect) {
4918     if (!Indirect)
4919       return isInactiveUnionMember(Field);
4920 
4921     for (auto *C : Indirect->chain()) {
4922       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4923       if (Field && isInactiveUnionMember(Field))
4924         return true;
4925     }
4926     return false;
4927   }
4928 };
4929 }
4930 
4931 /// Determine whether the given type is an incomplete or zero-lenfgth
4932 /// array type.
4933 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4934   if (T->isIncompleteArrayType())
4935     return true;
4936 
4937   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4938     if (!ArrayT->getSize())
4939       return true;
4940 
4941     T = ArrayT->getElementType();
4942   }
4943 
4944   return false;
4945 }
4946 
4947 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4948                                     FieldDecl *Field,
4949                                     IndirectFieldDecl *Indirect = nullptr) {
4950   if (Field->isInvalidDecl())
4951     return false;
4952 
4953   // Overwhelmingly common case: we have a direct initializer for this field.
4954   if (CXXCtorInitializer *Init =
4955           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4956     return Info.addFieldInitializer(Init);
4957 
4958   // C++11 [class.base.init]p8:
4959   //   if the entity is a non-static data member that has a
4960   //   brace-or-equal-initializer and either
4961   //   -- the constructor's class is a union and no other variant member of that
4962   //      union is designated by a mem-initializer-id or
4963   //   -- the constructor's class is not a union, and, if the entity is a member
4964   //      of an anonymous union, no other member of that union is designated by
4965   //      a mem-initializer-id,
4966   //   the entity is initialized as specified in [dcl.init].
4967   //
4968   // We also apply the same rules to handle anonymous structs within anonymous
4969   // unions.
4970   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4971     return false;
4972 
4973   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4974     ExprResult DIE =
4975         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4976     if (DIE.isInvalid())
4977       return true;
4978 
4979     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4980     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4981 
4982     CXXCtorInitializer *Init;
4983     if (Indirect)
4984       Init = new (SemaRef.Context)
4985           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4986                              SourceLocation(), DIE.get(), SourceLocation());
4987     else
4988       Init = new (SemaRef.Context)
4989           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4990                              SourceLocation(), DIE.get(), SourceLocation());
4991     return Info.addFieldInitializer(Init);
4992   }
4993 
4994   // Don't initialize incomplete or zero-length arrays.
4995   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4996     return false;
4997 
4998   // Don't try to build an implicit initializer if there were semantic
4999   // errors in any of the initializers (and therefore we might be
5000   // missing some that the user actually wrote).
5001   if (Info.AnyErrorsInInits)
5002     return false;
5003 
5004   CXXCtorInitializer *Init = nullptr;
5005   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5006                                      Indirect, Init))
5007     return true;
5008 
5009   if (!Init)
5010     return false;
5011 
5012   return Info.addFieldInitializer(Init);
5013 }
5014 
5015 bool
5016 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5017                                CXXCtorInitializer *Initializer) {
5018   assert(Initializer->isDelegatingInitializer());
5019   Constructor->setNumCtorInitializers(1);
5020   CXXCtorInitializer **initializer =
5021     new (Context) CXXCtorInitializer*[1];
5022   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5023   Constructor->setCtorInitializers(initializer);
5024 
5025   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5026     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5027     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5028   }
5029 
5030   DelegatingCtorDecls.push_back(Constructor);
5031 
5032   DiagnoseUninitializedFields(*this, Constructor);
5033 
5034   return false;
5035 }
5036 
5037 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5038                                ArrayRef<CXXCtorInitializer *> Initializers) {
5039   if (Constructor->isDependentContext()) {
5040     // Just store the initializers as written, they will be checked during
5041     // instantiation.
5042     if (!Initializers.empty()) {
5043       Constructor->setNumCtorInitializers(Initializers.size());
5044       CXXCtorInitializer **baseOrMemberInitializers =
5045         new (Context) CXXCtorInitializer*[Initializers.size()];
5046       memcpy(baseOrMemberInitializers, Initializers.data(),
5047              Initializers.size() * sizeof(CXXCtorInitializer*));
5048       Constructor->setCtorInitializers(baseOrMemberInitializers);
5049     }
5050 
5051     // Let template instantiation know whether we had errors.
5052     if (AnyErrors)
5053       Constructor->setInvalidDecl();
5054 
5055     return false;
5056   }
5057 
5058   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5059 
5060   // We need to build the initializer AST according to order of construction
5061   // and not what user specified in the Initializers list.
5062   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5063   if (!ClassDecl)
5064     return true;
5065 
5066   bool HadError = false;
5067 
5068   for (unsigned i = 0; i < Initializers.size(); i++) {
5069     CXXCtorInitializer *Member = Initializers[i];
5070 
5071     if (Member->isBaseInitializer())
5072       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5073     else {
5074       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5075 
5076       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5077         for (auto *C : F->chain()) {
5078           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5079           if (FD && FD->getParent()->isUnion())
5080             Info.ActiveUnionMember.insert(std::make_pair(
5081                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5082         }
5083       } else if (FieldDecl *FD = Member->getMember()) {
5084         if (FD->getParent()->isUnion())
5085           Info.ActiveUnionMember.insert(std::make_pair(
5086               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5087       }
5088     }
5089   }
5090 
5091   // Keep track of the direct virtual bases.
5092   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5093   for (auto &I : ClassDecl->bases()) {
5094     if (I.isVirtual())
5095       DirectVBases.insert(&I);
5096   }
5097 
5098   // Push virtual bases before others.
5099   for (auto &VBase : ClassDecl->vbases()) {
5100     if (CXXCtorInitializer *Value
5101         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5102       // [class.base.init]p7, per DR257:
5103       //   A mem-initializer where the mem-initializer-id names a virtual base
5104       //   class is ignored during execution of a constructor of any class that
5105       //   is not the most derived class.
5106       if (ClassDecl->isAbstract()) {
5107         // FIXME: Provide a fixit to remove the base specifier. This requires
5108         // tracking the location of the associated comma for a base specifier.
5109         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5110           << VBase.getType() << ClassDecl;
5111         DiagnoseAbstractType(ClassDecl);
5112       }
5113 
5114       Info.AllToInit.push_back(Value);
5115     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5116       // [class.base.init]p8, per DR257:
5117       //   If a given [...] base class is not named by a mem-initializer-id
5118       //   [...] and the entity is not a virtual base class of an abstract
5119       //   class, then [...] the entity is default-initialized.
5120       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5121       CXXCtorInitializer *CXXBaseInit;
5122       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5123                                        &VBase, IsInheritedVirtualBase,
5124                                        CXXBaseInit)) {
5125         HadError = true;
5126         continue;
5127       }
5128 
5129       Info.AllToInit.push_back(CXXBaseInit);
5130     }
5131   }
5132 
5133   // Non-virtual bases.
5134   for (auto &Base : ClassDecl->bases()) {
5135     // Virtuals are in the virtual base list and already constructed.
5136     if (Base.isVirtual())
5137       continue;
5138 
5139     if (CXXCtorInitializer *Value
5140           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5141       Info.AllToInit.push_back(Value);
5142     } else if (!AnyErrors) {
5143       CXXCtorInitializer *CXXBaseInit;
5144       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5145                                        &Base, /*IsInheritedVirtualBase=*/false,
5146                                        CXXBaseInit)) {
5147         HadError = true;
5148         continue;
5149       }
5150 
5151       Info.AllToInit.push_back(CXXBaseInit);
5152     }
5153   }
5154 
5155   // Fields.
5156   for (auto *Mem : ClassDecl->decls()) {
5157     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5158       // C++ [class.bit]p2:
5159       //   A declaration for a bit-field that omits the identifier declares an
5160       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5161       //   initialized.
5162       if (F->isUnnamedBitfield())
5163         continue;
5164 
5165       // If we're not generating the implicit copy/move constructor, then we'll
5166       // handle anonymous struct/union fields based on their individual
5167       // indirect fields.
5168       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5169         continue;
5170 
5171       if (CollectFieldInitializer(*this, Info, F))
5172         HadError = true;
5173       continue;
5174     }
5175 
5176     // Beyond this point, we only consider default initialization.
5177     if (Info.isImplicitCopyOrMove())
5178       continue;
5179 
5180     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5181       if (F->getType()->isIncompleteArrayType()) {
5182         assert(ClassDecl->hasFlexibleArrayMember() &&
5183                "Incomplete array type is not valid");
5184         continue;
5185       }
5186 
5187       // Initialize each field of an anonymous struct individually.
5188       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5189         HadError = true;
5190 
5191       continue;
5192     }
5193   }
5194 
5195   unsigned NumInitializers = Info.AllToInit.size();
5196   if (NumInitializers > 0) {
5197     Constructor->setNumCtorInitializers(NumInitializers);
5198     CXXCtorInitializer **baseOrMemberInitializers =
5199       new (Context) CXXCtorInitializer*[NumInitializers];
5200     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5201            NumInitializers * sizeof(CXXCtorInitializer*));
5202     Constructor->setCtorInitializers(baseOrMemberInitializers);
5203 
5204     // Constructors implicitly reference the base and member
5205     // destructors.
5206     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5207                                            Constructor->getParent());
5208   }
5209 
5210   return HadError;
5211 }
5212 
5213 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5214   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5215     const RecordDecl *RD = RT->getDecl();
5216     if (RD->isAnonymousStructOrUnion()) {
5217       for (auto *Field : RD->fields())
5218         PopulateKeysForFields(Field, IdealInits);
5219       return;
5220     }
5221   }
5222   IdealInits.push_back(Field->getCanonicalDecl());
5223 }
5224 
5225 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5226   return Context.getCanonicalType(BaseType).getTypePtr();
5227 }
5228 
5229 static const void *GetKeyForMember(ASTContext &Context,
5230                                    CXXCtorInitializer *Member) {
5231   if (!Member->isAnyMemberInitializer())
5232     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5233 
5234   return Member->getAnyMember()->getCanonicalDecl();
5235 }
5236 
5237 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5238                                  const CXXCtorInitializer *Previous,
5239                                  const CXXCtorInitializer *Current) {
5240   if (Previous->isAnyMemberInitializer())
5241     Diag << 0 << Previous->getAnyMember();
5242   else
5243     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5244 
5245   if (Current->isAnyMemberInitializer())
5246     Diag << 0 << Current->getAnyMember();
5247   else
5248     Diag << 1 << Current->getTypeSourceInfo()->getType();
5249 }
5250 
5251 static void DiagnoseBaseOrMemInitializerOrder(
5252     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5253     ArrayRef<CXXCtorInitializer *> Inits) {
5254   if (Constructor->getDeclContext()->isDependentContext())
5255     return;
5256 
5257   // Don't check initializers order unless the warning is enabled at the
5258   // location of at least one initializer.
5259   bool ShouldCheckOrder = false;
5260   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5261     CXXCtorInitializer *Init = Inits[InitIndex];
5262     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5263                                  Init->getSourceLocation())) {
5264       ShouldCheckOrder = true;
5265       break;
5266     }
5267   }
5268   if (!ShouldCheckOrder)
5269     return;
5270 
5271   // Build the list of bases and members in the order that they'll
5272   // actually be initialized.  The explicit initializers should be in
5273   // this same order but may be missing things.
5274   SmallVector<const void*, 32> IdealInitKeys;
5275 
5276   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5277 
5278   // 1. Virtual bases.
5279   for (const auto &VBase : ClassDecl->vbases())
5280     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5281 
5282   // 2. Non-virtual bases.
5283   for (const auto &Base : ClassDecl->bases()) {
5284     if (Base.isVirtual())
5285       continue;
5286     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5287   }
5288 
5289   // 3. Direct fields.
5290   for (auto *Field : ClassDecl->fields()) {
5291     if (Field->isUnnamedBitfield())
5292       continue;
5293 
5294     PopulateKeysForFields(Field, IdealInitKeys);
5295   }
5296 
5297   unsigned NumIdealInits = IdealInitKeys.size();
5298   unsigned IdealIndex = 0;
5299 
5300   // Track initializers that are in an incorrect order for either a warning or
5301   // note if multiple ones occur.
5302   SmallVector<unsigned> WarnIndexes;
5303   // Correlates the index of an initializer in the init-list to the index of
5304   // the field/base in the class.
5305   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5306 
5307   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5308     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5309 
5310     // Scan forward to try to find this initializer in the idealized
5311     // initializers list.
5312     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5313       if (InitKey == IdealInitKeys[IdealIndex])
5314         break;
5315 
5316     // If we didn't find this initializer, it must be because we
5317     // scanned past it on a previous iteration.  That can only
5318     // happen if we're out of order;  emit a warning.
5319     if (IdealIndex == NumIdealInits && InitIndex) {
5320       WarnIndexes.push_back(InitIndex);
5321 
5322       // Move back to the initializer's location in the ideal list.
5323       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5324         if (InitKey == IdealInitKeys[IdealIndex])
5325           break;
5326 
5327       assert(IdealIndex < NumIdealInits &&
5328              "initializer not found in initializer list");
5329     }
5330     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5331   }
5332 
5333   if (WarnIndexes.empty())
5334     return;
5335 
5336   // Sort based on the ideal order, first in the pair.
5337   llvm::sort(CorrelatedInitOrder,
5338              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5339 
5340   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5341   // emit the diagnostic before we can try adding notes.
5342   {
5343     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5344         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5345         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5346                                 : diag::warn_some_initializers_out_of_order);
5347 
5348     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5349       if (CorrelatedInitOrder[I].second == I)
5350         continue;
5351       // Ideally we would be using InsertFromRange here, but clang doesn't
5352       // appear to handle InsertFromRange correctly when the source range is
5353       // modified by another fix-it.
5354       D << FixItHint::CreateReplacement(
5355           Inits[I]->getSourceRange(),
5356           Lexer::getSourceText(
5357               CharSourceRange::getTokenRange(
5358                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5359               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5360     }
5361 
5362     // If there is only 1 item out of order, the warning expects the name and
5363     // type of each being added to it.
5364     if (WarnIndexes.size() == 1) {
5365       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5366                            Inits[WarnIndexes.front()]);
5367       return;
5368     }
5369   }
5370   // More than 1 item to warn, create notes letting the user know which ones
5371   // are bad.
5372   for (unsigned WarnIndex : WarnIndexes) {
5373     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5374     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5375                           diag::note_initializer_out_of_order);
5376     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5377     D << PrevInit->getSourceRange();
5378   }
5379 }
5380 
5381 namespace {
5382 bool CheckRedundantInit(Sema &S,
5383                         CXXCtorInitializer *Init,
5384                         CXXCtorInitializer *&PrevInit) {
5385   if (!PrevInit) {
5386     PrevInit = Init;
5387     return false;
5388   }
5389 
5390   if (FieldDecl *Field = Init->getAnyMember())
5391     S.Diag(Init->getSourceLocation(),
5392            diag::err_multiple_mem_initialization)
5393       << Field->getDeclName()
5394       << Init->getSourceRange();
5395   else {
5396     const Type *BaseClass = Init->getBaseClass();
5397     assert(BaseClass && "neither field nor base");
5398     S.Diag(Init->getSourceLocation(),
5399            diag::err_multiple_base_initialization)
5400       << QualType(BaseClass, 0)
5401       << Init->getSourceRange();
5402   }
5403   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5404     << 0 << PrevInit->getSourceRange();
5405 
5406   return true;
5407 }
5408 
5409 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5410 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5411 
5412 bool CheckRedundantUnionInit(Sema &S,
5413                              CXXCtorInitializer *Init,
5414                              RedundantUnionMap &Unions) {
5415   FieldDecl *Field = Init->getAnyMember();
5416   RecordDecl *Parent = Field->getParent();
5417   NamedDecl *Child = Field;
5418 
5419   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5420     if (Parent->isUnion()) {
5421       UnionEntry &En = Unions[Parent];
5422       if (En.first && En.first != Child) {
5423         S.Diag(Init->getSourceLocation(),
5424                diag::err_multiple_mem_union_initialization)
5425           << Field->getDeclName()
5426           << Init->getSourceRange();
5427         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5428           << 0 << En.second->getSourceRange();
5429         return true;
5430       }
5431       if (!En.first) {
5432         En.first = Child;
5433         En.second = Init;
5434       }
5435       if (!Parent->isAnonymousStructOrUnion())
5436         return false;
5437     }
5438 
5439     Child = Parent;
5440     Parent = cast<RecordDecl>(Parent->getDeclContext());
5441   }
5442 
5443   return false;
5444 }
5445 } // namespace
5446 
5447 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5448 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5449                                 SourceLocation ColonLoc,
5450                                 ArrayRef<CXXCtorInitializer*> MemInits,
5451                                 bool AnyErrors) {
5452   if (!ConstructorDecl)
5453     return;
5454 
5455   AdjustDeclIfTemplate(ConstructorDecl);
5456 
5457   CXXConstructorDecl *Constructor
5458     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5459 
5460   if (!Constructor) {
5461     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5462     return;
5463   }
5464 
5465   // Mapping for the duplicate initializers check.
5466   // For member initializers, this is keyed with a FieldDecl*.
5467   // For base initializers, this is keyed with a Type*.
5468   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5469 
5470   // Mapping for the inconsistent anonymous-union initializers check.
5471   RedundantUnionMap MemberUnions;
5472 
5473   bool HadError = false;
5474   for (unsigned i = 0; i < MemInits.size(); i++) {
5475     CXXCtorInitializer *Init = MemInits[i];
5476 
5477     // Set the source order index.
5478     Init->setSourceOrder(i);
5479 
5480     if (Init->isAnyMemberInitializer()) {
5481       const void *Key = GetKeyForMember(Context, Init);
5482       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5483           CheckRedundantUnionInit(*this, Init, MemberUnions))
5484         HadError = true;
5485     } else if (Init->isBaseInitializer()) {
5486       const void *Key = GetKeyForMember(Context, Init);
5487       if (CheckRedundantInit(*this, Init, Members[Key]))
5488         HadError = true;
5489     } else {
5490       assert(Init->isDelegatingInitializer());
5491       // This must be the only initializer
5492       if (MemInits.size() != 1) {
5493         Diag(Init->getSourceLocation(),
5494              diag::err_delegating_initializer_alone)
5495           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5496         // We will treat this as being the only initializer.
5497       }
5498       SetDelegatingInitializer(Constructor, MemInits[i]);
5499       // Return immediately as the initializer is set.
5500       return;
5501     }
5502   }
5503 
5504   if (HadError)
5505     return;
5506 
5507   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5508 
5509   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5510 
5511   DiagnoseUninitializedFields(*this, Constructor);
5512 }
5513 
5514 void
5515 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5516                                              CXXRecordDecl *ClassDecl) {
5517   // Ignore dependent contexts. Also ignore unions, since their members never
5518   // have destructors implicitly called.
5519   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5520     return;
5521 
5522   // FIXME: all the access-control diagnostics are positioned on the
5523   // field/base declaration.  That's probably good; that said, the
5524   // user might reasonably want to know why the destructor is being
5525   // emitted, and we currently don't say.
5526 
5527   // Non-static data members.
5528   for (auto *Field : ClassDecl->fields()) {
5529     if (Field->isInvalidDecl())
5530       continue;
5531 
5532     // Don't destroy incomplete or zero-length arrays.
5533     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5534       continue;
5535 
5536     QualType FieldType = Context.getBaseElementType(Field->getType());
5537 
5538     const RecordType* RT = FieldType->getAs<RecordType>();
5539     if (!RT)
5540       continue;
5541 
5542     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5543     if (FieldClassDecl->isInvalidDecl())
5544       continue;
5545     if (FieldClassDecl->hasIrrelevantDestructor())
5546       continue;
5547     // The destructor for an implicit anonymous union member is never invoked.
5548     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5549       continue;
5550 
5551     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5552     assert(Dtor && "No dtor found for FieldClassDecl!");
5553     CheckDestructorAccess(Field->getLocation(), Dtor,
5554                           PDiag(diag::err_access_dtor_field)
5555                             << Field->getDeclName()
5556                             << FieldType);
5557 
5558     MarkFunctionReferenced(Location, Dtor);
5559     DiagnoseUseOfDecl(Dtor, Location);
5560   }
5561 
5562   // We only potentially invoke the destructors of potentially constructed
5563   // subobjects.
5564   bool VisitVirtualBases = !ClassDecl->isAbstract();
5565 
5566   // If the destructor exists and has already been marked used in the MS ABI,
5567   // then virtual base destructors have already been checked and marked used.
5568   // Skip checking them again to avoid duplicate diagnostics.
5569   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5570     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5571     if (Dtor && Dtor->isUsed())
5572       VisitVirtualBases = false;
5573   }
5574 
5575   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5576 
5577   // Bases.
5578   for (const auto &Base : ClassDecl->bases()) {
5579     const RecordType *RT = Base.getType()->getAs<RecordType>();
5580     if (!RT)
5581       continue;
5582 
5583     // Remember direct virtual bases.
5584     if (Base.isVirtual()) {
5585       if (!VisitVirtualBases)
5586         continue;
5587       DirectVirtualBases.insert(RT);
5588     }
5589 
5590     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5591     // If our base class is invalid, we probably can't get its dtor anyway.
5592     if (BaseClassDecl->isInvalidDecl())
5593       continue;
5594     if (BaseClassDecl->hasIrrelevantDestructor())
5595       continue;
5596 
5597     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5598     assert(Dtor && "No dtor found for BaseClassDecl!");
5599 
5600     // FIXME: caret should be on the start of the class name
5601     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5602                           PDiag(diag::err_access_dtor_base)
5603                               << Base.getType() << Base.getSourceRange(),
5604                           Context.getTypeDeclType(ClassDecl));
5605 
5606     MarkFunctionReferenced(Location, Dtor);
5607     DiagnoseUseOfDecl(Dtor, Location);
5608   }
5609 
5610   if (VisitVirtualBases)
5611     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5612                                          &DirectVirtualBases);
5613 }
5614 
5615 void Sema::MarkVirtualBaseDestructorsReferenced(
5616     SourceLocation Location, CXXRecordDecl *ClassDecl,
5617     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5618   // Virtual bases.
5619   for (const auto &VBase : ClassDecl->vbases()) {
5620     // Bases are always records in a well-formed non-dependent class.
5621     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5622 
5623     // Ignore already visited direct virtual bases.
5624     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5625       continue;
5626 
5627     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5628     // If our base class is invalid, we probably can't get its dtor anyway.
5629     if (BaseClassDecl->isInvalidDecl())
5630       continue;
5631     if (BaseClassDecl->hasIrrelevantDestructor())
5632       continue;
5633 
5634     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5635     assert(Dtor && "No dtor found for BaseClassDecl!");
5636     if (CheckDestructorAccess(
5637             ClassDecl->getLocation(), Dtor,
5638             PDiag(diag::err_access_dtor_vbase)
5639                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5640             Context.getTypeDeclType(ClassDecl)) ==
5641         AR_accessible) {
5642       CheckDerivedToBaseConversion(
5643           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5644           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5645           SourceRange(), DeclarationName(), nullptr);
5646     }
5647 
5648     MarkFunctionReferenced(Location, Dtor);
5649     DiagnoseUseOfDecl(Dtor, Location);
5650   }
5651 }
5652 
5653 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5654   if (!CDtorDecl)
5655     return;
5656 
5657   if (CXXConstructorDecl *Constructor
5658       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5659     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5660     DiagnoseUninitializedFields(*this, Constructor);
5661   }
5662 }
5663 
5664 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5665   if (!getLangOpts().CPlusPlus)
5666     return false;
5667 
5668   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5669   if (!RD)
5670     return false;
5671 
5672   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5673   // class template specialization here, but doing so breaks a lot of code.
5674 
5675   // We can't answer whether something is abstract until it has a
5676   // definition. If it's currently being defined, we'll walk back
5677   // over all the declarations when we have a full definition.
5678   const CXXRecordDecl *Def = RD->getDefinition();
5679   if (!Def || Def->isBeingDefined())
5680     return false;
5681 
5682   return RD->isAbstract();
5683 }
5684 
5685 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5686                                   TypeDiagnoser &Diagnoser) {
5687   if (!isAbstractType(Loc, T))
5688     return false;
5689 
5690   T = Context.getBaseElementType(T);
5691   Diagnoser.diagnose(*this, Loc, T);
5692   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5693   return true;
5694 }
5695 
5696 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5697   // Check if we've already emitted the list of pure virtual functions
5698   // for this class.
5699   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5700     return;
5701 
5702   // If the diagnostic is suppressed, don't emit the notes. We're only
5703   // going to emit them once, so try to attach them to a diagnostic we're
5704   // actually going to show.
5705   if (Diags.isLastDiagnosticIgnored())
5706     return;
5707 
5708   CXXFinalOverriderMap FinalOverriders;
5709   RD->getFinalOverriders(FinalOverriders);
5710 
5711   // Keep a set of seen pure methods so we won't diagnose the same method
5712   // more than once.
5713   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5714 
5715   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5716                                    MEnd = FinalOverriders.end();
5717        M != MEnd;
5718        ++M) {
5719     for (OverridingMethods::iterator SO = M->second.begin(),
5720                                   SOEnd = M->second.end();
5721          SO != SOEnd; ++SO) {
5722       // C++ [class.abstract]p4:
5723       //   A class is abstract if it contains or inherits at least one
5724       //   pure virtual function for which the final overrider is pure
5725       //   virtual.
5726 
5727       //
5728       if (SO->second.size() != 1)
5729         continue;
5730 
5731       if (!SO->second.front().Method->isPure())
5732         continue;
5733 
5734       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5735         continue;
5736 
5737       Diag(SO->second.front().Method->getLocation(),
5738            diag::note_pure_virtual_function)
5739         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5740     }
5741   }
5742 
5743   if (!PureVirtualClassDiagSet)
5744     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5745   PureVirtualClassDiagSet->insert(RD);
5746 }
5747 
5748 namespace {
5749 struct AbstractUsageInfo {
5750   Sema &S;
5751   CXXRecordDecl *Record;
5752   CanQualType AbstractType;
5753   bool Invalid;
5754 
5755   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5756     : S(S), Record(Record),
5757       AbstractType(S.Context.getCanonicalType(
5758                    S.Context.getTypeDeclType(Record))),
5759       Invalid(false) {}
5760 
5761   void DiagnoseAbstractType() {
5762     if (Invalid) return;
5763     S.DiagnoseAbstractType(Record);
5764     Invalid = true;
5765   }
5766 
5767   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5768 };
5769 
5770 struct CheckAbstractUsage {
5771   AbstractUsageInfo &Info;
5772   const NamedDecl *Ctx;
5773 
5774   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5775     : Info(Info), Ctx(Ctx) {}
5776 
5777   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5778     switch (TL.getTypeLocClass()) {
5779 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5780 #define TYPELOC(CLASS, PARENT) \
5781     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5782 #include "clang/AST/TypeLocNodes.def"
5783     }
5784   }
5785 
5786   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5787     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5788     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5789       if (!TL.getParam(I))
5790         continue;
5791 
5792       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5793       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5794     }
5795   }
5796 
5797   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5798     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5799   }
5800 
5801   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5802     // Visit the type parameters from a permissive context.
5803     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5804       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5805       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5806         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5807           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5808       // TODO: other template argument types?
5809     }
5810   }
5811 
5812   // Visit pointee types from a permissive context.
5813 #define CheckPolymorphic(Type) \
5814   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5815     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5816   }
5817   CheckPolymorphic(PointerTypeLoc)
5818   CheckPolymorphic(ReferenceTypeLoc)
5819   CheckPolymorphic(MemberPointerTypeLoc)
5820   CheckPolymorphic(BlockPointerTypeLoc)
5821   CheckPolymorphic(AtomicTypeLoc)
5822 
5823   /// Handle all the types we haven't given a more specific
5824   /// implementation for above.
5825   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5826     // Every other kind of type that we haven't called out already
5827     // that has an inner type is either (1) sugar or (2) contains that
5828     // inner type in some way as a subobject.
5829     if (TypeLoc Next = TL.getNextTypeLoc())
5830       return Visit(Next, Sel);
5831 
5832     // If there's no inner type and we're in a permissive context,
5833     // don't diagnose.
5834     if (Sel == Sema::AbstractNone) return;
5835 
5836     // Check whether the type matches the abstract type.
5837     QualType T = TL.getType();
5838     if (T->isArrayType()) {
5839       Sel = Sema::AbstractArrayType;
5840       T = Info.S.Context.getBaseElementType(T);
5841     }
5842     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5843     if (CT != Info.AbstractType) return;
5844 
5845     // It matched; do some magic.
5846     if (Sel == Sema::AbstractArrayType) {
5847       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5848         << T << TL.getSourceRange();
5849     } else {
5850       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5851         << Sel << T << TL.getSourceRange();
5852     }
5853     Info.DiagnoseAbstractType();
5854   }
5855 };
5856 
5857 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5858                                   Sema::AbstractDiagSelID Sel) {
5859   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5860 }
5861 
5862 }
5863 
5864 /// Check for invalid uses of an abstract type in a method declaration.
5865 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5866                                     CXXMethodDecl *MD) {
5867   // No need to do the check on definitions, which require that
5868   // the return/param types be complete.
5869   if (MD->doesThisDeclarationHaveABody())
5870     return;
5871 
5872   // For safety's sake, just ignore it if we don't have type source
5873   // information.  This should never happen for non-implicit methods,
5874   // but...
5875   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5876     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5877 }
5878 
5879 /// Check for invalid uses of an abstract type within a class definition.
5880 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5881                                     CXXRecordDecl *RD) {
5882   for (auto *D : RD->decls()) {
5883     if (D->isImplicit()) continue;
5884 
5885     // Methods and method templates.
5886     if (isa<CXXMethodDecl>(D)) {
5887       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5888     } else if (isa<FunctionTemplateDecl>(D)) {
5889       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5890       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5891 
5892     // Fields and static variables.
5893     } else if (isa<FieldDecl>(D)) {
5894       FieldDecl *FD = cast<FieldDecl>(D);
5895       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5896         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5897     } else if (isa<VarDecl>(D)) {
5898       VarDecl *VD = cast<VarDecl>(D);
5899       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5900         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5901 
5902     // Nested classes and class templates.
5903     } else if (isa<CXXRecordDecl>(D)) {
5904       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5905     } else if (isa<ClassTemplateDecl>(D)) {
5906       CheckAbstractClassUsage(Info,
5907                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5908     }
5909   }
5910 }
5911 
5912 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5913   Attr *ClassAttr = getDLLAttr(Class);
5914   if (!ClassAttr)
5915     return;
5916 
5917   assert(ClassAttr->getKind() == attr::DLLExport);
5918 
5919   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5920 
5921   if (TSK == TSK_ExplicitInstantiationDeclaration)
5922     // Don't go any further if this is just an explicit instantiation
5923     // declaration.
5924     return;
5925 
5926   // Add a context note to explain how we got to any diagnostics produced below.
5927   struct MarkingClassDllexported {
5928     Sema &S;
5929     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5930                             SourceLocation AttrLoc)
5931         : S(S) {
5932       Sema::CodeSynthesisContext Ctx;
5933       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5934       Ctx.PointOfInstantiation = AttrLoc;
5935       Ctx.Entity = Class;
5936       S.pushCodeSynthesisContext(Ctx);
5937     }
5938     ~MarkingClassDllexported() {
5939       S.popCodeSynthesisContext();
5940     }
5941   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5942 
5943   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5944     S.MarkVTableUsed(Class->getLocation(), Class, true);
5945 
5946   for (Decl *Member : Class->decls()) {
5947     // Defined static variables that are members of an exported base
5948     // class must be marked export too.
5949     auto *VD = dyn_cast<VarDecl>(Member);
5950     if (VD && Member->getAttr<DLLExportAttr>() &&
5951         VD->getStorageClass() == SC_Static &&
5952         TSK == TSK_ImplicitInstantiation)
5953       S.MarkVariableReferenced(VD->getLocation(), VD);
5954 
5955     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5956     if (!MD)
5957       continue;
5958 
5959     if (Member->getAttr<DLLExportAttr>()) {
5960       if (MD->isUserProvided()) {
5961         // Instantiate non-default class member functions ...
5962 
5963         // .. except for certain kinds of template specializations.
5964         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5965           continue;
5966 
5967         S.MarkFunctionReferenced(Class->getLocation(), MD);
5968 
5969         // The function will be passed to the consumer when its definition is
5970         // encountered.
5971       } else if (MD->isExplicitlyDefaulted()) {
5972         // Synthesize and instantiate explicitly defaulted methods.
5973         S.MarkFunctionReferenced(Class->getLocation(), MD);
5974 
5975         if (TSK != TSK_ExplicitInstantiationDefinition) {
5976           // Except for explicit instantiation defs, we will not see the
5977           // definition again later, so pass it to the consumer now.
5978           S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5979         }
5980       } else if (!MD->isTrivial() ||
5981                  MD->isCopyAssignmentOperator() ||
5982                  MD->isMoveAssignmentOperator()) {
5983         // Synthesize and instantiate non-trivial implicit methods, and the copy
5984         // and move assignment operators. The latter are exported even if they
5985         // are trivial, because the address of an operator can be taken and
5986         // should compare equal across libraries.
5987         S.MarkFunctionReferenced(Class->getLocation(), MD);
5988 
5989         // There is no later point when we will see the definition of this
5990         // function, so pass it to the consumer now.
5991         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5992       }
5993     }
5994   }
5995 }
5996 
5997 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5998                                                         CXXRecordDecl *Class) {
5999   // Only the MS ABI has default constructor closures, so we don't need to do
6000   // this semantic checking anywhere else.
6001   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6002     return;
6003 
6004   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6005   for (Decl *Member : Class->decls()) {
6006     // Look for exported default constructors.
6007     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6008     if (!CD || !CD->isDefaultConstructor())
6009       continue;
6010     auto *Attr = CD->getAttr<DLLExportAttr>();
6011     if (!Attr)
6012       continue;
6013 
6014     // If the class is non-dependent, mark the default arguments as ODR-used so
6015     // that we can properly codegen the constructor closure.
6016     if (!Class->isDependentContext()) {
6017       for (ParmVarDecl *PD : CD->parameters()) {
6018         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6019         S.DiscardCleanupsInEvaluationContext();
6020       }
6021     }
6022 
6023     if (LastExportedDefaultCtor) {
6024       S.Diag(LastExportedDefaultCtor->getLocation(),
6025              diag::err_attribute_dll_ambiguous_default_ctor)
6026           << Class;
6027       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6028           << CD->getDeclName();
6029       return;
6030     }
6031     LastExportedDefaultCtor = CD;
6032   }
6033 }
6034 
6035 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6036                                                        CXXRecordDecl *Class) {
6037   bool ErrorReported = false;
6038   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6039                                                      ClassTemplateDecl *TD) {
6040     if (ErrorReported)
6041       return;
6042     S.Diag(TD->getLocation(),
6043            diag::err_cuda_device_builtin_surftex_cls_template)
6044         << /*surface*/ 0 << TD;
6045     ErrorReported = true;
6046   };
6047 
6048   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6049   if (!TD) {
6050     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6051     if (!SD) {
6052       S.Diag(Class->getLocation(),
6053              diag::err_cuda_device_builtin_surftex_ref_decl)
6054           << /*surface*/ 0 << Class;
6055       S.Diag(Class->getLocation(),
6056              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6057           << Class;
6058       return;
6059     }
6060     TD = SD->getSpecializedTemplate();
6061   }
6062 
6063   TemplateParameterList *Params = TD->getTemplateParameters();
6064   unsigned N = Params->size();
6065 
6066   if (N != 2) {
6067     reportIllegalClassTemplate(S, TD);
6068     S.Diag(TD->getLocation(),
6069            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6070         << TD << 2;
6071   }
6072   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6073     reportIllegalClassTemplate(S, TD);
6074     S.Diag(TD->getLocation(),
6075            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6076         << TD << /*1st*/ 0 << /*type*/ 0;
6077   }
6078   if (N > 1) {
6079     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6080     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6081       reportIllegalClassTemplate(S, TD);
6082       S.Diag(TD->getLocation(),
6083              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6084           << TD << /*2nd*/ 1 << /*integer*/ 1;
6085     }
6086   }
6087 }
6088 
6089 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6090                                                        CXXRecordDecl *Class) {
6091   bool ErrorReported = false;
6092   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6093                                                      ClassTemplateDecl *TD) {
6094     if (ErrorReported)
6095       return;
6096     S.Diag(TD->getLocation(),
6097            diag::err_cuda_device_builtin_surftex_cls_template)
6098         << /*texture*/ 1 << TD;
6099     ErrorReported = true;
6100   };
6101 
6102   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6103   if (!TD) {
6104     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6105     if (!SD) {
6106       S.Diag(Class->getLocation(),
6107              diag::err_cuda_device_builtin_surftex_ref_decl)
6108           << /*texture*/ 1 << Class;
6109       S.Diag(Class->getLocation(),
6110              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6111           << Class;
6112       return;
6113     }
6114     TD = SD->getSpecializedTemplate();
6115   }
6116 
6117   TemplateParameterList *Params = TD->getTemplateParameters();
6118   unsigned N = Params->size();
6119 
6120   if (N != 3) {
6121     reportIllegalClassTemplate(S, TD);
6122     S.Diag(TD->getLocation(),
6123            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6124         << TD << 3;
6125   }
6126   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6127     reportIllegalClassTemplate(S, TD);
6128     S.Diag(TD->getLocation(),
6129            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6130         << TD << /*1st*/ 0 << /*type*/ 0;
6131   }
6132   if (N > 1) {
6133     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6134     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6135       reportIllegalClassTemplate(S, TD);
6136       S.Diag(TD->getLocation(),
6137              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6138           << TD << /*2nd*/ 1 << /*integer*/ 1;
6139     }
6140   }
6141   if (N > 2) {
6142     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6143     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6144       reportIllegalClassTemplate(S, TD);
6145       S.Diag(TD->getLocation(),
6146              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6147           << TD << /*3rd*/ 2 << /*integer*/ 1;
6148     }
6149   }
6150 }
6151 
6152 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6153   // Mark any compiler-generated routines with the implicit code_seg attribute.
6154   for (auto *Method : Class->methods()) {
6155     if (Method->isUserProvided())
6156       continue;
6157     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6158       Method->addAttr(A);
6159   }
6160 }
6161 
6162 /// Check class-level dllimport/dllexport attribute.
6163 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6164   Attr *ClassAttr = getDLLAttr(Class);
6165 
6166   // MSVC inherits DLL attributes to partial class template specializations.
6167   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6168     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6169       if (Attr *TemplateAttr =
6170               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6171         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6172         A->setInherited(true);
6173         ClassAttr = A;
6174       }
6175     }
6176   }
6177 
6178   if (!ClassAttr)
6179     return;
6180 
6181   if (!Class->isExternallyVisible()) {
6182     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6183         << Class << ClassAttr;
6184     return;
6185   }
6186 
6187   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6188       !ClassAttr->isInherited()) {
6189     // Diagnose dll attributes on members of class with dll attribute.
6190     for (Decl *Member : Class->decls()) {
6191       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6192         continue;
6193       InheritableAttr *MemberAttr = getDLLAttr(Member);
6194       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6195         continue;
6196 
6197       Diag(MemberAttr->getLocation(),
6198              diag::err_attribute_dll_member_of_dll_class)
6199           << MemberAttr << ClassAttr;
6200       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6201       Member->setInvalidDecl();
6202     }
6203   }
6204 
6205   if (Class->getDescribedClassTemplate())
6206     // Don't inherit dll attribute until the template is instantiated.
6207     return;
6208 
6209   // The class is either imported or exported.
6210   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6211 
6212   // Check if this was a dllimport attribute propagated from a derived class to
6213   // a base class template specialization. We don't apply these attributes to
6214   // static data members.
6215   const bool PropagatedImport =
6216       !ClassExported &&
6217       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6218 
6219   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6220 
6221   // Ignore explicit dllexport on explicit class template instantiation
6222   // declarations, except in MinGW mode.
6223   if (ClassExported && !ClassAttr->isInherited() &&
6224       TSK == TSK_ExplicitInstantiationDeclaration &&
6225       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6226     Class->dropAttr<DLLExportAttr>();
6227     return;
6228   }
6229 
6230   // Force declaration of implicit members so they can inherit the attribute.
6231   ForceDeclarationOfImplicitMembers(Class);
6232 
6233   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6234   // seem to be true in practice?
6235 
6236   for (Decl *Member : Class->decls()) {
6237     VarDecl *VD = dyn_cast<VarDecl>(Member);
6238     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6239 
6240     // Only methods and static fields inherit the attributes.
6241     if (!VD && !MD)
6242       continue;
6243 
6244     if (MD) {
6245       // Don't process deleted methods.
6246       if (MD->isDeleted())
6247         continue;
6248 
6249       if (MD->isInlined()) {
6250         // MinGW does not import or export inline methods. But do it for
6251         // template instantiations.
6252         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6253             TSK != TSK_ExplicitInstantiationDeclaration &&
6254             TSK != TSK_ExplicitInstantiationDefinition)
6255           continue;
6256 
6257         // MSVC versions before 2015 don't export the move assignment operators
6258         // and move constructor, so don't attempt to import/export them if
6259         // we have a definition.
6260         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6261         if ((MD->isMoveAssignmentOperator() ||
6262              (Ctor && Ctor->isMoveConstructor())) &&
6263             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6264           continue;
6265 
6266         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6267         // operator is exported anyway.
6268         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6269             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6270           continue;
6271       }
6272     }
6273 
6274     // Don't apply dllimport attributes to static data members of class template
6275     // instantiations when the attribute is propagated from a derived class.
6276     if (VD && PropagatedImport)
6277       continue;
6278 
6279     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6280       continue;
6281 
6282     if (!getDLLAttr(Member)) {
6283       InheritableAttr *NewAttr = nullptr;
6284 
6285       // Do not export/import inline function when -fno-dllexport-inlines is
6286       // passed. But add attribute for later local static var check.
6287       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6288           TSK != TSK_ExplicitInstantiationDeclaration &&
6289           TSK != TSK_ExplicitInstantiationDefinition) {
6290         if (ClassExported) {
6291           NewAttr = ::new (getASTContext())
6292               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6293         } else {
6294           NewAttr = ::new (getASTContext())
6295               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6296         }
6297       } else {
6298         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6299       }
6300 
6301       NewAttr->setInherited(true);
6302       Member->addAttr(NewAttr);
6303 
6304       if (MD) {
6305         // Propagate DLLAttr to friend re-declarations of MD that have already
6306         // been constructed.
6307         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6308              FD = FD->getPreviousDecl()) {
6309           if (FD->getFriendObjectKind() == Decl::FOK_None)
6310             continue;
6311           assert(!getDLLAttr(FD) &&
6312                  "friend re-decl should not already have a DLLAttr");
6313           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6314           NewAttr->setInherited(true);
6315           FD->addAttr(NewAttr);
6316         }
6317       }
6318     }
6319   }
6320 
6321   if (ClassExported)
6322     DelayedDllExportClasses.push_back(Class);
6323 }
6324 
6325 /// Perform propagation of DLL attributes from a derived class to a
6326 /// templated base class for MS compatibility.
6327 void Sema::propagateDLLAttrToBaseClassTemplate(
6328     CXXRecordDecl *Class, Attr *ClassAttr,
6329     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6330   if (getDLLAttr(
6331           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6332     // If the base class template has a DLL attribute, don't try to change it.
6333     return;
6334   }
6335 
6336   auto TSK = BaseTemplateSpec->getSpecializationKind();
6337   if (!getDLLAttr(BaseTemplateSpec) &&
6338       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6339        TSK == TSK_ImplicitInstantiation)) {
6340     // The template hasn't been instantiated yet (or it has, but only as an
6341     // explicit instantiation declaration or implicit instantiation, which means
6342     // we haven't codegenned any members yet), so propagate the attribute.
6343     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6344     NewAttr->setInherited(true);
6345     BaseTemplateSpec->addAttr(NewAttr);
6346 
6347     // If this was an import, mark that we propagated it from a derived class to
6348     // a base class template specialization.
6349     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6350       ImportAttr->setPropagatedToBaseTemplate();
6351 
6352     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6353     // needs to be run again to work see the new attribute. Otherwise this will
6354     // get run whenever the template is instantiated.
6355     if (TSK != TSK_Undeclared)
6356       checkClassLevelDLLAttribute(BaseTemplateSpec);
6357 
6358     return;
6359   }
6360 
6361   if (getDLLAttr(BaseTemplateSpec)) {
6362     // The template has already been specialized or instantiated with an
6363     // attribute, explicitly or through propagation. We should not try to change
6364     // it.
6365     return;
6366   }
6367 
6368   // The template was previously instantiated or explicitly specialized without
6369   // a dll attribute, It's too late for us to add an attribute, so warn that
6370   // this is unsupported.
6371   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6372       << BaseTemplateSpec->isExplicitSpecialization();
6373   Diag(ClassAttr->getLocation(), diag::note_attribute);
6374   if (BaseTemplateSpec->isExplicitSpecialization()) {
6375     Diag(BaseTemplateSpec->getLocation(),
6376            diag::note_template_class_explicit_specialization_was_here)
6377         << BaseTemplateSpec;
6378   } else {
6379     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6380            diag::note_template_class_instantiation_was_here)
6381         << BaseTemplateSpec;
6382   }
6383 }
6384 
6385 /// Determine the kind of defaulting that would be done for a given function.
6386 ///
6387 /// If the function is both a default constructor and a copy / move constructor
6388 /// (due to having a default argument for the first parameter), this picks
6389 /// CXXDefaultConstructor.
6390 ///
6391 /// FIXME: Check that case is properly handled by all callers.
6392 Sema::DefaultedFunctionKind
6393 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6394   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6395     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6396       if (Ctor->isDefaultConstructor())
6397         return Sema::CXXDefaultConstructor;
6398 
6399       if (Ctor->isCopyConstructor())
6400         return Sema::CXXCopyConstructor;
6401 
6402       if (Ctor->isMoveConstructor())
6403         return Sema::CXXMoveConstructor;
6404     }
6405 
6406     if (MD->isCopyAssignmentOperator())
6407       return Sema::CXXCopyAssignment;
6408 
6409     if (MD->isMoveAssignmentOperator())
6410       return Sema::CXXMoveAssignment;
6411 
6412     if (isa<CXXDestructorDecl>(FD))
6413       return Sema::CXXDestructor;
6414   }
6415 
6416   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6417   case OO_EqualEqual:
6418     return DefaultedComparisonKind::Equal;
6419 
6420   case OO_ExclaimEqual:
6421     return DefaultedComparisonKind::NotEqual;
6422 
6423   case OO_Spaceship:
6424     // No point allowing this if <=> doesn't exist in the current language mode.
6425     if (!getLangOpts().CPlusPlus20)
6426       break;
6427     return DefaultedComparisonKind::ThreeWay;
6428 
6429   case OO_Less:
6430   case OO_LessEqual:
6431   case OO_Greater:
6432   case OO_GreaterEqual:
6433     // No point allowing this if <=> doesn't exist in the current language mode.
6434     if (!getLangOpts().CPlusPlus20)
6435       break;
6436     return DefaultedComparisonKind::Relational;
6437 
6438   default:
6439     break;
6440   }
6441 
6442   // Not defaultable.
6443   return DefaultedFunctionKind();
6444 }
6445 
6446 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6447                                     SourceLocation DefaultLoc) {
6448   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6449   if (DFK.isComparison())
6450     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6451 
6452   switch (DFK.asSpecialMember()) {
6453   case Sema::CXXDefaultConstructor:
6454     S.DefineImplicitDefaultConstructor(DefaultLoc,
6455                                        cast<CXXConstructorDecl>(FD));
6456     break;
6457   case Sema::CXXCopyConstructor:
6458     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6459     break;
6460   case Sema::CXXCopyAssignment:
6461     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6462     break;
6463   case Sema::CXXDestructor:
6464     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6465     break;
6466   case Sema::CXXMoveConstructor:
6467     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6468     break;
6469   case Sema::CXXMoveAssignment:
6470     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6471     break;
6472   case Sema::CXXInvalid:
6473     llvm_unreachable("Invalid special member.");
6474   }
6475 }
6476 
6477 /// Determine whether a type is permitted to be passed or returned in
6478 /// registers, per C++ [class.temporary]p3.
6479 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6480                                TargetInfo::CallingConvKind CCK) {
6481   if (D->isDependentType() || D->isInvalidDecl())
6482     return false;
6483 
6484   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6485   // The PS4 platform ABI follows the behavior of Clang 3.2.
6486   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6487     return !D->hasNonTrivialDestructorForCall() &&
6488            !D->hasNonTrivialCopyConstructorForCall();
6489 
6490   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6491     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6492     bool DtorIsTrivialForCall = false;
6493 
6494     // If a class has at least one non-deleted, trivial copy constructor, it
6495     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6496     //
6497     // Note: This permits classes with non-trivial copy or move ctors to be
6498     // passed in registers, so long as they *also* have a trivial copy ctor,
6499     // which is non-conforming.
6500     if (D->needsImplicitCopyConstructor()) {
6501       if (!D->defaultedCopyConstructorIsDeleted()) {
6502         if (D->hasTrivialCopyConstructor())
6503           CopyCtorIsTrivial = true;
6504         if (D->hasTrivialCopyConstructorForCall())
6505           CopyCtorIsTrivialForCall = true;
6506       }
6507     } else {
6508       for (const CXXConstructorDecl *CD : D->ctors()) {
6509         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6510           if (CD->isTrivial())
6511             CopyCtorIsTrivial = true;
6512           if (CD->isTrivialForCall())
6513             CopyCtorIsTrivialForCall = true;
6514         }
6515       }
6516     }
6517 
6518     if (D->needsImplicitDestructor()) {
6519       if (!D->defaultedDestructorIsDeleted() &&
6520           D->hasTrivialDestructorForCall())
6521         DtorIsTrivialForCall = true;
6522     } else if (const auto *DD = D->getDestructor()) {
6523       if (!DD->isDeleted() && DD->isTrivialForCall())
6524         DtorIsTrivialForCall = true;
6525     }
6526 
6527     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6528     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6529       return true;
6530 
6531     // If a class has a destructor, we'd really like to pass it indirectly
6532     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6533     // impossible for small types, which it will pass in a single register or
6534     // stack slot. Most objects with dtors are large-ish, so handle that early.
6535     // We can't call out all large objects as being indirect because there are
6536     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6537     // how we pass large POD types.
6538 
6539     // Note: This permits small classes with nontrivial destructors to be
6540     // passed in registers, which is non-conforming.
6541     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6542     uint64_t TypeSize = isAArch64 ? 128 : 64;
6543 
6544     if (CopyCtorIsTrivial &&
6545         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6546       return true;
6547     return false;
6548   }
6549 
6550   // Per C++ [class.temporary]p3, the relevant condition is:
6551   //   each copy constructor, move constructor, and destructor of X is
6552   //   either trivial or deleted, and X has at least one non-deleted copy
6553   //   or move constructor
6554   bool HasNonDeletedCopyOrMove = false;
6555 
6556   if (D->needsImplicitCopyConstructor() &&
6557       !D->defaultedCopyConstructorIsDeleted()) {
6558     if (!D->hasTrivialCopyConstructorForCall())
6559       return false;
6560     HasNonDeletedCopyOrMove = true;
6561   }
6562 
6563   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6564       !D->defaultedMoveConstructorIsDeleted()) {
6565     if (!D->hasTrivialMoveConstructorForCall())
6566       return false;
6567     HasNonDeletedCopyOrMove = true;
6568   }
6569 
6570   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6571       !D->hasTrivialDestructorForCall())
6572     return false;
6573 
6574   for (const CXXMethodDecl *MD : D->methods()) {
6575     if (MD->isDeleted())
6576       continue;
6577 
6578     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6579     if (CD && CD->isCopyOrMoveConstructor())
6580       HasNonDeletedCopyOrMove = true;
6581     else if (!isa<CXXDestructorDecl>(MD))
6582       continue;
6583 
6584     if (!MD->isTrivialForCall())
6585       return false;
6586   }
6587 
6588   return HasNonDeletedCopyOrMove;
6589 }
6590 
6591 /// Report an error regarding overriding, along with any relevant
6592 /// overridden methods.
6593 ///
6594 /// \param DiagID the primary error to report.
6595 /// \param MD the overriding method.
6596 static bool
6597 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6598                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6599   bool IssuedDiagnostic = false;
6600   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6601     if (Report(O)) {
6602       if (!IssuedDiagnostic) {
6603         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6604         IssuedDiagnostic = true;
6605       }
6606       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6607     }
6608   }
6609   return IssuedDiagnostic;
6610 }
6611 
6612 /// Perform semantic checks on a class definition that has been
6613 /// completing, introducing implicitly-declared members, checking for
6614 /// abstract types, etc.
6615 ///
6616 /// \param S The scope in which the class was parsed. Null if we didn't just
6617 ///        parse a class definition.
6618 /// \param Record The completed class.
6619 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6620   if (!Record)
6621     return;
6622 
6623   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6624     AbstractUsageInfo Info(*this, Record);
6625     CheckAbstractClassUsage(Info, Record);
6626   }
6627 
6628   // If this is not an aggregate type and has no user-declared constructor,
6629   // complain about any non-static data members of reference or const scalar
6630   // type, since they will never get initializers.
6631   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6632       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6633       !Record->isLambda()) {
6634     bool Complained = false;
6635     for (const auto *F : Record->fields()) {
6636       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6637         continue;
6638 
6639       if (F->getType()->isReferenceType() ||
6640           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6641         if (!Complained) {
6642           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6643             << Record->getTagKind() << Record;
6644           Complained = true;
6645         }
6646 
6647         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6648           << F->getType()->isReferenceType()
6649           << F->getDeclName();
6650       }
6651     }
6652   }
6653 
6654   if (Record->getIdentifier()) {
6655     // C++ [class.mem]p13:
6656     //   If T is the name of a class, then each of the following shall have a
6657     //   name different from T:
6658     //     - every member of every anonymous union that is a member of class T.
6659     //
6660     // C++ [class.mem]p14:
6661     //   In addition, if class T has a user-declared constructor (12.1), every
6662     //   non-static data member of class T shall have a name different from T.
6663     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6664     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6665          ++I) {
6666       NamedDecl *D = (*I)->getUnderlyingDecl();
6667       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6668            Record->hasUserDeclaredConstructor()) ||
6669           isa<IndirectFieldDecl>(D)) {
6670         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6671           << D->getDeclName();
6672         break;
6673       }
6674     }
6675   }
6676 
6677   // Warn if the class has virtual methods but non-virtual public destructor.
6678   if (Record->isPolymorphic() && !Record->isDependentType()) {
6679     CXXDestructorDecl *dtor = Record->getDestructor();
6680     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6681         !Record->hasAttr<FinalAttr>())
6682       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6683            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6684   }
6685 
6686   if (Record->isAbstract()) {
6687     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6688       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6689         << FA->isSpelledAsSealed();
6690       DiagnoseAbstractType(Record);
6691     }
6692   }
6693 
6694   // Warn if the class has a final destructor but is not itself marked final.
6695   if (!Record->hasAttr<FinalAttr>()) {
6696     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6697       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6698         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6699             << FA->isSpelledAsSealed()
6700             << FixItHint::CreateInsertion(
6701                    getLocForEndOfToken(Record->getLocation()),
6702                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6703         Diag(Record->getLocation(),
6704              diag::note_final_dtor_non_final_class_silence)
6705             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6706       }
6707     }
6708   }
6709 
6710   // See if trivial_abi has to be dropped.
6711   if (Record->hasAttr<TrivialABIAttr>())
6712     checkIllFormedTrivialABIStruct(*Record);
6713 
6714   // Set HasTrivialSpecialMemberForCall if the record has attribute
6715   // "trivial_abi".
6716   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6717 
6718   if (HasTrivialABI)
6719     Record->setHasTrivialSpecialMemberForCall();
6720 
6721   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6722   // We check these last because they can depend on the properties of the
6723   // primary comparison functions (==, <=>).
6724   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6725 
6726   // Perform checks that can't be done until we know all the properties of a
6727   // member function (whether it's defaulted, deleted, virtual, overriding,
6728   // ...).
6729   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6730     // A static function cannot override anything.
6731     if (MD->getStorageClass() == SC_Static) {
6732       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6733                           [](const CXXMethodDecl *) { return true; }))
6734         return;
6735     }
6736 
6737     // A deleted function cannot override a non-deleted function and vice
6738     // versa.
6739     if (ReportOverrides(*this,
6740                         MD->isDeleted() ? diag::err_deleted_override
6741                                         : diag::err_non_deleted_override,
6742                         MD, [&](const CXXMethodDecl *V) {
6743                           return MD->isDeleted() != V->isDeleted();
6744                         })) {
6745       if (MD->isDefaulted() && MD->isDeleted())
6746         // Explain why this defaulted function was deleted.
6747         DiagnoseDeletedDefaultedFunction(MD);
6748       return;
6749     }
6750 
6751     // A consteval function cannot override a non-consteval function and vice
6752     // versa.
6753     if (ReportOverrides(*this,
6754                         MD->isConsteval() ? diag::err_consteval_override
6755                                           : diag::err_non_consteval_override,
6756                         MD, [&](const CXXMethodDecl *V) {
6757                           return MD->isConsteval() != V->isConsteval();
6758                         })) {
6759       if (MD->isDefaulted() && MD->isDeleted())
6760         // Explain why this defaulted function was deleted.
6761         DiagnoseDeletedDefaultedFunction(MD);
6762       return;
6763     }
6764   };
6765 
6766   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6767     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6768       return false;
6769 
6770     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6771     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6772         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6773       DefaultedSecondaryComparisons.push_back(FD);
6774       return true;
6775     }
6776 
6777     CheckExplicitlyDefaultedFunction(S, FD);
6778     return false;
6779   };
6780 
6781   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6782     // Check whether the explicitly-defaulted members are valid.
6783     bool Incomplete = CheckForDefaultedFunction(M);
6784 
6785     // Skip the rest of the checks for a member of a dependent class.
6786     if (Record->isDependentType())
6787       return;
6788 
6789     // For an explicitly defaulted or deleted special member, we defer
6790     // determining triviality until the class is complete. That time is now!
6791     CXXSpecialMember CSM = getSpecialMember(M);
6792     if (!M->isImplicit() && !M->isUserProvided()) {
6793       if (CSM != CXXInvalid) {
6794         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6795         // Inform the class that we've finished declaring this member.
6796         Record->finishedDefaultedOrDeletedMember(M);
6797         M->setTrivialForCall(
6798             HasTrivialABI ||
6799             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6800         Record->setTrivialForCallFlags(M);
6801       }
6802     }
6803 
6804     // Set triviality for the purpose of calls if this is a user-provided
6805     // copy/move constructor or destructor.
6806     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6807          CSM == CXXDestructor) && M->isUserProvided()) {
6808       M->setTrivialForCall(HasTrivialABI);
6809       Record->setTrivialForCallFlags(M);
6810     }
6811 
6812     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6813         M->hasAttr<DLLExportAttr>()) {
6814       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6815           M->isTrivial() &&
6816           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6817            CSM == CXXDestructor))
6818         M->dropAttr<DLLExportAttr>();
6819 
6820       if (M->hasAttr<DLLExportAttr>()) {
6821         // Define after any fields with in-class initializers have been parsed.
6822         DelayedDllExportMemberFunctions.push_back(M);
6823       }
6824     }
6825 
6826     // Define defaulted constexpr virtual functions that override a base class
6827     // function right away.
6828     // FIXME: We can defer doing this until the vtable is marked as used.
6829     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6830       DefineDefaultedFunction(*this, M, M->getLocation());
6831 
6832     if (!Incomplete)
6833       CheckCompletedMemberFunction(M);
6834   };
6835 
6836   // Check the destructor before any other member function. We need to
6837   // determine whether it's trivial in order to determine whether the claas
6838   // type is a literal type, which is a prerequisite for determining whether
6839   // other special member functions are valid and whether they're implicitly
6840   // 'constexpr'.
6841   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6842     CompleteMemberFunction(Dtor);
6843 
6844   bool HasMethodWithOverrideControl = false,
6845        HasOverridingMethodWithoutOverrideControl = false;
6846   for (auto *D : Record->decls()) {
6847     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6848       // FIXME: We could do this check for dependent types with non-dependent
6849       // bases.
6850       if (!Record->isDependentType()) {
6851         // See if a method overloads virtual methods in a base
6852         // class without overriding any.
6853         if (!M->isStatic())
6854           DiagnoseHiddenVirtualMethods(M);
6855         if (M->hasAttr<OverrideAttr>())
6856           HasMethodWithOverrideControl = true;
6857         else if (M->size_overridden_methods() > 0)
6858           HasOverridingMethodWithoutOverrideControl = true;
6859       }
6860 
6861       if (!isa<CXXDestructorDecl>(M))
6862         CompleteMemberFunction(M);
6863     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6864       CheckForDefaultedFunction(
6865           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6866     }
6867   }
6868 
6869   if (HasOverridingMethodWithoutOverrideControl) {
6870     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6871     for (auto *M : Record->methods())
6872       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6873   }
6874 
6875   // Check the defaulted secondary comparisons after any other member functions.
6876   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6877     CheckExplicitlyDefaultedFunction(S, FD);
6878 
6879     // If this is a member function, we deferred checking it until now.
6880     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6881       CheckCompletedMemberFunction(MD);
6882   }
6883 
6884   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6885   // whether this class uses any C++ features that are implemented
6886   // completely differently in MSVC, and if so, emit a diagnostic.
6887   // That diagnostic defaults to an error, but we allow projects to
6888   // map it down to a warning (or ignore it).  It's a fairly common
6889   // practice among users of the ms_struct pragma to mass-annotate
6890   // headers, sweeping up a bunch of types that the project doesn't
6891   // really rely on MSVC-compatible layout for.  We must therefore
6892   // support "ms_struct except for C++ stuff" as a secondary ABI.
6893   // Don't emit this diagnostic if the feature was enabled as a
6894   // language option (as opposed to via a pragma or attribute), as
6895   // the option -mms-bitfields otherwise essentially makes it impossible
6896   // to build C++ code, unless this diagnostic is turned off.
6897   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6898       (Record->isPolymorphic() || Record->getNumBases())) {
6899     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6900   }
6901 
6902   checkClassLevelDLLAttribute(Record);
6903   checkClassLevelCodeSegAttribute(Record);
6904 
6905   bool ClangABICompat4 =
6906       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6907   TargetInfo::CallingConvKind CCK =
6908       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6909   bool CanPass = canPassInRegisters(*this, Record, CCK);
6910 
6911   // Do not change ArgPassingRestrictions if it has already been set to
6912   // APK_CanNeverPassInRegs.
6913   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6914     Record->setArgPassingRestrictions(CanPass
6915                                           ? RecordDecl::APK_CanPassInRegs
6916                                           : RecordDecl::APK_CannotPassInRegs);
6917 
6918   // If canPassInRegisters returns true despite the record having a non-trivial
6919   // destructor, the record is destructed in the callee. This happens only when
6920   // the record or one of its subobjects has a field annotated with trivial_abi
6921   // or a field qualified with ObjC __strong/__weak.
6922   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6923     Record->setParamDestroyedInCallee(true);
6924   else if (Record->hasNonTrivialDestructor())
6925     Record->setParamDestroyedInCallee(CanPass);
6926 
6927   if (getLangOpts().ForceEmitVTables) {
6928     // If we want to emit all the vtables, we need to mark it as used.  This
6929     // is especially required for cases like vtable assumption loads.
6930     MarkVTableUsed(Record->getInnerLocStart(), Record);
6931   }
6932 
6933   if (getLangOpts().CUDA) {
6934     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6935       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6936     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6937       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6938   }
6939 }
6940 
6941 /// Look up the special member function that would be called by a special
6942 /// member function for a subobject of class type.
6943 ///
6944 /// \param Class The class type of the subobject.
6945 /// \param CSM The kind of special member function.
6946 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6947 /// \param ConstRHS True if this is a copy operation with a const object
6948 ///        on its RHS, that is, if the argument to the outer special member
6949 ///        function is 'const' and this is not a field marked 'mutable'.
6950 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6951     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6952     unsigned FieldQuals, bool ConstRHS) {
6953   unsigned LHSQuals = 0;
6954   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6955     LHSQuals = FieldQuals;
6956 
6957   unsigned RHSQuals = FieldQuals;
6958   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6959     RHSQuals = 0;
6960   else if (ConstRHS)
6961     RHSQuals |= Qualifiers::Const;
6962 
6963   return S.LookupSpecialMember(Class, CSM,
6964                                RHSQuals & Qualifiers::Const,
6965                                RHSQuals & Qualifiers::Volatile,
6966                                false,
6967                                LHSQuals & Qualifiers::Const,
6968                                LHSQuals & Qualifiers::Volatile);
6969 }
6970 
6971 class Sema::InheritedConstructorInfo {
6972   Sema &S;
6973   SourceLocation UseLoc;
6974 
6975   /// A mapping from the base classes through which the constructor was
6976   /// inherited to the using shadow declaration in that base class (or a null
6977   /// pointer if the constructor was declared in that base class).
6978   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6979       InheritedFromBases;
6980 
6981 public:
6982   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6983                            ConstructorUsingShadowDecl *Shadow)
6984       : S(S), UseLoc(UseLoc) {
6985     bool DiagnosedMultipleConstructedBases = false;
6986     CXXRecordDecl *ConstructedBase = nullptr;
6987     UsingDecl *ConstructedBaseUsing = nullptr;
6988 
6989     // Find the set of such base class subobjects and check that there's a
6990     // unique constructed subobject.
6991     for (auto *D : Shadow->redecls()) {
6992       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6993       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6994       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6995 
6996       InheritedFromBases.insert(
6997           std::make_pair(DNominatedBase->getCanonicalDecl(),
6998                          DShadow->getNominatedBaseClassShadowDecl()));
6999       if (DShadow->constructsVirtualBase())
7000         InheritedFromBases.insert(
7001             std::make_pair(DConstructedBase->getCanonicalDecl(),
7002                            DShadow->getConstructedBaseClassShadowDecl()));
7003       else
7004         assert(DNominatedBase == DConstructedBase);
7005 
7006       // [class.inhctor.init]p2:
7007       //   If the constructor was inherited from multiple base class subobjects
7008       //   of type B, the program is ill-formed.
7009       if (!ConstructedBase) {
7010         ConstructedBase = DConstructedBase;
7011         ConstructedBaseUsing = D->getUsingDecl();
7012       } else if (ConstructedBase != DConstructedBase &&
7013                  !Shadow->isInvalidDecl()) {
7014         if (!DiagnosedMultipleConstructedBases) {
7015           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7016               << Shadow->getTargetDecl();
7017           S.Diag(ConstructedBaseUsing->getLocation(),
7018                diag::note_ambiguous_inherited_constructor_using)
7019               << ConstructedBase;
7020           DiagnosedMultipleConstructedBases = true;
7021         }
7022         S.Diag(D->getUsingDecl()->getLocation(),
7023                diag::note_ambiguous_inherited_constructor_using)
7024             << DConstructedBase;
7025       }
7026     }
7027 
7028     if (DiagnosedMultipleConstructedBases)
7029       Shadow->setInvalidDecl();
7030   }
7031 
7032   /// Find the constructor to use for inherited construction of a base class,
7033   /// and whether that base class constructor inherits the constructor from a
7034   /// virtual base class (in which case it won't actually invoke it).
7035   std::pair<CXXConstructorDecl *, bool>
7036   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7037     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7038     if (It == InheritedFromBases.end())
7039       return std::make_pair(nullptr, false);
7040 
7041     // This is an intermediary class.
7042     if (It->second)
7043       return std::make_pair(
7044           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7045           It->second->constructsVirtualBase());
7046 
7047     // This is the base class from which the constructor was inherited.
7048     return std::make_pair(Ctor, false);
7049   }
7050 };
7051 
7052 /// Is the special member function which would be selected to perform the
7053 /// specified operation on the specified class type a constexpr constructor?
7054 static bool
7055 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7056                          Sema::CXXSpecialMember CSM, unsigned Quals,
7057                          bool ConstRHS,
7058                          CXXConstructorDecl *InheritedCtor = nullptr,
7059                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7060   // If we're inheriting a constructor, see if we need to call it for this base
7061   // class.
7062   if (InheritedCtor) {
7063     assert(CSM == Sema::CXXDefaultConstructor);
7064     auto BaseCtor =
7065         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7066     if (BaseCtor)
7067       return BaseCtor->isConstexpr();
7068   }
7069 
7070   if (CSM == Sema::CXXDefaultConstructor)
7071     return ClassDecl->hasConstexprDefaultConstructor();
7072   if (CSM == Sema::CXXDestructor)
7073     return ClassDecl->hasConstexprDestructor();
7074 
7075   Sema::SpecialMemberOverloadResult SMOR =
7076       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7077   if (!SMOR.getMethod())
7078     // A constructor we wouldn't select can't be "involved in initializing"
7079     // anything.
7080     return true;
7081   return SMOR.getMethod()->isConstexpr();
7082 }
7083 
7084 /// Determine whether the specified special member function would be constexpr
7085 /// if it were implicitly defined.
7086 static bool defaultedSpecialMemberIsConstexpr(
7087     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7088     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7089     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7090   if (!S.getLangOpts().CPlusPlus11)
7091     return false;
7092 
7093   // C++11 [dcl.constexpr]p4:
7094   // In the definition of a constexpr constructor [...]
7095   bool Ctor = true;
7096   switch (CSM) {
7097   case Sema::CXXDefaultConstructor:
7098     if (Inherited)
7099       break;
7100     // Since default constructor lookup is essentially trivial (and cannot
7101     // involve, for instance, template instantiation), we compute whether a
7102     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7103     //
7104     // This is important for performance; we need to know whether the default
7105     // constructor is constexpr to determine whether the type is a literal type.
7106     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7107 
7108   case Sema::CXXCopyConstructor:
7109   case Sema::CXXMoveConstructor:
7110     // For copy or move constructors, we need to perform overload resolution.
7111     break;
7112 
7113   case Sema::CXXCopyAssignment:
7114   case Sema::CXXMoveAssignment:
7115     if (!S.getLangOpts().CPlusPlus14)
7116       return false;
7117     // In C++1y, we need to perform overload resolution.
7118     Ctor = false;
7119     break;
7120 
7121   case Sema::CXXDestructor:
7122     return ClassDecl->defaultedDestructorIsConstexpr();
7123 
7124   case Sema::CXXInvalid:
7125     return false;
7126   }
7127 
7128   //   -- if the class is a non-empty union, or for each non-empty anonymous
7129   //      union member of a non-union class, exactly one non-static data member
7130   //      shall be initialized; [DR1359]
7131   //
7132   // If we squint, this is guaranteed, since exactly one non-static data member
7133   // will be initialized (if the constructor isn't deleted), we just don't know
7134   // which one.
7135   if (Ctor && ClassDecl->isUnion())
7136     return CSM == Sema::CXXDefaultConstructor
7137                ? ClassDecl->hasInClassInitializer() ||
7138                      !ClassDecl->hasVariantMembers()
7139                : true;
7140 
7141   //   -- the class shall not have any virtual base classes;
7142   if (Ctor && ClassDecl->getNumVBases())
7143     return false;
7144 
7145   // C++1y [class.copy]p26:
7146   //   -- [the class] is a literal type, and
7147   if (!Ctor && !ClassDecl->isLiteral())
7148     return false;
7149 
7150   //   -- every constructor involved in initializing [...] base class
7151   //      sub-objects shall be a constexpr constructor;
7152   //   -- the assignment operator selected to copy/move each direct base
7153   //      class is a constexpr function, and
7154   for (const auto &B : ClassDecl->bases()) {
7155     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7156     if (!BaseType) continue;
7157 
7158     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7159     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7160                                   InheritedCtor, Inherited))
7161       return false;
7162   }
7163 
7164   //   -- every constructor involved in initializing non-static data members
7165   //      [...] shall be a constexpr constructor;
7166   //   -- every non-static data member and base class sub-object shall be
7167   //      initialized
7168   //   -- for each non-static data member of X that is of class type (or array
7169   //      thereof), the assignment operator selected to copy/move that member is
7170   //      a constexpr function
7171   for (const auto *F : ClassDecl->fields()) {
7172     if (F->isInvalidDecl())
7173       continue;
7174     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7175       continue;
7176     QualType BaseType = S.Context.getBaseElementType(F->getType());
7177     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7178       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7179       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7180                                     BaseType.getCVRQualifiers(),
7181                                     ConstArg && !F->isMutable()))
7182         return false;
7183     } else if (CSM == Sema::CXXDefaultConstructor) {
7184       return false;
7185     }
7186   }
7187 
7188   // All OK, it's constexpr!
7189   return true;
7190 }
7191 
7192 namespace {
7193 /// RAII object to register a defaulted function as having its exception
7194 /// specification computed.
7195 struct ComputingExceptionSpec {
7196   Sema &S;
7197 
7198   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7199       : S(S) {
7200     Sema::CodeSynthesisContext Ctx;
7201     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7202     Ctx.PointOfInstantiation = Loc;
7203     Ctx.Entity = FD;
7204     S.pushCodeSynthesisContext(Ctx);
7205   }
7206   ~ComputingExceptionSpec() {
7207     S.popCodeSynthesisContext();
7208   }
7209 };
7210 }
7211 
7212 static Sema::ImplicitExceptionSpecification
7213 ComputeDefaultedSpecialMemberExceptionSpec(
7214     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7215     Sema::InheritedConstructorInfo *ICI);
7216 
7217 static Sema::ImplicitExceptionSpecification
7218 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7219                                         FunctionDecl *FD,
7220                                         Sema::DefaultedComparisonKind DCK);
7221 
7222 static Sema::ImplicitExceptionSpecification
7223 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7224   auto DFK = S.getDefaultedFunctionKind(FD);
7225   if (DFK.isSpecialMember())
7226     return ComputeDefaultedSpecialMemberExceptionSpec(
7227         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7228   if (DFK.isComparison())
7229     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7230                                                    DFK.asComparison());
7231 
7232   auto *CD = cast<CXXConstructorDecl>(FD);
7233   assert(CD->getInheritedConstructor() &&
7234          "only defaulted functions and inherited constructors have implicit "
7235          "exception specs");
7236   Sema::InheritedConstructorInfo ICI(
7237       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7238   return ComputeDefaultedSpecialMemberExceptionSpec(
7239       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7240 }
7241 
7242 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7243                                                             CXXMethodDecl *MD) {
7244   FunctionProtoType::ExtProtoInfo EPI;
7245 
7246   // Build an exception specification pointing back at this member.
7247   EPI.ExceptionSpec.Type = EST_Unevaluated;
7248   EPI.ExceptionSpec.SourceDecl = MD;
7249 
7250   // Set the calling convention to the default for C++ instance methods.
7251   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7252       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7253                                             /*IsCXXMethod=*/true));
7254   return EPI;
7255 }
7256 
7257 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7258   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7259   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7260     return;
7261 
7262   // Evaluate the exception specification.
7263   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7264   auto ESI = IES.getExceptionSpec();
7265 
7266   // Update the type of the special member to use it.
7267   UpdateExceptionSpec(FD, ESI);
7268 }
7269 
7270 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7271   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7272 
7273   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7274   if (!DefKind) {
7275     assert(FD->getDeclContext()->isDependentContext());
7276     return;
7277   }
7278 
7279   if (DefKind.isSpecialMember()
7280           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7281                                                   DefKind.asSpecialMember())
7282           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7283     FD->setInvalidDecl();
7284 }
7285 
7286 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7287                                                  CXXSpecialMember CSM) {
7288   CXXRecordDecl *RD = MD->getParent();
7289 
7290   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7291          "not an explicitly-defaulted special member");
7292 
7293   // Defer all checking for special members of a dependent type.
7294   if (RD->isDependentType())
7295     return false;
7296 
7297   // Whether this was the first-declared instance of the constructor.
7298   // This affects whether we implicitly add an exception spec and constexpr.
7299   bool First = MD == MD->getCanonicalDecl();
7300 
7301   bool HadError = false;
7302 
7303   // C++11 [dcl.fct.def.default]p1:
7304   //   A function that is explicitly defaulted shall
7305   //     -- be a special member function [...] (checked elsewhere),
7306   //     -- have the same type (except for ref-qualifiers, and except that a
7307   //        copy operation can take a non-const reference) as an implicit
7308   //        declaration, and
7309   //     -- not have default arguments.
7310   // C++2a changes the second bullet to instead delete the function if it's
7311   // defaulted on its first declaration, unless it's "an assignment operator,
7312   // and its return type differs or its parameter type is not a reference".
7313   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7314   bool ShouldDeleteForTypeMismatch = false;
7315   unsigned ExpectedParams = 1;
7316   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7317     ExpectedParams = 0;
7318   if (MD->getNumParams() != ExpectedParams) {
7319     // This checks for default arguments: a copy or move constructor with a
7320     // default argument is classified as a default constructor, and assignment
7321     // operations and destructors can't have default arguments.
7322     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7323       << CSM << MD->getSourceRange();
7324     HadError = true;
7325   } else if (MD->isVariadic()) {
7326     if (DeleteOnTypeMismatch)
7327       ShouldDeleteForTypeMismatch = true;
7328     else {
7329       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7330         << CSM << MD->getSourceRange();
7331       HadError = true;
7332     }
7333   }
7334 
7335   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7336 
7337   bool CanHaveConstParam = false;
7338   if (CSM == CXXCopyConstructor)
7339     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7340   else if (CSM == CXXCopyAssignment)
7341     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7342 
7343   QualType ReturnType = Context.VoidTy;
7344   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7345     // Check for return type matching.
7346     ReturnType = Type->getReturnType();
7347 
7348     QualType DeclType = Context.getTypeDeclType(RD);
7349     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7350     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7351 
7352     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7353       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7354         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7355       HadError = true;
7356     }
7357 
7358     // A defaulted special member cannot have cv-qualifiers.
7359     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7360       if (DeleteOnTypeMismatch)
7361         ShouldDeleteForTypeMismatch = true;
7362       else {
7363         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7364           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7365         HadError = true;
7366       }
7367     }
7368   }
7369 
7370   // Check for parameter type matching.
7371   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7372   bool HasConstParam = false;
7373   if (ExpectedParams && ArgType->isReferenceType()) {
7374     // Argument must be reference to possibly-const T.
7375     QualType ReferentType = ArgType->getPointeeType();
7376     HasConstParam = ReferentType.isConstQualified();
7377 
7378     if (ReferentType.isVolatileQualified()) {
7379       if (DeleteOnTypeMismatch)
7380         ShouldDeleteForTypeMismatch = true;
7381       else {
7382         Diag(MD->getLocation(),
7383              diag::err_defaulted_special_member_volatile_param) << CSM;
7384         HadError = true;
7385       }
7386     }
7387 
7388     if (HasConstParam && !CanHaveConstParam) {
7389       if (DeleteOnTypeMismatch)
7390         ShouldDeleteForTypeMismatch = true;
7391       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7392         Diag(MD->getLocation(),
7393              diag::err_defaulted_special_member_copy_const_param)
7394           << (CSM == CXXCopyAssignment);
7395         // FIXME: Explain why this special member can't be const.
7396         HadError = true;
7397       } else {
7398         Diag(MD->getLocation(),
7399              diag::err_defaulted_special_member_move_const_param)
7400           << (CSM == CXXMoveAssignment);
7401         HadError = true;
7402       }
7403     }
7404   } else if (ExpectedParams) {
7405     // A copy assignment operator can take its argument by value, but a
7406     // defaulted one cannot.
7407     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7408     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7409     HadError = true;
7410   }
7411 
7412   // C++11 [dcl.fct.def.default]p2:
7413   //   An explicitly-defaulted function may be declared constexpr only if it
7414   //   would have been implicitly declared as constexpr,
7415   // Do not apply this rule to members of class templates, since core issue 1358
7416   // makes such functions always instantiate to constexpr functions. For
7417   // functions which cannot be constexpr (for non-constructors in C++11 and for
7418   // destructors in C++14 and C++17), this is checked elsewhere.
7419   //
7420   // FIXME: This should not apply if the member is deleted.
7421   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7422                                                      HasConstParam);
7423   if ((getLangOpts().CPlusPlus20 ||
7424        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7425                                   : isa<CXXConstructorDecl>(MD))) &&
7426       MD->isConstexpr() && !Constexpr &&
7427       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7428     Diag(MD->getBeginLoc(), MD->isConsteval()
7429                                 ? diag::err_incorrect_defaulted_consteval
7430                                 : diag::err_incorrect_defaulted_constexpr)
7431         << CSM;
7432     // FIXME: Explain why the special member can't be constexpr.
7433     HadError = true;
7434   }
7435 
7436   if (First) {
7437     // C++2a [dcl.fct.def.default]p3:
7438     //   If a function is explicitly defaulted on its first declaration, it is
7439     //   implicitly considered to be constexpr if the implicit declaration
7440     //   would be.
7441     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7442                                           ? ConstexprSpecKind::Consteval
7443                                           : ConstexprSpecKind::Constexpr)
7444                                    : ConstexprSpecKind::Unspecified);
7445 
7446     if (!Type->hasExceptionSpec()) {
7447       // C++2a [except.spec]p3:
7448       //   If a declaration of a function does not have a noexcept-specifier
7449       //   [and] is defaulted on its first declaration, [...] the exception
7450       //   specification is as specified below
7451       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7452       EPI.ExceptionSpec.Type = EST_Unevaluated;
7453       EPI.ExceptionSpec.SourceDecl = MD;
7454       MD->setType(Context.getFunctionType(ReturnType,
7455                                           llvm::makeArrayRef(&ArgType,
7456                                                              ExpectedParams),
7457                                           EPI));
7458     }
7459   }
7460 
7461   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7462     if (First) {
7463       SetDeclDeleted(MD, MD->getLocation());
7464       if (!inTemplateInstantiation() && !HadError) {
7465         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7466         if (ShouldDeleteForTypeMismatch) {
7467           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7468         } else {
7469           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7470         }
7471       }
7472       if (ShouldDeleteForTypeMismatch && !HadError) {
7473         Diag(MD->getLocation(),
7474              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7475       }
7476     } else {
7477       // C++11 [dcl.fct.def.default]p4:
7478       //   [For a] user-provided explicitly-defaulted function [...] if such a
7479       //   function is implicitly defined as deleted, the program is ill-formed.
7480       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7481       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7482       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7483       HadError = true;
7484     }
7485   }
7486 
7487   return HadError;
7488 }
7489 
7490 namespace {
7491 /// Helper class for building and checking a defaulted comparison.
7492 ///
7493 /// Defaulted functions are built in two phases:
7494 ///
7495 ///  * First, the set of operations that the function will perform are
7496 ///    identified, and some of them are checked. If any of the checked
7497 ///    operations is invalid in certain ways, the comparison function is
7498 ///    defined as deleted and no body is built.
7499 ///  * Then, if the function is not defined as deleted, the body is built.
7500 ///
7501 /// This is accomplished by performing two visitation steps over the eventual
7502 /// body of the function.
7503 template<typename Derived, typename ResultList, typename Result,
7504          typename Subobject>
7505 class DefaultedComparisonVisitor {
7506 public:
7507   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7508 
7509   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7510                              DefaultedComparisonKind DCK)
7511       : S(S), RD(RD), FD(FD), DCK(DCK) {
7512     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7513       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7514       // UnresolvedSet to avoid this copy.
7515       Fns.assign(Info->getUnqualifiedLookups().begin(),
7516                  Info->getUnqualifiedLookups().end());
7517     }
7518   }
7519 
7520   ResultList visit() {
7521     // The type of an lvalue naming a parameter of this function.
7522     QualType ParamLvalType =
7523         FD->getParamDecl(0)->getType().getNonReferenceType();
7524 
7525     ResultList Results;
7526 
7527     switch (DCK) {
7528     case DefaultedComparisonKind::None:
7529       llvm_unreachable("not a defaulted comparison");
7530 
7531     case DefaultedComparisonKind::Equal:
7532     case DefaultedComparisonKind::ThreeWay:
7533       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7534       return Results;
7535 
7536     case DefaultedComparisonKind::NotEqual:
7537     case DefaultedComparisonKind::Relational:
7538       Results.add(getDerived().visitExpandedSubobject(
7539           ParamLvalType, getDerived().getCompleteObject()));
7540       return Results;
7541     }
7542     llvm_unreachable("");
7543   }
7544 
7545 protected:
7546   Derived &getDerived() { return static_cast<Derived&>(*this); }
7547 
7548   /// Visit the expanded list of subobjects of the given type, as specified in
7549   /// C++2a [class.compare.default].
7550   ///
7551   /// \return \c true if the ResultList object said we're done, \c false if not.
7552   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7553                        Qualifiers Quals) {
7554     // C++2a [class.compare.default]p4:
7555     //   The direct base class subobjects of C
7556     for (CXXBaseSpecifier &Base : Record->bases())
7557       if (Results.add(getDerived().visitSubobject(
7558               S.Context.getQualifiedType(Base.getType(), Quals),
7559               getDerived().getBase(&Base))))
7560         return true;
7561 
7562     //   followed by the non-static data members of C
7563     for (FieldDecl *Field : Record->fields()) {
7564       // Recursively expand anonymous structs.
7565       if (Field->isAnonymousStructOrUnion()) {
7566         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7567                             Quals))
7568           return true;
7569         continue;
7570       }
7571 
7572       // Figure out the type of an lvalue denoting this field.
7573       Qualifiers FieldQuals = Quals;
7574       if (Field->isMutable())
7575         FieldQuals.removeConst();
7576       QualType FieldType =
7577           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7578 
7579       if (Results.add(getDerived().visitSubobject(
7580               FieldType, getDerived().getField(Field))))
7581         return true;
7582     }
7583 
7584     //   form a list of subobjects.
7585     return false;
7586   }
7587 
7588   Result visitSubobject(QualType Type, Subobject Subobj) {
7589     //   In that list, any subobject of array type is recursively expanded
7590     const ArrayType *AT = S.Context.getAsArrayType(Type);
7591     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7592       return getDerived().visitSubobjectArray(CAT->getElementType(),
7593                                               CAT->getSize(), Subobj);
7594     return getDerived().visitExpandedSubobject(Type, Subobj);
7595   }
7596 
7597   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7598                              Subobject Subobj) {
7599     return getDerived().visitSubobject(Type, Subobj);
7600   }
7601 
7602 protected:
7603   Sema &S;
7604   CXXRecordDecl *RD;
7605   FunctionDecl *FD;
7606   DefaultedComparisonKind DCK;
7607   UnresolvedSet<16> Fns;
7608 };
7609 
7610 /// Information about a defaulted comparison, as determined by
7611 /// DefaultedComparisonAnalyzer.
7612 struct DefaultedComparisonInfo {
7613   bool Deleted = false;
7614   bool Constexpr = true;
7615   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7616 
7617   static DefaultedComparisonInfo deleted() {
7618     DefaultedComparisonInfo Deleted;
7619     Deleted.Deleted = true;
7620     return Deleted;
7621   }
7622 
7623   bool add(const DefaultedComparisonInfo &R) {
7624     Deleted |= R.Deleted;
7625     Constexpr &= R.Constexpr;
7626     Category = commonComparisonType(Category, R.Category);
7627     return Deleted;
7628   }
7629 };
7630 
7631 /// An element in the expanded list of subobjects of a defaulted comparison, as
7632 /// specified in C++2a [class.compare.default]p4.
7633 struct DefaultedComparisonSubobject {
7634   enum { CompleteObject, Member, Base } Kind;
7635   NamedDecl *Decl;
7636   SourceLocation Loc;
7637 };
7638 
7639 /// A visitor over the notional body of a defaulted comparison that determines
7640 /// whether that body would be deleted or constexpr.
7641 class DefaultedComparisonAnalyzer
7642     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7643                                         DefaultedComparisonInfo,
7644                                         DefaultedComparisonInfo,
7645                                         DefaultedComparisonSubobject> {
7646 public:
7647   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7648 
7649 private:
7650   DiagnosticKind Diagnose;
7651 
7652 public:
7653   using Base = DefaultedComparisonVisitor;
7654   using Result = DefaultedComparisonInfo;
7655   using Subobject = DefaultedComparisonSubobject;
7656 
7657   friend Base;
7658 
7659   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7660                               DefaultedComparisonKind DCK,
7661                               DiagnosticKind Diagnose = NoDiagnostics)
7662       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7663 
7664   Result visit() {
7665     if ((DCK == DefaultedComparisonKind::Equal ||
7666          DCK == DefaultedComparisonKind::ThreeWay) &&
7667         RD->hasVariantMembers()) {
7668       // C++2a [class.compare.default]p2 [P2002R0]:
7669       //   A defaulted comparison operator function for class C is defined as
7670       //   deleted if [...] C has variant members.
7671       if (Diagnose == ExplainDeleted) {
7672         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7673           << FD << RD->isUnion() << RD;
7674       }
7675       return Result::deleted();
7676     }
7677 
7678     return Base::visit();
7679   }
7680 
7681 private:
7682   Subobject getCompleteObject() {
7683     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7684   }
7685 
7686   Subobject getBase(CXXBaseSpecifier *Base) {
7687     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7688                      Base->getBaseTypeLoc()};
7689   }
7690 
7691   Subobject getField(FieldDecl *Field) {
7692     return Subobject{Subobject::Member, Field, Field->getLocation()};
7693   }
7694 
7695   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7696     // C++2a [class.compare.default]p2 [P2002R0]:
7697     //   A defaulted <=> or == operator function for class C is defined as
7698     //   deleted if any non-static data member of C is of reference type
7699     if (Type->isReferenceType()) {
7700       if (Diagnose == ExplainDeleted) {
7701         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7702             << FD << RD;
7703       }
7704       return Result::deleted();
7705     }
7706 
7707     // [...] Let xi be an lvalue denoting the ith element [...]
7708     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7709     Expr *Args[] = {&Xi, &Xi};
7710 
7711     // All operators start by trying to apply that same operator recursively.
7712     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7713     assert(OO != OO_None && "not an overloaded operator!");
7714     return visitBinaryOperator(OO, Args, Subobj);
7715   }
7716 
7717   Result
7718   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7719                       Subobject Subobj,
7720                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7721     // Note that there is no need to consider rewritten candidates here if
7722     // we've already found there is no viable 'operator<=>' candidate (and are
7723     // considering synthesizing a '<=>' from '==' and '<').
7724     OverloadCandidateSet CandidateSet(
7725         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7726         OverloadCandidateSet::OperatorRewriteInfo(
7727             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7728 
7729     /// C++2a [class.compare.default]p1 [P2002R0]:
7730     ///   [...] the defaulted function itself is never a candidate for overload
7731     ///   resolution [...]
7732     CandidateSet.exclude(FD);
7733 
7734     if (Args[0]->getType()->isOverloadableType())
7735       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7736     else if (OO == OO_EqualEqual ||
7737              !Args[0]->getType()->isFunctionPointerType()) {
7738       // FIXME: We determine whether this is a valid expression by checking to
7739       // see if there's a viable builtin operator candidate for it. That isn't
7740       // really what the rules ask us to do, but should give the right results.
7741       //
7742       // Note that the builtin operator for relational comparisons on function
7743       // pointers is the only known case which cannot be used.
7744       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7745     }
7746 
7747     Result R;
7748 
7749     OverloadCandidateSet::iterator Best;
7750     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7751     case OR_Success: {
7752       // C++2a [class.compare.secondary]p2 [P2002R0]:
7753       //   The operator function [...] is defined as deleted if [...] the
7754       //   candidate selected by overload resolution is not a rewritten
7755       //   candidate.
7756       if ((DCK == DefaultedComparisonKind::NotEqual ||
7757            DCK == DefaultedComparisonKind::Relational) &&
7758           !Best->RewriteKind) {
7759         if (Diagnose == ExplainDeleted) {
7760           S.Diag(Best->Function->getLocation(),
7761                  diag::note_defaulted_comparison_not_rewritten_callee)
7762               << FD;
7763         }
7764         return Result::deleted();
7765       }
7766 
7767       // Throughout C++2a [class.compare]: if overload resolution does not
7768       // result in a usable function, the candidate function is defined as
7769       // deleted. This requires that we selected an accessible function.
7770       //
7771       // Note that this only considers the access of the function when named
7772       // within the type of the subobject, and not the access path for any
7773       // derived-to-base conversion.
7774       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7775       if (ArgClass && Best->FoundDecl.getDecl() &&
7776           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7777         QualType ObjectType = Subobj.Kind == Subobject::Member
7778                                   ? Args[0]->getType()
7779                                   : S.Context.getRecordType(RD);
7780         if (!S.isMemberAccessibleForDeletion(
7781                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7782                 Diagnose == ExplainDeleted
7783                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7784                           << FD << Subobj.Kind << Subobj.Decl
7785                     : S.PDiag()))
7786           return Result::deleted();
7787       }
7788 
7789       // C++2a [class.compare.default]p3 [P2002R0]:
7790       //   A defaulted comparison function is constexpr-compatible if [...]
7791       //   no overlod resolution performed [...] results in a non-constexpr
7792       //   function.
7793       if (FunctionDecl *BestFD = Best->Function) {
7794         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7795         // If it's not constexpr, explain why not.
7796         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7797           if (Subobj.Kind != Subobject::CompleteObject)
7798             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7799               << Subobj.Kind << Subobj.Decl;
7800           S.Diag(BestFD->getLocation(),
7801                  diag::note_defaulted_comparison_not_constexpr_here);
7802           // Bail out after explaining; we don't want any more notes.
7803           return Result::deleted();
7804         }
7805         R.Constexpr &= BestFD->isConstexpr();
7806       }
7807 
7808       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7809         if (auto *BestFD = Best->Function) {
7810           // If any callee has an undeduced return type, deduce it now.
7811           // FIXME: It's not clear how a failure here should be handled. For
7812           // now, we produce an eager diagnostic, because that is forward
7813           // compatible with most (all?) other reasonable options.
7814           if (BestFD->getReturnType()->isUndeducedType() &&
7815               S.DeduceReturnType(BestFD, FD->getLocation(),
7816                                  /*Diagnose=*/false)) {
7817             // Don't produce a duplicate error when asked to explain why the
7818             // comparison is deleted: we diagnosed that when initially checking
7819             // the defaulted operator.
7820             if (Diagnose == NoDiagnostics) {
7821               S.Diag(
7822                   FD->getLocation(),
7823                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7824                   << Subobj.Kind << Subobj.Decl;
7825               S.Diag(
7826                   Subobj.Loc,
7827                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7828                   << Subobj.Kind << Subobj.Decl;
7829               S.Diag(BestFD->getLocation(),
7830                      diag::note_defaulted_comparison_cannot_deduce_callee)
7831                   << Subobj.Kind << Subobj.Decl;
7832             }
7833             return Result::deleted();
7834           }
7835           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7836               BestFD->getCallResultType())) {
7837             R.Category = Info->Kind;
7838           } else {
7839             if (Diagnose == ExplainDeleted) {
7840               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7841                   << Subobj.Kind << Subobj.Decl
7842                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7843               S.Diag(BestFD->getLocation(),
7844                      diag::note_defaulted_comparison_cannot_deduce_callee)
7845                   << Subobj.Kind << Subobj.Decl;
7846             }
7847             return Result::deleted();
7848           }
7849         } else {
7850           Optional<ComparisonCategoryType> Cat =
7851               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7852           assert(Cat && "no category for builtin comparison?");
7853           R.Category = *Cat;
7854         }
7855       }
7856 
7857       // Note that we might be rewriting to a different operator. That call is
7858       // not considered until we come to actually build the comparison function.
7859       break;
7860     }
7861 
7862     case OR_Ambiguous:
7863       if (Diagnose == ExplainDeleted) {
7864         unsigned Kind = 0;
7865         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7866           Kind = OO == OO_EqualEqual ? 1 : 2;
7867         CandidateSet.NoteCandidates(
7868             PartialDiagnosticAt(
7869                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7870                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7871             S, OCD_AmbiguousCandidates, Args);
7872       }
7873       R = Result::deleted();
7874       break;
7875 
7876     case OR_Deleted:
7877       if (Diagnose == ExplainDeleted) {
7878         if ((DCK == DefaultedComparisonKind::NotEqual ||
7879              DCK == DefaultedComparisonKind::Relational) &&
7880             !Best->RewriteKind) {
7881           S.Diag(Best->Function->getLocation(),
7882                  diag::note_defaulted_comparison_not_rewritten_callee)
7883               << FD;
7884         } else {
7885           S.Diag(Subobj.Loc,
7886                  diag::note_defaulted_comparison_calls_deleted)
7887               << FD << Subobj.Kind << Subobj.Decl;
7888           S.NoteDeletedFunction(Best->Function);
7889         }
7890       }
7891       R = Result::deleted();
7892       break;
7893 
7894     case OR_No_Viable_Function:
7895       // If there's no usable candidate, we're done unless we can rewrite a
7896       // '<=>' in terms of '==' and '<'.
7897       if (OO == OO_Spaceship &&
7898           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7899         // For any kind of comparison category return type, we need a usable
7900         // '==' and a usable '<'.
7901         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7902                                        &CandidateSet)))
7903           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7904         break;
7905       }
7906 
7907       if (Diagnose == ExplainDeleted) {
7908         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7909             << FD << Subobj.Kind << Subobj.Decl;
7910 
7911         // For a three-way comparison, list both the candidates for the
7912         // original operator and the candidates for the synthesized operator.
7913         if (SpaceshipCandidates) {
7914           SpaceshipCandidates->NoteCandidates(
7915               S, Args,
7916               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7917                                                       Args, FD->getLocation()));
7918           S.Diag(Subobj.Loc,
7919                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7920               << (OO == OO_EqualEqual ? 0 : 1);
7921         }
7922 
7923         CandidateSet.NoteCandidates(
7924             S, Args,
7925             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7926                                             FD->getLocation()));
7927       }
7928       R = Result::deleted();
7929       break;
7930     }
7931 
7932     return R;
7933   }
7934 };
7935 
7936 /// A list of statements.
7937 struct StmtListResult {
7938   bool IsInvalid = false;
7939   llvm::SmallVector<Stmt*, 16> Stmts;
7940 
7941   bool add(const StmtResult &S) {
7942     IsInvalid |= S.isInvalid();
7943     if (IsInvalid)
7944       return true;
7945     Stmts.push_back(S.get());
7946     return false;
7947   }
7948 };
7949 
7950 /// A visitor over the notional body of a defaulted comparison that synthesizes
7951 /// the actual body.
7952 class DefaultedComparisonSynthesizer
7953     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7954                                         StmtListResult, StmtResult,
7955                                         std::pair<ExprResult, ExprResult>> {
7956   SourceLocation Loc;
7957   unsigned ArrayDepth = 0;
7958 
7959 public:
7960   using Base = DefaultedComparisonVisitor;
7961   using ExprPair = std::pair<ExprResult, ExprResult>;
7962 
7963   friend Base;
7964 
7965   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7966                                  DefaultedComparisonKind DCK,
7967                                  SourceLocation BodyLoc)
7968       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7969 
7970   /// Build a suitable function body for this defaulted comparison operator.
7971   StmtResult build() {
7972     Sema::CompoundScopeRAII CompoundScope(S);
7973 
7974     StmtListResult Stmts = visit();
7975     if (Stmts.IsInvalid)
7976       return StmtError();
7977 
7978     ExprResult RetVal;
7979     switch (DCK) {
7980     case DefaultedComparisonKind::None:
7981       llvm_unreachable("not a defaulted comparison");
7982 
7983     case DefaultedComparisonKind::Equal: {
7984       // C++2a [class.eq]p3:
7985       //   [...] compar[e] the corresponding elements [...] until the first
7986       //   index i where xi == yi yields [...] false. If no such index exists,
7987       //   V is true. Otherwise, V is false.
7988       //
7989       // Join the comparisons with '&&'s and return the result. Use a right
7990       // fold (traversing the conditions right-to-left), because that
7991       // short-circuits more naturally.
7992       auto OldStmts = std::move(Stmts.Stmts);
7993       Stmts.Stmts.clear();
7994       ExprResult CmpSoFar;
7995       // Finish a particular comparison chain.
7996       auto FinishCmp = [&] {
7997         if (Expr *Prior = CmpSoFar.get()) {
7998           // Convert the last expression to 'return ...;'
7999           if (RetVal.isUnset() && Stmts.Stmts.empty())
8000             RetVal = CmpSoFar;
8001           // Convert any prior comparison to 'if (!(...)) return false;'
8002           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8003             return true;
8004           CmpSoFar = ExprResult();
8005         }
8006         return false;
8007       };
8008       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8009         Expr *E = dyn_cast<Expr>(EAsStmt);
8010         if (!E) {
8011           // Found an array comparison.
8012           if (FinishCmp() || Stmts.add(EAsStmt))
8013             return StmtError();
8014           continue;
8015         }
8016 
8017         if (CmpSoFar.isUnset()) {
8018           CmpSoFar = E;
8019           continue;
8020         }
8021         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8022         if (CmpSoFar.isInvalid())
8023           return StmtError();
8024       }
8025       if (FinishCmp())
8026         return StmtError();
8027       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8028       //   If no such index exists, V is true.
8029       if (RetVal.isUnset())
8030         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8031       break;
8032     }
8033 
8034     case DefaultedComparisonKind::ThreeWay: {
8035       // Per C++2a [class.spaceship]p3, as a fallback add:
8036       // return static_cast<R>(std::strong_ordering::equal);
8037       QualType StrongOrdering = S.CheckComparisonCategoryType(
8038           ComparisonCategoryType::StrongOrdering, Loc,
8039           Sema::ComparisonCategoryUsage::DefaultedOperator);
8040       if (StrongOrdering.isNull())
8041         return StmtError();
8042       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8043                              .getValueInfo(ComparisonCategoryResult::Equal)
8044                              ->VD;
8045       RetVal = getDecl(EqualVD);
8046       if (RetVal.isInvalid())
8047         return StmtError();
8048       RetVal = buildStaticCastToR(RetVal.get());
8049       break;
8050     }
8051 
8052     case DefaultedComparisonKind::NotEqual:
8053     case DefaultedComparisonKind::Relational:
8054       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8055       break;
8056     }
8057 
8058     // Build the final return statement.
8059     if (RetVal.isInvalid())
8060       return StmtError();
8061     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8062     if (ReturnStmt.isInvalid())
8063       return StmtError();
8064     Stmts.Stmts.push_back(ReturnStmt.get());
8065 
8066     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8067   }
8068 
8069 private:
8070   ExprResult getDecl(ValueDecl *VD) {
8071     return S.BuildDeclarationNameExpr(
8072         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8073   }
8074 
8075   ExprResult getParam(unsigned I) {
8076     ParmVarDecl *PD = FD->getParamDecl(I);
8077     return getDecl(PD);
8078   }
8079 
8080   ExprPair getCompleteObject() {
8081     unsigned Param = 0;
8082     ExprResult LHS;
8083     if (isa<CXXMethodDecl>(FD)) {
8084       // LHS is '*this'.
8085       LHS = S.ActOnCXXThis(Loc);
8086       if (!LHS.isInvalid())
8087         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8088     } else {
8089       LHS = getParam(Param++);
8090     }
8091     ExprResult RHS = getParam(Param++);
8092     assert(Param == FD->getNumParams());
8093     return {LHS, RHS};
8094   }
8095 
8096   ExprPair getBase(CXXBaseSpecifier *Base) {
8097     ExprPair Obj = getCompleteObject();
8098     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8099       return {ExprError(), ExprError()};
8100     CXXCastPath Path = {Base};
8101     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8102                                 CK_DerivedToBase, VK_LValue, &Path),
8103             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8104                                 CK_DerivedToBase, VK_LValue, &Path)};
8105   }
8106 
8107   ExprPair getField(FieldDecl *Field) {
8108     ExprPair Obj = getCompleteObject();
8109     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8110       return {ExprError(), ExprError()};
8111 
8112     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8113     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8114     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8115                                       CXXScopeSpec(), Field, Found, NameInfo),
8116             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8117                                       CXXScopeSpec(), Field, Found, NameInfo)};
8118   }
8119 
8120   // FIXME: When expanding a subobject, register a note in the code synthesis
8121   // stack to say which subobject we're comparing.
8122 
8123   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8124     if (Cond.isInvalid())
8125       return StmtError();
8126 
8127     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8128     if (NotCond.isInvalid())
8129       return StmtError();
8130 
8131     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8132     assert(!False.isInvalid() && "should never fail");
8133     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8134     if (ReturnFalse.isInvalid())
8135       return StmtError();
8136 
8137     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8138                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8139                                           Sema::ConditionKind::Boolean),
8140                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8141   }
8142 
8143   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8144                                  ExprPair Subobj) {
8145     QualType SizeType = S.Context.getSizeType();
8146     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8147 
8148     // Build 'size_t i$n = 0'.
8149     IdentifierInfo *IterationVarName = nullptr;
8150     {
8151       SmallString<8> Str;
8152       llvm::raw_svector_ostream OS(Str);
8153       OS << "i" << ArrayDepth;
8154       IterationVarName = &S.Context.Idents.get(OS.str());
8155     }
8156     VarDecl *IterationVar = VarDecl::Create(
8157         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8158         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8159     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8160     IterationVar->setInit(
8161         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8162     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8163 
8164     auto IterRef = [&] {
8165       ExprResult Ref = S.BuildDeclarationNameExpr(
8166           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8167           IterationVar);
8168       assert(!Ref.isInvalid() && "can't reference our own variable?");
8169       return Ref.get();
8170     };
8171 
8172     // Build 'i$n != Size'.
8173     ExprResult Cond = S.CreateBuiltinBinOp(
8174         Loc, BO_NE, IterRef(),
8175         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8176     assert(!Cond.isInvalid() && "should never fail");
8177 
8178     // Build '++i$n'.
8179     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8180     assert(!Inc.isInvalid() && "should never fail");
8181 
8182     // Build 'a[i$n]' and 'b[i$n]'.
8183     auto Index = [&](ExprResult E) {
8184       if (E.isInvalid())
8185         return ExprError();
8186       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8187     };
8188     Subobj.first = Index(Subobj.first);
8189     Subobj.second = Index(Subobj.second);
8190 
8191     // Compare the array elements.
8192     ++ArrayDepth;
8193     StmtResult Substmt = visitSubobject(Type, Subobj);
8194     --ArrayDepth;
8195 
8196     if (Substmt.isInvalid())
8197       return StmtError();
8198 
8199     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8200     // For outer levels or for an 'operator<=>' we already have a suitable
8201     // statement that returns as necessary.
8202     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8203       assert(DCK == DefaultedComparisonKind::Equal &&
8204              "should have non-expression statement");
8205       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8206       if (Substmt.isInvalid())
8207         return StmtError();
8208     }
8209 
8210     // Build 'for (...) ...'
8211     return S.ActOnForStmt(Loc, Loc, Init,
8212                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8213                                            Sema::ConditionKind::Boolean),
8214                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8215                           Substmt.get());
8216   }
8217 
8218   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8219     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8220       return StmtError();
8221 
8222     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8223     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8224     ExprResult Op;
8225     if (Type->isOverloadableType())
8226       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8227                                    Obj.second.get(), /*PerformADL=*/true,
8228                                    /*AllowRewrittenCandidates=*/true, FD);
8229     else
8230       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8231     if (Op.isInvalid())
8232       return StmtError();
8233 
8234     switch (DCK) {
8235     case DefaultedComparisonKind::None:
8236       llvm_unreachable("not a defaulted comparison");
8237 
8238     case DefaultedComparisonKind::Equal:
8239       // Per C++2a [class.eq]p2, each comparison is individually contextually
8240       // converted to bool.
8241       Op = S.PerformContextuallyConvertToBool(Op.get());
8242       if (Op.isInvalid())
8243         return StmtError();
8244       return Op.get();
8245 
8246     case DefaultedComparisonKind::ThreeWay: {
8247       // Per C++2a [class.spaceship]p3, form:
8248       //   if (R cmp = static_cast<R>(op); cmp != 0)
8249       //     return cmp;
8250       QualType R = FD->getReturnType();
8251       Op = buildStaticCastToR(Op.get());
8252       if (Op.isInvalid())
8253         return StmtError();
8254 
8255       // R cmp = ...;
8256       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8257       VarDecl *VD =
8258           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8259                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8260       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8261       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8262 
8263       // cmp != 0
8264       ExprResult VDRef = getDecl(VD);
8265       if (VDRef.isInvalid())
8266         return StmtError();
8267       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8268       Expr *Zero =
8269           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8270       ExprResult Comp;
8271       if (VDRef.get()->getType()->isOverloadableType())
8272         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8273                                        true, FD);
8274       else
8275         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8276       if (Comp.isInvalid())
8277         return StmtError();
8278       Sema::ConditionResult Cond = S.ActOnCondition(
8279           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8280       if (Cond.isInvalid())
8281         return StmtError();
8282 
8283       // return cmp;
8284       VDRef = getDecl(VD);
8285       if (VDRef.isInvalid())
8286         return StmtError();
8287       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8288       if (ReturnStmt.isInvalid())
8289         return StmtError();
8290 
8291       // if (...)
8292       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8293                            ReturnStmt.get(),
8294                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8295     }
8296 
8297     case DefaultedComparisonKind::NotEqual:
8298     case DefaultedComparisonKind::Relational:
8299       // C++2a [class.compare.secondary]p2:
8300       //   Otherwise, the operator function yields x @ y.
8301       return Op.get();
8302     }
8303     llvm_unreachable("");
8304   }
8305 
8306   /// Build "static_cast<R>(E)".
8307   ExprResult buildStaticCastToR(Expr *E) {
8308     QualType R = FD->getReturnType();
8309     assert(!R->isUndeducedType() && "type should have been deduced already");
8310 
8311     // Don't bother forming a no-op cast in the common case.
8312     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8313       return E;
8314     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8315                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8316                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8317   }
8318 };
8319 }
8320 
8321 /// Perform the unqualified lookups that might be needed to form a defaulted
8322 /// comparison function for the given operator.
8323 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8324                                                   UnresolvedSetImpl &Operators,
8325                                                   OverloadedOperatorKind Op) {
8326   auto Lookup = [&](OverloadedOperatorKind OO) {
8327     Self.LookupOverloadedOperatorName(OO, S, Operators);
8328   };
8329 
8330   // Every defaulted operator looks up itself.
8331   Lookup(Op);
8332   // ... and the rewritten form of itself, if any.
8333   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8334     Lookup(ExtraOp);
8335 
8336   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8337   // synthesize a three-way comparison from '<' and '=='. In a dependent
8338   // context, we also need to look up '==' in case we implicitly declare a
8339   // defaulted 'operator=='.
8340   if (Op == OO_Spaceship) {
8341     Lookup(OO_ExclaimEqual);
8342     Lookup(OO_Less);
8343     Lookup(OO_EqualEqual);
8344   }
8345 }
8346 
8347 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8348                                               DefaultedComparisonKind DCK) {
8349   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8350 
8351   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8352   assert(RD && "defaulted comparison is not defaulted in a class");
8353 
8354   // Perform any unqualified lookups we're going to need to default this
8355   // function.
8356   if (S) {
8357     UnresolvedSet<32> Operators;
8358     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8359                                           FD->getOverloadedOperator());
8360     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8361         Context, Operators.pairs()));
8362   }
8363 
8364   // C++2a [class.compare.default]p1:
8365   //   A defaulted comparison operator function for some class C shall be a
8366   //   non-template function declared in the member-specification of C that is
8367   //    -- a non-static const member of C having one parameter of type
8368   //       const C&, or
8369   //    -- a friend of C having two parameters of type const C& or two
8370   //       parameters of type C.
8371   QualType ExpectedParmType1 = Context.getRecordType(RD);
8372   QualType ExpectedParmType2 =
8373       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8374   if (isa<CXXMethodDecl>(FD))
8375     ExpectedParmType1 = ExpectedParmType2;
8376   for (const ParmVarDecl *Param : FD->parameters()) {
8377     if (!Param->getType()->isDependentType() &&
8378         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8379         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8380       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8381       // corresponding defaulted 'operator<=>' already.
8382       if (!FD->isImplicit()) {
8383         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8384             << (int)DCK << Param->getType() << ExpectedParmType1
8385             << !isa<CXXMethodDecl>(FD)
8386             << ExpectedParmType2 << Param->getSourceRange();
8387       }
8388       return true;
8389     }
8390   }
8391   if (FD->getNumParams() == 2 &&
8392       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8393                            FD->getParamDecl(1)->getType())) {
8394     if (!FD->isImplicit()) {
8395       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8396           << (int)DCK
8397           << FD->getParamDecl(0)->getType()
8398           << FD->getParamDecl(0)->getSourceRange()
8399           << FD->getParamDecl(1)->getType()
8400           << FD->getParamDecl(1)->getSourceRange();
8401     }
8402     return true;
8403   }
8404 
8405   // ... non-static const member ...
8406   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8407     assert(!MD->isStatic() && "comparison function cannot be a static member");
8408     if (!MD->isConst()) {
8409       SourceLocation InsertLoc;
8410       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8411         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8412       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8413       // corresponding defaulted 'operator<=>' already.
8414       if (!MD->isImplicit()) {
8415         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8416           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8417       }
8418 
8419       // Add the 'const' to the type to recover.
8420       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8421       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8422       EPI.TypeQuals.addConst();
8423       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8424                                           FPT->getParamTypes(), EPI));
8425     }
8426   } else {
8427     // A non-member function declared in a class must be a friend.
8428     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8429   }
8430 
8431   // C++2a [class.eq]p1, [class.rel]p1:
8432   //   A [defaulted comparison other than <=>] shall have a declared return
8433   //   type bool.
8434   if (DCK != DefaultedComparisonKind::ThreeWay &&
8435       !FD->getDeclaredReturnType()->isDependentType() &&
8436       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8437     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8438         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8439         << FD->getReturnTypeSourceRange();
8440     return true;
8441   }
8442   // C++2a [class.spaceship]p2 [P2002R0]:
8443   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8444   //   R shall not contain a placeholder type.
8445   if (DCK == DefaultedComparisonKind::ThreeWay &&
8446       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8447       !Context.hasSameType(FD->getDeclaredReturnType(),
8448                            Context.getAutoDeductType())) {
8449     Diag(FD->getLocation(),
8450          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8451         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8452         << FD->getReturnTypeSourceRange();
8453     return true;
8454   }
8455 
8456   // For a defaulted function in a dependent class, defer all remaining checks
8457   // until instantiation.
8458   if (RD->isDependentType())
8459     return false;
8460 
8461   // Determine whether the function should be defined as deleted.
8462   DefaultedComparisonInfo Info =
8463       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8464 
8465   bool First = FD == FD->getCanonicalDecl();
8466 
8467   // If we want to delete the function, then do so; there's nothing else to
8468   // check in that case.
8469   if (Info.Deleted) {
8470     if (!First) {
8471       // C++11 [dcl.fct.def.default]p4:
8472       //   [For a] user-provided explicitly-defaulted function [...] if such a
8473       //   function is implicitly defined as deleted, the program is ill-formed.
8474       //
8475       // This is really just a consequence of the general rule that you can
8476       // only delete a function on its first declaration.
8477       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8478           << FD->isImplicit() << (int)DCK;
8479       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8480                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8481           .visit();
8482       return true;
8483     }
8484 
8485     SetDeclDeleted(FD, FD->getLocation());
8486     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8487       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8488           << (int)DCK;
8489       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8490                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8491           .visit();
8492     }
8493     return false;
8494   }
8495 
8496   // C++2a [class.spaceship]p2:
8497   //   The return type is deduced as the common comparison type of R0, R1, ...
8498   if (DCK == DefaultedComparisonKind::ThreeWay &&
8499       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8500     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8501     if (RetLoc.isInvalid())
8502       RetLoc = FD->getBeginLoc();
8503     // FIXME: Should we really care whether we have the complete type and the
8504     // 'enumerator' constants here? A forward declaration seems sufficient.
8505     QualType Cat = CheckComparisonCategoryType(
8506         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8507     if (Cat.isNull())
8508       return true;
8509     Context.adjustDeducedFunctionResultType(
8510         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8511   }
8512 
8513   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8514   //   An explicitly-defaulted function that is not defined as deleted may be
8515   //   declared constexpr or consteval only if it is constexpr-compatible.
8516   // C++2a [class.compare.default]p3 [P2002R0]:
8517   //   A defaulted comparison function is constexpr-compatible if it satisfies
8518   //   the requirements for a constexpr function [...]
8519   // The only relevant requirements are that the parameter and return types are
8520   // literal types. The remaining conditions are checked by the analyzer.
8521   if (FD->isConstexpr()) {
8522     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8523         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8524         !Info.Constexpr) {
8525       Diag(FD->getBeginLoc(),
8526            diag::err_incorrect_defaulted_comparison_constexpr)
8527           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8528       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8529                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8530           .visit();
8531     }
8532   }
8533 
8534   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8535   //   If a constexpr-compatible function is explicitly defaulted on its first
8536   //   declaration, it is implicitly considered to be constexpr.
8537   // FIXME: Only applying this to the first declaration seems problematic, as
8538   // simple reorderings can affect the meaning of the program.
8539   if (First && !FD->isConstexpr() && Info.Constexpr)
8540     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8541 
8542   // C++2a [except.spec]p3:
8543   //   If a declaration of a function does not have a noexcept-specifier
8544   //   [and] is defaulted on its first declaration, [...] the exception
8545   //   specification is as specified below
8546   if (FD->getExceptionSpecType() == EST_None) {
8547     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8548     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8549     EPI.ExceptionSpec.Type = EST_Unevaluated;
8550     EPI.ExceptionSpec.SourceDecl = FD;
8551     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8552                                         FPT->getParamTypes(), EPI));
8553   }
8554 
8555   return false;
8556 }
8557 
8558 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8559                                              FunctionDecl *Spaceship) {
8560   Sema::CodeSynthesisContext Ctx;
8561   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8562   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8563   Ctx.Entity = Spaceship;
8564   pushCodeSynthesisContext(Ctx);
8565 
8566   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8567     EqualEqual->setImplicit();
8568 
8569   popCodeSynthesisContext();
8570 }
8571 
8572 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8573                                      DefaultedComparisonKind DCK) {
8574   assert(FD->isDefaulted() && !FD->isDeleted() &&
8575          !FD->doesThisDeclarationHaveABody());
8576   if (FD->willHaveBody() || FD->isInvalidDecl())
8577     return;
8578 
8579   SynthesizedFunctionScope Scope(*this, FD);
8580 
8581   // Add a context note for diagnostics produced after this point.
8582   Scope.addContextNote(UseLoc);
8583 
8584   {
8585     // Build and set up the function body.
8586     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8587     SourceLocation BodyLoc =
8588         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8589     StmtResult Body =
8590         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8591     if (Body.isInvalid()) {
8592       FD->setInvalidDecl();
8593       return;
8594     }
8595     FD->setBody(Body.get());
8596     FD->markUsed(Context);
8597   }
8598 
8599   // The exception specification is needed because we are defining the
8600   // function. Note that this will reuse the body we just built.
8601   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8602 
8603   if (ASTMutationListener *L = getASTMutationListener())
8604     L->CompletedImplicitDefinition(FD);
8605 }
8606 
8607 static Sema::ImplicitExceptionSpecification
8608 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8609                                         FunctionDecl *FD,
8610                                         Sema::DefaultedComparisonKind DCK) {
8611   ComputingExceptionSpec CES(S, FD, Loc);
8612   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8613 
8614   if (FD->isInvalidDecl())
8615     return ExceptSpec;
8616 
8617   // The common case is that we just defined the comparison function. In that
8618   // case, just look at whether the body can throw.
8619   if (FD->hasBody()) {
8620     ExceptSpec.CalledStmt(FD->getBody());
8621   } else {
8622     // Otherwise, build a body so we can check it. This should ideally only
8623     // happen when we're not actually marking the function referenced. (This is
8624     // only really important for efficiency: we don't want to build and throw
8625     // away bodies for comparison functions more than we strictly need to.)
8626 
8627     // Pretend to synthesize the function body in an unevaluated context.
8628     // Note that we can't actually just go ahead and define the function here:
8629     // we are not permitted to mark its callees as referenced.
8630     Sema::SynthesizedFunctionScope Scope(S, FD);
8631     EnterExpressionEvaluationContext Context(
8632         S, Sema::ExpressionEvaluationContext::Unevaluated);
8633 
8634     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8635     SourceLocation BodyLoc =
8636         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8637     StmtResult Body =
8638         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8639     if (!Body.isInvalid())
8640       ExceptSpec.CalledStmt(Body.get());
8641 
8642     // FIXME: Can we hold onto this body and just transform it to potentially
8643     // evaluated when we're asked to define the function rather than rebuilding
8644     // it? Either that, or we should only build the bits of the body that we
8645     // need (the expressions, not the statements).
8646   }
8647 
8648   return ExceptSpec;
8649 }
8650 
8651 void Sema::CheckDelayedMemberExceptionSpecs() {
8652   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8653   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8654 
8655   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8656   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8657 
8658   // Perform any deferred checking of exception specifications for virtual
8659   // destructors.
8660   for (auto &Check : Overriding)
8661     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8662 
8663   // Perform any deferred checking of exception specifications for befriended
8664   // special members.
8665   for (auto &Check : Equivalent)
8666     CheckEquivalentExceptionSpec(Check.second, Check.first);
8667 }
8668 
8669 namespace {
8670 /// CRTP base class for visiting operations performed by a special member
8671 /// function (or inherited constructor).
8672 template<typename Derived>
8673 struct SpecialMemberVisitor {
8674   Sema &S;
8675   CXXMethodDecl *MD;
8676   Sema::CXXSpecialMember CSM;
8677   Sema::InheritedConstructorInfo *ICI;
8678 
8679   // Properties of the special member, computed for convenience.
8680   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8681 
8682   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8683                        Sema::InheritedConstructorInfo *ICI)
8684       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8685     switch (CSM) {
8686     case Sema::CXXDefaultConstructor:
8687     case Sema::CXXCopyConstructor:
8688     case Sema::CXXMoveConstructor:
8689       IsConstructor = true;
8690       break;
8691     case Sema::CXXCopyAssignment:
8692     case Sema::CXXMoveAssignment:
8693       IsAssignment = true;
8694       break;
8695     case Sema::CXXDestructor:
8696       break;
8697     case Sema::CXXInvalid:
8698       llvm_unreachable("invalid special member kind");
8699     }
8700 
8701     if (MD->getNumParams()) {
8702       if (const ReferenceType *RT =
8703               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8704         ConstArg = RT->getPointeeType().isConstQualified();
8705     }
8706   }
8707 
8708   Derived &getDerived() { return static_cast<Derived&>(*this); }
8709 
8710   /// Is this a "move" special member?
8711   bool isMove() const {
8712     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8713   }
8714 
8715   /// Look up the corresponding special member in the given class.
8716   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8717                                              unsigned Quals, bool IsMutable) {
8718     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8719                                        ConstArg && !IsMutable);
8720   }
8721 
8722   /// Look up the constructor for the specified base class to see if it's
8723   /// overridden due to this being an inherited constructor.
8724   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8725     if (!ICI)
8726       return {};
8727     assert(CSM == Sema::CXXDefaultConstructor);
8728     auto *BaseCtor =
8729       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8730     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8731       return MD;
8732     return {};
8733   }
8734 
8735   /// A base or member subobject.
8736   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8737 
8738   /// Get the location to use for a subobject in diagnostics.
8739   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8740     // FIXME: For an indirect virtual base, the direct base leading to
8741     // the indirect virtual base would be a more useful choice.
8742     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8743       return B->getBaseTypeLoc();
8744     else
8745       return Subobj.get<FieldDecl*>()->getLocation();
8746   }
8747 
8748   enum BasesToVisit {
8749     /// Visit all non-virtual (direct) bases.
8750     VisitNonVirtualBases,
8751     /// Visit all direct bases, virtual or not.
8752     VisitDirectBases,
8753     /// Visit all non-virtual bases, and all virtual bases if the class
8754     /// is not abstract.
8755     VisitPotentiallyConstructedBases,
8756     /// Visit all direct or virtual bases.
8757     VisitAllBases
8758   };
8759 
8760   // Visit the bases and members of the class.
8761   bool visit(BasesToVisit Bases) {
8762     CXXRecordDecl *RD = MD->getParent();
8763 
8764     if (Bases == VisitPotentiallyConstructedBases)
8765       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8766 
8767     for (auto &B : RD->bases())
8768       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8769           getDerived().visitBase(&B))
8770         return true;
8771 
8772     if (Bases == VisitAllBases)
8773       for (auto &B : RD->vbases())
8774         if (getDerived().visitBase(&B))
8775           return true;
8776 
8777     for (auto *F : RD->fields())
8778       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8779           getDerived().visitField(F))
8780         return true;
8781 
8782     return false;
8783   }
8784 };
8785 }
8786 
8787 namespace {
8788 struct SpecialMemberDeletionInfo
8789     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8790   bool Diagnose;
8791 
8792   SourceLocation Loc;
8793 
8794   bool AllFieldsAreConst;
8795 
8796   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8797                             Sema::CXXSpecialMember CSM,
8798                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8799       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8800         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8801 
8802   bool inUnion() const { return MD->getParent()->isUnion(); }
8803 
8804   Sema::CXXSpecialMember getEffectiveCSM() {
8805     return ICI ? Sema::CXXInvalid : CSM;
8806   }
8807 
8808   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8809 
8810   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8811   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8812 
8813   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8814   bool shouldDeleteForField(FieldDecl *FD);
8815   bool shouldDeleteForAllConstMembers();
8816 
8817   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8818                                      unsigned Quals);
8819   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8820                                     Sema::SpecialMemberOverloadResult SMOR,
8821                                     bool IsDtorCallInCtor);
8822 
8823   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8824 };
8825 }
8826 
8827 /// Is the given special member inaccessible when used on the given
8828 /// sub-object.
8829 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8830                                              CXXMethodDecl *target) {
8831   /// If we're operating on a base class, the object type is the
8832   /// type of this special member.
8833   QualType objectTy;
8834   AccessSpecifier access = target->getAccess();
8835   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8836     objectTy = S.Context.getTypeDeclType(MD->getParent());
8837     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8838 
8839   // If we're operating on a field, the object type is the type of the field.
8840   } else {
8841     objectTy = S.Context.getTypeDeclType(target->getParent());
8842   }
8843 
8844   return S.isMemberAccessibleForDeletion(
8845       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8846 }
8847 
8848 /// Check whether we should delete a special member due to the implicit
8849 /// definition containing a call to a special member of a subobject.
8850 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8851     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8852     bool IsDtorCallInCtor) {
8853   CXXMethodDecl *Decl = SMOR.getMethod();
8854   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8855 
8856   int DiagKind = -1;
8857 
8858   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8859     DiagKind = !Decl ? 0 : 1;
8860   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8861     DiagKind = 2;
8862   else if (!isAccessible(Subobj, Decl))
8863     DiagKind = 3;
8864   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8865            !Decl->isTrivial()) {
8866     // A member of a union must have a trivial corresponding special member.
8867     // As a weird special case, a destructor call from a union's constructor
8868     // must be accessible and non-deleted, but need not be trivial. Such a
8869     // destructor is never actually called, but is semantically checked as
8870     // if it were.
8871     DiagKind = 4;
8872   }
8873 
8874   if (DiagKind == -1)
8875     return false;
8876 
8877   if (Diagnose) {
8878     if (Field) {
8879       S.Diag(Field->getLocation(),
8880              diag::note_deleted_special_member_class_subobject)
8881         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8882         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8883     } else {
8884       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8885       S.Diag(Base->getBeginLoc(),
8886              diag::note_deleted_special_member_class_subobject)
8887           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8888           << Base->getType() << DiagKind << IsDtorCallInCtor
8889           << /*IsObjCPtr*/false;
8890     }
8891 
8892     if (DiagKind == 1)
8893       S.NoteDeletedFunction(Decl);
8894     // FIXME: Explain inaccessibility if DiagKind == 3.
8895   }
8896 
8897   return true;
8898 }
8899 
8900 /// Check whether we should delete a special member function due to having a
8901 /// direct or virtual base class or non-static data member of class type M.
8902 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8903     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8904   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8905   bool IsMutable = Field && Field->isMutable();
8906 
8907   // C++11 [class.ctor]p5:
8908   // -- any direct or virtual base class, or non-static data member with no
8909   //    brace-or-equal-initializer, has class type M (or array thereof) and
8910   //    either M has no default constructor or overload resolution as applied
8911   //    to M's default constructor results in an ambiguity or in a function
8912   //    that is deleted or inaccessible
8913   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8914   // -- a direct or virtual base class B that cannot be copied/moved because
8915   //    overload resolution, as applied to B's corresponding special member,
8916   //    results in an ambiguity or a function that is deleted or inaccessible
8917   //    from the defaulted special member
8918   // C++11 [class.dtor]p5:
8919   // -- any direct or virtual base class [...] has a type with a destructor
8920   //    that is deleted or inaccessible
8921   if (!(CSM == Sema::CXXDefaultConstructor &&
8922         Field && Field->hasInClassInitializer()) &&
8923       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8924                                    false))
8925     return true;
8926 
8927   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8928   // -- any direct or virtual base class or non-static data member has a
8929   //    type with a destructor that is deleted or inaccessible
8930   if (IsConstructor) {
8931     Sema::SpecialMemberOverloadResult SMOR =
8932         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8933                               false, false, false, false, false);
8934     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8935       return true;
8936   }
8937 
8938   return false;
8939 }
8940 
8941 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8942     FieldDecl *FD, QualType FieldType) {
8943   // The defaulted special functions are defined as deleted if this is a variant
8944   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8945   // type under ARC.
8946   if (!FieldType.hasNonTrivialObjCLifetime())
8947     return false;
8948 
8949   // Don't make the defaulted default constructor defined as deleted if the
8950   // member has an in-class initializer.
8951   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8952     return false;
8953 
8954   if (Diagnose) {
8955     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8956     S.Diag(FD->getLocation(),
8957            diag::note_deleted_special_member_class_subobject)
8958         << getEffectiveCSM() << ParentClass << /*IsField*/true
8959         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8960   }
8961 
8962   return true;
8963 }
8964 
8965 /// Check whether we should delete a special member function due to the class
8966 /// having a particular direct or virtual base class.
8967 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8968   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8969   // If program is correct, BaseClass cannot be null, but if it is, the error
8970   // must be reported elsewhere.
8971   if (!BaseClass)
8972     return false;
8973   // If we have an inheriting constructor, check whether we're calling an
8974   // inherited constructor instead of a default constructor.
8975   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8976   if (auto *BaseCtor = SMOR.getMethod()) {
8977     // Note that we do not check access along this path; other than that,
8978     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8979     // FIXME: Check that the base has a usable destructor! Sink this into
8980     // shouldDeleteForClassSubobject.
8981     if (BaseCtor->isDeleted() && Diagnose) {
8982       S.Diag(Base->getBeginLoc(),
8983              diag::note_deleted_special_member_class_subobject)
8984           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8985           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8986           << /*IsObjCPtr*/false;
8987       S.NoteDeletedFunction(BaseCtor);
8988     }
8989     return BaseCtor->isDeleted();
8990   }
8991   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8992 }
8993 
8994 /// Check whether we should delete a special member function due to the class
8995 /// having a particular non-static data member.
8996 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8997   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8998   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8999 
9000   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9001     return true;
9002 
9003   if (CSM == Sema::CXXDefaultConstructor) {
9004     // For a default constructor, all references must be initialized in-class
9005     // and, if a union, it must have a non-const member.
9006     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9007       if (Diagnose)
9008         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9009           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9010       return true;
9011     }
9012     // C++11 [class.ctor]p5: any non-variant non-static data member of
9013     // const-qualified type (or array thereof) with no
9014     // brace-or-equal-initializer does not have a user-provided default
9015     // constructor.
9016     if (!inUnion() && FieldType.isConstQualified() &&
9017         !FD->hasInClassInitializer() &&
9018         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9019       if (Diagnose)
9020         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9021           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9022       return true;
9023     }
9024 
9025     if (inUnion() && !FieldType.isConstQualified())
9026       AllFieldsAreConst = false;
9027   } else if (CSM == Sema::CXXCopyConstructor) {
9028     // For a copy constructor, data members must not be of rvalue reference
9029     // type.
9030     if (FieldType->isRValueReferenceType()) {
9031       if (Diagnose)
9032         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9033           << MD->getParent() << FD << FieldType;
9034       return true;
9035     }
9036   } else if (IsAssignment) {
9037     // For an assignment operator, data members must not be of reference type.
9038     if (FieldType->isReferenceType()) {
9039       if (Diagnose)
9040         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9041           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9042       return true;
9043     }
9044     if (!FieldRecord && FieldType.isConstQualified()) {
9045       // C++11 [class.copy]p23:
9046       // -- a non-static data member of const non-class type (or array thereof)
9047       if (Diagnose)
9048         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9049           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9050       return true;
9051     }
9052   }
9053 
9054   if (FieldRecord) {
9055     // Some additional restrictions exist on the variant members.
9056     if (!inUnion() && FieldRecord->isUnion() &&
9057         FieldRecord->isAnonymousStructOrUnion()) {
9058       bool AllVariantFieldsAreConst = true;
9059 
9060       // FIXME: Handle anonymous unions declared within anonymous unions.
9061       for (auto *UI : FieldRecord->fields()) {
9062         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9063 
9064         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9065           return true;
9066 
9067         if (!UnionFieldType.isConstQualified())
9068           AllVariantFieldsAreConst = false;
9069 
9070         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9071         if (UnionFieldRecord &&
9072             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9073                                           UnionFieldType.getCVRQualifiers()))
9074           return true;
9075       }
9076 
9077       // At least one member in each anonymous union must be non-const
9078       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9079           !FieldRecord->field_empty()) {
9080         if (Diagnose)
9081           S.Diag(FieldRecord->getLocation(),
9082                  diag::note_deleted_default_ctor_all_const)
9083             << !!ICI << MD->getParent() << /*anonymous union*/1;
9084         return true;
9085       }
9086 
9087       // Don't check the implicit member of the anonymous union type.
9088       // This is technically non-conformant, but sanity demands it.
9089       return false;
9090     }
9091 
9092     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9093                                       FieldType.getCVRQualifiers()))
9094       return true;
9095   }
9096 
9097   return false;
9098 }
9099 
9100 /// C++11 [class.ctor] p5:
9101 ///   A defaulted default constructor for a class X is defined as deleted if
9102 /// X is a union and all of its variant members are of const-qualified type.
9103 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9104   // This is a silly definition, because it gives an empty union a deleted
9105   // default constructor. Don't do that.
9106   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9107     bool AnyFields = false;
9108     for (auto *F : MD->getParent()->fields())
9109       if ((AnyFields = !F->isUnnamedBitfield()))
9110         break;
9111     if (!AnyFields)
9112       return false;
9113     if (Diagnose)
9114       S.Diag(MD->getParent()->getLocation(),
9115              diag::note_deleted_default_ctor_all_const)
9116         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9117     return true;
9118   }
9119   return false;
9120 }
9121 
9122 /// Determine whether a defaulted special member function should be defined as
9123 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9124 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9125 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9126                                      InheritedConstructorInfo *ICI,
9127                                      bool Diagnose) {
9128   if (MD->isInvalidDecl())
9129     return false;
9130   CXXRecordDecl *RD = MD->getParent();
9131   assert(!RD->isDependentType() && "do deletion after instantiation");
9132   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9133     return false;
9134 
9135   // C++11 [expr.lambda.prim]p19:
9136   //   The closure type associated with a lambda-expression has a
9137   //   deleted (8.4.3) default constructor and a deleted copy
9138   //   assignment operator.
9139   // C++2a adds back these operators if the lambda has no lambda-capture.
9140   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9141       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9142     if (Diagnose)
9143       Diag(RD->getLocation(), diag::note_lambda_decl);
9144     return true;
9145   }
9146 
9147   // For an anonymous struct or union, the copy and assignment special members
9148   // will never be used, so skip the check. For an anonymous union declared at
9149   // namespace scope, the constructor and destructor are used.
9150   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9151       RD->isAnonymousStructOrUnion())
9152     return false;
9153 
9154   // C++11 [class.copy]p7, p18:
9155   //   If the class definition declares a move constructor or move assignment
9156   //   operator, an implicitly declared copy constructor or copy assignment
9157   //   operator is defined as deleted.
9158   if (MD->isImplicit() &&
9159       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9160     CXXMethodDecl *UserDeclaredMove = nullptr;
9161 
9162     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9163     // deletion of the corresponding copy operation, not both copy operations.
9164     // MSVC 2015 has adopted the standards conforming behavior.
9165     bool DeletesOnlyMatchingCopy =
9166         getLangOpts().MSVCCompat &&
9167         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9168 
9169     if (RD->hasUserDeclaredMoveConstructor() &&
9170         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9171       if (!Diagnose) return true;
9172 
9173       // Find any user-declared move constructor.
9174       for (auto *I : RD->ctors()) {
9175         if (I->isMoveConstructor()) {
9176           UserDeclaredMove = I;
9177           break;
9178         }
9179       }
9180       assert(UserDeclaredMove);
9181     } else if (RD->hasUserDeclaredMoveAssignment() &&
9182                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9183       if (!Diagnose) return true;
9184 
9185       // Find any user-declared move assignment operator.
9186       for (auto *I : RD->methods()) {
9187         if (I->isMoveAssignmentOperator()) {
9188           UserDeclaredMove = I;
9189           break;
9190         }
9191       }
9192       assert(UserDeclaredMove);
9193     }
9194 
9195     if (UserDeclaredMove) {
9196       Diag(UserDeclaredMove->getLocation(),
9197            diag::note_deleted_copy_user_declared_move)
9198         << (CSM == CXXCopyAssignment) << RD
9199         << UserDeclaredMove->isMoveAssignmentOperator();
9200       return true;
9201     }
9202   }
9203 
9204   // Do access control from the special member function
9205   ContextRAII MethodContext(*this, MD);
9206 
9207   // C++11 [class.dtor]p5:
9208   // -- for a virtual destructor, lookup of the non-array deallocation function
9209   //    results in an ambiguity or in a function that is deleted or inaccessible
9210   if (CSM == CXXDestructor && MD->isVirtual()) {
9211     FunctionDecl *OperatorDelete = nullptr;
9212     DeclarationName Name =
9213       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9214     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9215                                  OperatorDelete, /*Diagnose*/false)) {
9216       if (Diagnose)
9217         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9218       return true;
9219     }
9220   }
9221 
9222   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9223 
9224   // Per DR1611, do not consider virtual bases of constructors of abstract
9225   // classes, since we are not going to construct them.
9226   // Per DR1658, do not consider virtual bases of destructors of abstract
9227   // classes either.
9228   // Per DR2180, for assignment operators we only assign (and thus only
9229   // consider) direct bases.
9230   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9231                                  : SMI.VisitPotentiallyConstructedBases))
9232     return true;
9233 
9234   if (SMI.shouldDeleteForAllConstMembers())
9235     return true;
9236 
9237   if (getLangOpts().CUDA) {
9238     // We should delete the special member in CUDA mode if target inference
9239     // failed.
9240     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9241     // is treated as certain special member, which may not reflect what special
9242     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9243     // expects CSM to match MD, therefore recalculate CSM.
9244     assert(ICI || CSM == getSpecialMember(MD));
9245     auto RealCSM = CSM;
9246     if (ICI)
9247       RealCSM = getSpecialMember(MD);
9248 
9249     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9250                                                    SMI.ConstArg, Diagnose);
9251   }
9252 
9253   return false;
9254 }
9255 
9256 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9257   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9258   assert(DFK && "not a defaultable function");
9259   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9260 
9261   if (DFK.isSpecialMember()) {
9262     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9263                               nullptr, /*Diagnose=*/true);
9264   } else {
9265     DefaultedComparisonAnalyzer(
9266         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9267         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9268         .visit();
9269   }
9270 }
9271 
9272 /// Perform lookup for a special member of the specified kind, and determine
9273 /// whether it is trivial. If the triviality can be determined without the
9274 /// lookup, skip it. This is intended for use when determining whether a
9275 /// special member of a containing object is trivial, and thus does not ever
9276 /// perform overload resolution for default constructors.
9277 ///
9278 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9279 /// member that was most likely to be intended to be trivial, if any.
9280 ///
9281 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9282 /// determine whether the special member is trivial.
9283 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9284                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9285                                      bool ConstRHS,
9286                                      Sema::TrivialABIHandling TAH,
9287                                      CXXMethodDecl **Selected) {
9288   if (Selected)
9289     *Selected = nullptr;
9290 
9291   switch (CSM) {
9292   case Sema::CXXInvalid:
9293     llvm_unreachable("not a special member");
9294 
9295   case Sema::CXXDefaultConstructor:
9296     // C++11 [class.ctor]p5:
9297     //   A default constructor is trivial if:
9298     //    - all the [direct subobjects] have trivial default constructors
9299     //
9300     // Note, no overload resolution is performed in this case.
9301     if (RD->hasTrivialDefaultConstructor())
9302       return true;
9303 
9304     if (Selected) {
9305       // If there's a default constructor which could have been trivial, dig it
9306       // out. Otherwise, if there's any user-provided default constructor, point
9307       // to that as an example of why there's not a trivial one.
9308       CXXConstructorDecl *DefCtor = nullptr;
9309       if (RD->needsImplicitDefaultConstructor())
9310         S.DeclareImplicitDefaultConstructor(RD);
9311       for (auto *CI : RD->ctors()) {
9312         if (!CI->isDefaultConstructor())
9313           continue;
9314         DefCtor = CI;
9315         if (!DefCtor->isUserProvided())
9316           break;
9317       }
9318 
9319       *Selected = DefCtor;
9320     }
9321 
9322     return false;
9323 
9324   case Sema::CXXDestructor:
9325     // C++11 [class.dtor]p5:
9326     //   A destructor is trivial if:
9327     //    - all the direct [subobjects] have trivial destructors
9328     if (RD->hasTrivialDestructor() ||
9329         (TAH == Sema::TAH_ConsiderTrivialABI &&
9330          RD->hasTrivialDestructorForCall()))
9331       return true;
9332 
9333     if (Selected) {
9334       if (RD->needsImplicitDestructor())
9335         S.DeclareImplicitDestructor(RD);
9336       *Selected = RD->getDestructor();
9337     }
9338 
9339     return false;
9340 
9341   case Sema::CXXCopyConstructor:
9342     // C++11 [class.copy]p12:
9343     //   A copy constructor is trivial if:
9344     //    - the constructor selected to copy each direct [subobject] is trivial
9345     if (RD->hasTrivialCopyConstructor() ||
9346         (TAH == Sema::TAH_ConsiderTrivialABI &&
9347          RD->hasTrivialCopyConstructorForCall())) {
9348       if (Quals == Qualifiers::Const)
9349         // We must either select the trivial copy constructor or reach an
9350         // ambiguity; no need to actually perform overload resolution.
9351         return true;
9352     } else if (!Selected) {
9353       return false;
9354     }
9355     // In C++98, we are not supposed to perform overload resolution here, but we
9356     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9357     // cases like B as having a non-trivial copy constructor:
9358     //   struct A { template<typename T> A(T&); };
9359     //   struct B { mutable A a; };
9360     goto NeedOverloadResolution;
9361 
9362   case Sema::CXXCopyAssignment:
9363     // C++11 [class.copy]p25:
9364     //   A copy assignment operator is trivial if:
9365     //    - the assignment operator selected to copy each direct [subobject] is
9366     //      trivial
9367     if (RD->hasTrivialCopyAssignment()) {
9368       if (Quals == Qualifiers::Const)
9369         return true;
9370     } else if (!Selected) {
9371       return false;
9372     }
9373     // In C++98, we are not supposed to perform overload resolution here, but we
9374     // treat that as a language defect.
9375     goto NeedOverloadResolution;
9376 
9377   case Sema::CXXMoveConstructor:
9378   case Sema::CXXMoveAssignment:
9379   NeedOverloadResolution:
9380     Sema::SpecialMemberOverloadResult SMOR =
9381         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9382 
9383     // The standard doesn't describe how to behave if the lookup is ambiguous.
9384     // We treat it as not making the member non-trivial, just like the standard
9385     // mandates for the default constructor. This should rarely matter, because
9386     // the member will also be deleted.
9387     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9388       return true;
9389 
9390     if (!SMOR.getMethod()) {
9391       assert(SMOR.getKind() ==
9392              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9393       return false;
9394     }
9395 
9396     // We deliberately don't check if we found a deleted special member. We're
9397     // not supposed to!
9398     if (Selected)
9399       *Selected = SMOR.getMethod();
9400 
9401     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9402         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9403       return SMOR.getMethod()->isTrivialForCall();
9404     return SMOR.getMethod()->isTrivial();
9405   }
9406 
9407   llvm_unreachable("unknown special method kind");
9408 }
9409 
9410 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9411   for (auto *CI : RD->ctors())
9412     if (!CI->isImplicit())
9413       return CI;
9414 
9415   // Look for constructor templates.
9416   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9417   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9418     if (CXXConstructorDecl *CD =
9419           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9420       return CD;
9421   }
9422 
9423   return nullptr;
9424 }
9425 
9426 /// The kind of subobject we are checking for triviality. The values of this
9427 /// enumeration are used in diagnostics.
9428 enum TrivialSubobjectKind {
9429   /// The subobject is a base class.
9430   TSK_BaseClass,
9431   /// The subobject is a non-static data member.
9432   TSK_Field,
9433   /// The object is actually the complete object.
9434   TSK_CompleteObject
9435 };
9436 
9437 /// Check whether the special member selected for a given type would be trivial.
9438 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9439                                       QualType SubType, bool ConstRHS,
9440                                       Sema::CXXSpecialMember CSM,
9441                                       TrivialSubobjectKind Kind,
9442                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9443   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9444   if (!SubRD)
9445     return true;
9446 
9447   CXXMethodDecl *Selected;
9448   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9449                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9450     return true;
9451 
9452   if (Diagnose) {
9453     if (ConstRHS)
9454       SubType.addConst();
9455 
9456     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9457       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9458         << Kind << SubType.getUnqualifiedType();
9459       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9460         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9461     } else if (!Selected)
9462       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9463         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9464     else if (Selected->isUserProvided()) {
9465       if (Kind == TSK_CompleteObject)
9466         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9467           << Kind << SubType.getUnqualifiedType() << CSM;
9468       else {
9469         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9470           << Kind << SubType.getUnqualifiedType() << CSM;
9471         S.Diag(Selected->getLocation(), diag::note_declared_at);
9472       }
9473     } else {
9474       if (Kind != TSK_CompleteObject)
9475         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9476           << Kind << SubType.getUnqualifiedType() << CSM;
9477 
9478       // Explain why the defaulted or deleted special member isn't trivial.
9479       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9480                                Diagnose);
9481     }
9482   }
9483 
9484   return false;
9485 }
9486 
9487 /// Check whether the members of a class type allow a special member to be
9488 /// trivial.
9489 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9490                                      Sema::CXXSpecialMember CSM,
9491                                      bool ConstArg,
9492                                      Sema::TrivialABIHandling TAH,
9493                                      bool Diagnose) {
9494   for (const auto *FI : RD->fields()) {
9495     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9496       continue;
9497 
9498     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9499 
9500     // Pretend anonymous struct or union members are members of this class.
9501     if (FI->isAnonymousStructOrUnion()) {
9502       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9503                                     CSM, ConstArg, TAH, Diagnose))
9504         return false;
9505       continue;
9506     }
9507 
9508     // C++11 [class.ctor]p5:
9509     //   A default constructor is trivial if [...]
9510     //    -- no non-static data member of its class has a
9511     //       brace-or-equal-initializer
9512     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9513       if (Diagnose)
9514         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9515             << FI;
9516       return false;
9517     }
9518 
9519     // Objective C ARC 4.3.5:
9520     //   [...] nontrivally ownership-qualified types are [...] not trivially
9521     //   default constructible, copy constructible, move constructible, copy
9522     //   assignable, move assignable, or destructible [...]
9523     if (FieldType.hasNonTrivialObjCLifetime()) {
9524       if (Diagnose)
9525         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9526           << RD << FieldType.getObjCLifetime();
9527       return false;
9528     }
9529 
9530     bool ConstRHS = ConstArg && !FI->isMutable();
9531     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9532                                    CSM, TSK_Field, TAH, Diagnose))
9533       return false;
9534   }
9535 
9536   return true;
9537 }
9538 
9539 /// Diagnose why the specified class does not have a trivial special member of
9540 /// the given kind.
9541 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9542   QualType Ty = Context.getRecordType(RD);
9543 
9544   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9545   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9546                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9547                             /*Diagnose*/true);
9548 }
9549 
9550 /// Determine whether a defaulted or deleted special member function is trivial,
9551 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9552 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9553 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9554                                   TrivialABIHandling TAH, bool Diagnose) {
9555   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9556 
9557   CXXRecordDecl *RD = MD->getParent();
9558 
9559   bool ConstArg = false;
9560 
9561   // C++11 [class.copy]p12, p25: [DR1593]
9562   //   A [special member] is trivial if [...] its parameter-type-list is
9563   //   equivalent to the parameter-type-list of an implicit declaration [...]
9564   switch (CSM) {
9565   case CXXDefaultConstructor:
9566   case CXXDestructor:
9567     // Trivial default constructors and destructors cannot have parameters.
9568     break;
9569 
9570   case CXXCopyConstructor:
9571   case CXXCopyAssignment: {
9572     // Trivial copy operations always have const, non-volatile parameter types.
9573     ConstArg = true;
9574     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9575     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9576     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9577       if (Diagnose)
9578         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9579           << Param0->getSourceRange() << Param0->getType()
9580           << Context.getLValueReferenceType(
9581                Context.getRecordType(RD).withConst());
9582       return false;
9583     }
9584     break;
9585   }
9586 
9587   case CXXMoveConstructor:
9588   case CXXMoveAssignment: {
9589     // Trivial move operations always have non-cv-qualified parameters.
9590     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9591     const RValueReferenceType *RT =
9592       Param0->getType()->getAs<RValueReferenceType>();
9593     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9594       if (Diagnose)
9595         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9596           << Param0->getSourceRange() << Param0->getType()
9597           << Context.getRValueReferenceType(Context.getRecordType(RD));
9598       return false;
9599     }
9600     break;
9601   }
9602 
9603   case CXXInvalid:
9604     llvm_unreachable("not a special member");
9605   }
9606 
9607   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9608     if (Diagnose)
9609       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9610            diag::note_nontrivial_default_arg)
9611         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9612     return false;
9613   }
9614   if (MD->isVariadic()) {
9615     if (Diagnose)
9616       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9617     return false;
9618   }
9619 
9620   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9621   //   A copy/move [constructor or assignment operator] is trivial if
9622   //    -- the [member] selected to copy/move each direct base class subobject
9623   //       is trivial
9624   //
9625   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9626   //   A [default constructor or destructor] is trivial if
9627   //    -- all the direct base classes have trivial [default constructors or
9628   //       destructors]
9629   for (const auto &BI : RD->bases())
9630     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9631                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9632       return false;
9633 
9634   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9635   //   A copy/move [constructor or assignment operator] for a class X is
9636   //   trivial if
9637   //    -- for each non-static data member of X that is of class type (or array
9638   //       thereof), the constructor selected to copy/move that member is
9639   //       trivial
9640   //
9641   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9642   //   A [default constructor or destructor] is trivial if
9643   //    -- for all of the non-static data members of its class that are of class
9644   //       type (or array thereof), each such class has a trivial [default
9645   //       constructor or destructor]
9646   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9647     return false;
9648 
9649   // C++11 [class.dtor]p5:
9650   //   A destructor is trivial if [...]
9651   //    -- the destructor is not virtual
9652   if (CSM == CXXDestructor && MD->isVirtual()) {
9653     if (Diagnose)
9654       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9655     return false;
9656   }
9657 
9658   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9659   //   A [special member] for class X is trivial if [...]
9660   //    -- class X has no virtual functions and no virtual base classes
9661   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9662     if (!Diagnose)
9663       return false;
9664 
9665     if (RD->getNumVBases()) {
9666       // Check for virtual bases. We already know that the corresponding
9667       // member in all bases is trivial, so vbases must all be direct.
9668       CXXBaseSpecifier &BS = *RD->vbases_begin();
9669       assert(BS.isVirtual());
9670       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9671       return false;
9672     }
9673 
9674     // Must have a virtual method.
9675     for (const auto *MI : RD->methods()) {
9676       if (MI->isVirtual()) {
9677         SourceLocation MLoc = MI->getBeginLoc();
9678         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9679         return false;
9680       }
9681     }
9682 
9683     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9684   }
9685 
9686   // Looks like it's trivial!
9687   return true;
9688 }
9689 
9690 namespace {
9691 struct FindHiddenVirtualMethod {
9692   Sema *S;
9693   CXXMethodDecl *Method;
9694   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9695   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9696 
9697 private:
9698   /// Check whether any most overridden method from MD in Methods
9699   static bool CheckMostOverridenMethods(
9700       const CXXMethodDecl *MD,
9701       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9702     if (MD->size_overridden_methods() == 0)
9703       return Methods.count(MD->getCanonicalDecl());
9704     for (const CXXMethodDecl *O : MD->overridden_methods())
9705       if (CheckMostOverridenMethods(O, Methods))
9706         return true;
9707     return false;
9708   }
9709 
9710 public:
9711   /// Member lookup function that determines whether a given C++
9712   /// method overloads virtual methods in a base class without overriding any,
9713   /// to be used with CXXRecordDecl::lookupInBases().
9714   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9715     RecordDecl *BaseRecord =
9716         Specifier->getType()->castAs<RecordType>()->getDecl();
9717 
9718     DeclarationName Name = Method->getDeclName();
9719     assert(Name.getNameKind() == DeclarationName::Identifier);
9720 
9721     bool foundSameNameMethod = false;
9722     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9723     for (Path.Decls = BaseRecord->lookup(Name).begin();
9724          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9725       NamedDecl *D = *Path.Decls;
9726       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9727         MD = MD->getCanonicalDecl();
9728         foundSameNameMethod = true;
9729         // Interested only in hidden virtual methods.
9730         if (!MD->isVirtual())
9731           continue;
9732         // If the method we are checking overrides a method from its base
9733         // don't warn about the other overloaded methods. Clang deviates from
9734         // GCC by only diagnosing overloads of inherited virtual functions that
9735         // do not override any other virtual functions in the base. GCC's
9736         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9737         // function from a base class. These cases may be better served by a
9738         // warning (not specific to virtual functions) on call sites when the
9739         // call would select a different function from the base class, were it
9740         // visible.
9741         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9742         if (!S->IsOverload(Method, MD, false))
9743           return true;
9744         // Collect the overload only if its hidden.
9745         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9746           overloadedMethods.push_back(MD);
9747       }
9748     }
9749 
9750     if (foundSameNameMethod)
9751       OverloadedMethods.append(overloadedMethods.begin(),
9752                                overloadedMethods.end());
9753     return foundSameNameMethod;
9754   }
9755 };
9756 } // end anonymous namespace
9757 
9758 /// Add the most overriden methods from MD to Methods
9759 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9760                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9761   if (MD->size_overridden_methods() == 0)
9762     Methods.insert(MD->getCanonicalDecl());
9763   else
9764     for (const CXXMethodDecl *O : MD->overridden_methods())
9765       AddMostOverridenMethods(O, Methods);
9766 }
9767 
9768 /// Check if a method overloads virtual methods in a base class without
9769 /// overriding any.
9770 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9771                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9772   if (!MD->getDeclName().isIdentifier())
9773     return;
9774 
9775   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9776                      /*bool RecordPaths=*/false,
9777                      /*bool DetectVirtual=*/false);
9778   FindHiddenVirtualMethod FHVM;
9779   FHVM.Method = MD;
9780   FHVM.S = this;
9781 
9782   // Keep the base methods that were overridden or introduced in the subclass
9783   // by 'using' in a set. A base method not in this set is hidden.
9784   CXXRecordDecl *DC = MD->getParent();
9785   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9786   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9787     NamedDecl *ND = *I;
9788     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9789       ND = shad->getTargetDecl();
9790     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9791       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9792   }
9793 
9794   if (DC->lookupInBases(FHVM, Paths))
9795     OverloadedMethods = FHVM.OverloadedMethods;
9796 }
9797 
9798 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9799                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9800   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9801     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9802     PartialDiagnostic PD = PDiag(
9803          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9804     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9805     Diag(overloadedMD->getLocation(), PD);
9806   }
9807 }
9808 
9809 /// Diagnose methods which overload virtual methods in a base class
9810 /// without overriding any.
9811 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9812   if (MD->isInvalidDecl())
9813     return;
9814 
9815   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9816     return;
9817 
9818   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9819   FindHiddenVirtualMethods(MD, OverloadedMethods);
9820   if (!OverloadedMethods.empty()) {
9821     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9822       << MD << (OverloadedMethods.size() > 1);
9823 
9824     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9825   }
9826 }
9827 
9828 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9829   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9830     // No diagnostics if this is a template instantiation.
9831     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9832       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9833            diag::ext_cannot_use_trivial_abi) << &RD;
9834       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9835            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9836     }
9837     RD.dropAttr<TrivialABIAttr>();
9838   };
9839 
9840   // Ill-formed if the copy and move constructors are deleted.
9841   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9842     // If the type is dependent, then assume it might have
9843     // implicit copy or move ctor because we won't know yet at this point.
9844     if (RD.isDependentType())
9845       return true;
9846     if (RD.needsImplicitCopyConstructor() &&
9847         !RD.defaultedCopyConstructorIsDeleted())
9848       return true;
9849     if (RD.needsImplicitMoveConstructor() &&
9850         !RD.defaultedMoveConstructorIsDeleted())
9851       return true;
9852     for (const CXXConstructorDecl *CD : RD.ctors())
9853       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9854         return true;
9855     return false;
9856   };
9857 
9858   if (!HasNonDeletedCopyOrMoveConstructor()) {
9859     PrintDiagAndRemoveAttr(0);
9860     return;
9861   }
9862 
9863   // Ill-formed if the struct has virtual functions.
9864   if (RD.isPolymorphic()) {
9865     PrintDiagAndRemoveAttr(1);
9866     return;
9867   }
9868 
9869   for (const auto &B : RD.bases()) {
9870     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9871     // virtual base.
9872     if (!B.getType()->isDependentType() &&
9873         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9874       PrintDiagAndRemoveAttr(2);
9875       return;
9876     }
9877 
9878     if (B.isVirtual()) {
9879       PrintDiagAndRemoveAttr(3);
9880       return;
9881     }
9882   }
9883 
9884   for (const auto *FD : RD.fields()) {
9885     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9886     // non-trivial for the purpose of calls.
9887     QualType FT = FD->getType();
9888     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9889       PrintDiagAndRemoveAttr(4);
9890       return;
9891     }
9892 
9893     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9894       if (!RT->isDependentType() &&
9895           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9896         PrintDiagAndRemoveAttr(5);
9897         return;
9898       }
9899   }
9900 }
9901 
9902 void Sema::ActOnFinishCXXMemberSpecification(
9903     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9904     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9905   if (!TagDecl)
9906     return;
9907 
9908   AdjustDeclIfTemplate(TagDecl);
9909 
9910   for (const ParsedAttr &AL : AttrList) {
9911     if (AL.getKind() != ParsedAttr::AT_Visibility)
9912       continue;
9913     AL.setInvalid();
9914     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9915   }
9916 
9917   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9918               // strict aliasing violation!
9919               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9920               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9921 
9922   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9923 }
9924 
9925 /// Find the equality comparison functions that should be implicitly declared
9926 /// in a given class definition, per C++2a [class.compare.default]p3.
9927 static void findImplicitlyDeclaredEqualityComparisons(
9928     ASTContext &Ctx, CXXRecordDecl *RD,
9929     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9930   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9931   if (!RD->lookup(EqEq).empty())
9932     // Member operator== explicitly declared: no implicit operator==s.
9933     return;
9934 
9935   // Traverse friends looking for an '==' or a '<=>'.
9936   for (FriendDecl *Friend : RD->friends()) {
9937     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9938     if (!FD) continue;
9939 
9940     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9941       // Friend operator== explicitly declared: no implicit operator==s.
9942       Spaceships.clear();
9943       return;
9944     }
9945 
9946     if (FD->getOverloadedOperator() == OO_Spaceship &&
9947         FD->isExplicitlyDefaulted())
9948       Spaceships.push_back(FD);
9949   }
9950 
9951   // Look for members named 'operator<=>'.
9952   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9953   for (NamedDecl *ND : RD->lookup(Cmp)) {
9954     // Note that we could find a non-function here (either a function template
9955     // or a using-declaration). Neither case results in an implicit
9956     // 'operator=='.
9957     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9958       if (FD->isExplicitlyDefaulted())
9959         Spaceships.push_back(FD);
9960   }
9961 }
9962 
9963 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9964 /// special functions, such as the default constructor, copy
9965 /// constructor, or destructor, to the given C++ class (C++
9966 /// [special]p1).  This routine can only be executed just before the
9967 /// definition of the class is complete.
9968 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9969   // Don't add implicit special members to templated classes.
9970   // FIXME: This means unqualified lookups for 'operator=' within a class
9971   // template don't work properly.
9972   if (!ClassDecl->isDependentType()) {
9973     if (ClassDecl->needsImplicitDefaultConstructor()) {
9974       ++getASTContext().NumImplicitDefaultConstructors;
9975 
9976       if (ClassDecl->hasInheritedConstructor())
9977         DeclareImplicitDefaultConstructor(ClassDecl);
9978     }
9979 
9980     if (ClassDecl->needsImplicitCopyConstructor()) {
9981       ++getASTContext().NumImplicitCopyConstructors;
9982 
9983       // If the properties or semantics of the copy constructor couldn't be
9984       // determined while the class was being declared, force a declaration
9985       // of it now.
9986       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9987           ClassDecl->hasInheritedConstructor())
9988         DeclareImplicitCopyConstructor(ClassDecl);
9989       // For the MS ABI we need to know whether the copy ctor is deleted. A
9990       // prerequisite for deleting the implicit copy ctor is that the class has
9991       // a move ctor or move assignment that is either user-declared or whose
9992       // semantics are inherited from a subobject. FIXME: We should provide a
9993       // more direct way for CodeGen to ask whether the constructor was deleted.
9994       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9995                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9996                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9997                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9998                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9999         DeclareImplicitCopyConstructor(ClassDecl);
10000     }
10001 
10002     if (getLangOpts().CPlusPlus11 &&
10003         ClassDecl->needsImplicitMoveConstructor()) {
10004       ++getASTContext().NumImplicitMoveConstructors;
10005 
10006       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10007           ClassDecl->hasInheritedConstructor())
10008         DeclareImplicitMoveConstructor(ClassDecl);
10009     }
10010 
10011     if (ClassDecl->needsImplicitCopyAssignment()) {
10012       ++getASTContext().NumImplicitCopyAssignmentOperators;
10013 
10014       // If we have a dynamic class, then the copy assignment operator may be
10015       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10016       // it shows up in the right place in the vtable and that we diagnose
10017       // problems with the implicit exception specification.
10018       if (ClassDecl->isDynamicClass() ||
10019           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10020           ClassDecl->hasInheritedAssignment())
10021         DeclareImplicitCopyAssignment(ClassDecl);
10022     }
10023 
10024     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10025       ++getASTContext().NumImplicitMoveAssignmentOperators;
10026 
10027       // Likewise for the move assignment operator.
10028       if (ClassDecl->isDynamicClass() ||
10029           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10030           ClassDecl->hasInheritedAssignment())
10031         DeclareImplicitMoveAssignment(ClassDecl);
10032     }
10033 
10034     if (ClassDecl->needsImplicitDestructor()) {
10035       ++getASTContext().NumImplicitDestructors;
10036 
10037       // If we have a dynamic class, then the destructor may be virtual, so we
10038       // have to declare the destructor immediately. This ensures that, e.g., it
10039       // shows up in the right place in the vtable and that we diagnose problems
10040       // with the implicit exception specification.
10041       if (ClassDecl->isDynamicClass() ||
10042           ClassDecl->needsOverloadResolutionForDestructor())
10043         DeclareImplicitDestructor(ClassDecl);
10044     }
10045   }
10046 
10047   // C++2a [class.compare.default]p3:
10048   //   If the member-specification does not explicitly declare any member or
10049   //   friend named operator==, an == operator function is declared implicitly
10050   //   for each defaulted three-way comparison operator function defined in
10051   //   the member-specification
10052   // FIXME: Consider doing this lazily.
10053   // We do this during the initial parse for a class template, not during
10054   // instantiation, so that we can handle unqualified lookups for 'operator=='
10055   // when parsing the template.
10056   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10057     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10058     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10059                                               DefaultedSpaceships);
10060     for (auto *FD : DefaultedSpaceships)
10061       DeclareImplicitEqualityComparison(ClassDecl, FD);
10062   }
10063 }
10064 
10065 unsigned
10066 Sema::ActOnReenterTemplateScope(Decl *D,
10067                                 llvm::function_ref<Scope *()> EnterScope) {
10068   if (!D)
10069     return 0;
10070   AdjustDeclIfTemplate(D);
10071 
10072   // In order to get name lookup right, reenter template scopes in order from
10073   // outermost to innermost.
10074   SmallVector<TemplateParameterList *, 4> ParameterLists;
10075   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10076 
10077   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10078     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10079       ParameterLists.push_back(DD->getTemplateParameterList(i));
10080 
10081     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10082       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10083         ParameterLists.push_back(FTD->getTemplateParameters());
10084     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10085       LookupDC = VD->getDeclContext();
10086 
10087       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10088         ParameterLists.push_back(VTD->getTemplateParameters());
10089       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10090         ParameterLists.push_back(PSD->getTemplateParameters());
10091     }
10092   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10093     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10094       ParameterLists.push_back(TD->getTemplateParameterList(i));
10095 
10096     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10097       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10098         ParameterLists.push_back(CTD->getTemplateParameters());
10099       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10100         ParameterLists.push_back(PSD->getTemplateParameters());
10101     }
10102   }
10103   // FIXME: Alias declarations and concepts.
10104 
10105   unsigned Count = 0;
10106   Scope *InnermostTemplateScope = nullptr;
10107   for (TemplateParameterList *Params : ParameterLists) {
10108     // Ignore explicit specializations; they don't contribute to the template
10109     // depth.
10110     if (Params->size() == 0)
10111       continue;
10112 
10113     InnermostTemplateScope = EnterScope();
10114     for (NamedDecl *Param : *Params) {
10115       if (Param->getDeclName()) {
10116         InnermostTemplateScope->AddDecl(Param);
10117         IdResolver.AddDecl(Param);
10118       }
10119     }
10120     ++Count;
10121   }
10122 
10123   // Associate the new template scopes with the corresponding entities.
10124   if (InnermostTemplateScope) {
10125     assert(LookupDC && "no enclosing DeclContext for template lookup");
10126     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10127   }
10128 
10129   return Count;
10130 }
10131 
10132 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10133   if (!RecordD) return;
10134   AdjustDeclIfTemplate(RecordD);
10135   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10136   PushDeclContext(S, Record);
10137 }
10138 
10139 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10140   if (!RecordD) return;
10141   PopDeclContext();
10142 }
10143 
10144 /// This is used to implement the constant expression evaluation part of the
10145 /// attribute enable_if extension. There is nothing in standard C++ which would
10146 /// require reentering parameters.
10147 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10148   if (!Param)
10149     return;
10150 
10151   S->AddDecl(Param);
10152   if (Param->getDeclName())
10153     IdResolver.AddDecl(Param);
10154 }
10155 
10156 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10157 /// parsing a top-level (non-nested) C++ class, and we are now
10158 /// parsing those parts of the given Method declaration that could
10159 /// not be parsed earlier (C++ [class.mem]p2), such as default
10160 /// arguments. This action should enter the scope of the given
10161 /// Method declaration as if we had just parsed the qualified method
10162 /// name. However, it should not bring the parameters into scope;
10163 /// that will be performed by ActOnDelayedCXXMethodParameter.
10164 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10165 }
10166 
10167 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10168 /// C++ method declaration. We're (re-)introducing the given
10169 /// function parameter into scope for use in parsing later parts of
10170 /// the method declaration. For example, we could see an
10171 /// ActOnParamDefaultArgument event for this parameter.
10172 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10173   if (!ParamD)
10174     return;
10175 
10176   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10177 
10178   S->AddDecl(Param);
10179   if (Param->getDeclName())
10180     IdResolver.AddDecl(Param);
10181 }
10182 
10183 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10184 /// processing the delayed method declaration for Method. The method
10185 /// declaration is now considered finished. There may be a separate
10186 /// ActOnStartOfFunctionDef action later (not necessarily
10187 /// immediately!) for this method, if it was also defined inside the
10188 /// class body.
10189 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10190   if (!MethodD)
10191     return;
10192 
10193   AdjustDeclIfTemplate(MethodD);
10194 
10195   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10196 
10197   // Now that we have our default arguments, check the constructor
10198   // again. It could produce additional diagnostics or affect whether
10199   // the class has implicitly-declared destructors, among other
10200   // things.
10201   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10202     CheckConstructor(Constructor);
10203 
10204   // Check the default arguments, which we may have added.
10205   if (!Method->isInvalidDecl())
10206     CheckCXXDefaultArguments(Method);
10207 }
10208 
10209 // Emit the given diagnostic for each non-address-space qualifier.
10210 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10211 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10212   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10213   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10214     bool DiagOccured = false;
10215     FTI.MethodQualifiers->forEachQualifier(
10216         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10217                                    SourceLocation SL) {
10218           // This diagnostic should be emitted on any qualifier except an addr
10219           // space qualifier. However, forEachQualifier currently doesn't visit
10220           // addr space qualifiers, so there's no way to write this condition
10221           // right now; we just diagnose on everything.
10222           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10223           DiagOccured = true;
10224         });
10225     if (DiagOccured)
10226       D.setInvalidType();
10227   }
10228 }
10229 
10230 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10231 /// the well-formedness of the constructor declarator @p D with type @p
10232 /// R. If there are any errors in the declarator, this routine will
10233 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10234 /// will be updated to reflect a well-formed type for the constructor and
10235 /// returned.
10236 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10237                                           StorageClass &SC) {
10238   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10239 
10240   // C++ [class.ctor]p3:
10241   //   A constructor shall not be virtual (10.3) or static (9.4). A
10242   //   constructor can be invoked for a const, volatile or const
10243   //   volatile object. A constructor shall not be declared const,
10244   //   volatile, or const volatile (9.3.2).
10245   if (isVirtual) {
10246     if (!D.isInvalidType())
10247       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10248         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10249         << SourceRange(D.getIdentifierLoc());
10250     D.setInvalidType();
10251   }
10252   if (SC == SC_Static) {
10253     if (!D.isInvalidType())
10254       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10255         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10256         << SourceRange(D.getIdentifierLoc());
10257     D.setInvalidType();
10258     SC = SC_None;
10259   }
10260 
10261   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10262     diagnoseIgnoredQualifiers(
10263         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10264         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10265         D.getDeclSpec().getRestrictSpecLoc(),
10266         D.getDeclSpec().getAtomicSpecLoc());
10267     D.setInvalidType();
10268   }
10269 
10270   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10271 
10272   // C++0x [class.ctor]p4:
10273   //   A constructor shall not be declared with a ref-qualifier.
10274   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10275   if (FTI.hasRefQualifier()) {
10276     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10277       << FTI.RefQualifierIsLValueRef
10278       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10279     D.setInvalidType();
10280   }
10281 
10282   // Rebuild the function type "R" without any type qualifiers (in
10283   // case any of the errors above fired) and with "void" as the
10284   // return type, since constructors don't have return types.
10285   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10286   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10287     return R;
10288 
10289   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10290   EPI.TypeQuals = Qualifiers();
10291   EPI.RefQualifier = RQ_None;
10292 
10293   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10294 }
10295 
10296 /// CheckConstructor - Checks a fully-formed constructor for
10297 /// well-formedness, issuing any diagnostics required. Returns true if
10298 /// the constructor declarator is invalid.
10299 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10300   CXXRecordDecl *ClassDecl
10301     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10302   if (!ClassDecl)
10303     return Constructor->setInvalidDecl();
10304 
10305   // C++ [class.copy]p3:
10306   //   A declaration of a constructor for a class X is ill-formed if
10307   //   its first parameter is of type (optionally cv-qualified) X and
10308   //   either there are no other parameters or else all other
10309   //   parameters have default arguments.
10310   if (!Constructor->isInvalidDecl() &&
10311       Constructor->hasOneParamOrDefaultArgs() &&
10312       Constructor->getTemplateSpecializationKind() !=
10313           TSK_ImplicitInstantiation) {
10314     QualType ParamType = Constructor->getParamDecl(0)->getType();
10315     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10316     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10317       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10318       const char *ConstRef
10319         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10320                                                         : " const &";
10321       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10322         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10323 
10324       // FIXME: Rather that making the constructor invalid, we should endeavor
10325       // to fix the type.
10326       Constructor->setInvalidDecl();
10327     }
10328   }
10329 }
10330 
10331 /// CheckDestructor - Checks a fully-formed destructor definition for
10332 /// well-formedness, issuing any diagnostics required.  Returns true
10333 /// on error.
10334 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10335   CXXRecordDecl *RD = Destructor->getParent();
10336 
10337   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10338     SourceLocation Loc;
10339 
10340     if (!Destructor->isImplicit())
10341       Loc = Destructor->getLocation();
10342     else
10343       Loc = RD->getLocation();
10344 
10345     // If we have a virtual destructor, look up the deallocation function
10346     if (FunctionDecl *OperatorDelete =
10347             FindDeallocationFunctionForDestructor(Loc, RD)) {
10348       Expr *ThisArg = nullptr;
10349 
10350       // If the notional 'delete this' expression requires a non-trivial
10351       // conversion from 'this' to the type of a destroying operator delete's
10352       // first parameter, perform that conversion now.
10353       if (OperatorDelete->isDestroyingOperatorDelete()) {
10354         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10355         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10356           // C++ [class.dtor]p13:
10357           //   ... as if for the expression 'delete this' appearing in a
10358           //   non-virtual destructor of the destructor's class.
10359           ContextRAII SwitchContext(*this, Destructor);
10360           ExprResult This =
10361               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10362           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10363           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10364           if (This.isInvalid()) {
10365             // FIXME: Register this as a context note so that it comes out
10366             // in the right order.
10367             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10368             return true;
10369           }
10370           ThisArg = This.get();
10371         }
10372       }
10373 
10374       DiagnoseUseOfDecl(OperatorDelete, Loc);
10375       MarkFunctionReferenced(Loc, OperatorDelete);
10376       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10377     }
10378   }
10379 
10380   return false;
10381 }
10382 
10383 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10384 /// the well-formednes of the destructor declarator @p D with type @p
10385 /// R. If there are any errors in the declarator, this routine will
10386 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10387 /// will be updated to reflect a well-formed type for the destructor and
10388 /// returned.
10389 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10390                                          StorageClass& SC) {
10391   // C++ [class.dtor]p1:
10392   //   [...] A typedef-name that names a class is a class-name
10393   //   (7.1.3); however, a typedef-name that names a class shall not
10394   //   be used as the identifier in the declarator for a destructor
10395   //   declaration.
10396   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10397   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10398     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10399       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10400   else if (const TemplateSpecializationType *TST =
10401              DeclaratorType->getAs<TemplateSpecializationType>())
10402     if (TST->isTypeAlias())
10403       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10404         << DeclaratorType << 1;
10405 
10406   // C++ [class.dtor]p2:
10407   //   A destructor is used to destroy objects of its class type. A
10408   //   destructor takes no parameters, and no return type can be
10409   //   specified for it (not even void). The address of a destructor
10410   //   shall not be taken. A destructor shall not be static. A
10411   //   destructor can be invoked for a const, volatile or const
10412   //   volatile object. A destructor shall not be declared const,
10413   //   volatile or const volatile (9.3.2).
10414   if (SC == SC_Static) {
10415     if (!D.isInvalidType())
10416       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10417         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10418         << SourceRange(D.getIdentifierLoc())
10419         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10420 
10421     SC = SC_None;
10422   }
10423   if (!D.isInvalidType()) {
10424     // Destructors don't have return types, but the parser will
10425     // happily parse something like:
10426     //
10427     //   class X {
10428     //     float ~X();
10429     //   };
10430     //
10431     // The return type will be eliminated later.
10432     if (D.getDeclSpec().hasTypeSpecifier())
10433       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10434         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10435         << SourceRange(D.getIdentifierLoc());
10436     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10437       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10438                                 SourceLocation(),
10439                                 D.getDeclSpec().getConstSpecLoc(),
10440                                 D.getDeclSpec().getVolatileSpecLoc(),
10441                                 D.getDeclSpec().getRestrictSpecLoc(),
10442                                 D.getDeclSpec().getAtomicSpecLoc());
10443       D.setInvalidType();
10444     }
10445   }
10446 
10447   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10448 
10449   // C++0x [class.dtor]p2:
10450   //   A destructor shall not be declared with a ref-qualifier.
10451   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10452   if (FTI.hasRefQualifier()) {
10453     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10454       << FTI.RefQualifierIsLValueRef
10455       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10456     D.setInvalidType();
10457   }
10458 
10459   // Make sure we don't have any parameters.
10460   if (FTIHasNonVoidParameters(FTI)) {
10461     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10462 
10463     // Delete the parameters.
10464     FTI.freeParams();
10465     D.setInvalidType();
10466   }
10467 
10468   // Make sure the destructor isn't variadic.
10469   if (FTI.isVariadic) {
10470     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10471     D.setInvalidType();
10472   }
10473 
10474   // Rebuild the function type "R" without any type qualifiers or
10475   // parameters (in case any of the errors above fired) and with
10476   // "void" as the return type, since destructors don't have return
10477   // types.
10478   if (!D.isInvalidType())
10479     return R;
10480 
10481   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10482   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10483   EPI.Variadic = false;
10484   EPI.TypeQuals = Qualifiers();
10485   EPI.RefQualifier = RQ_None;
10486   return Context.getFunctionType(Context.VoidTy, None, EPI);
10487 }
10488 
10489 static void extendLeft(SourceRange &R, SourceRange Before) {
10490   if (Before.isInvalid())
10491     return;
10492   R.setBegin(Before.getBegin());
10493   if (R.getEnd().isInvalid())
10494     R.setEnd(Before.getEnd());
10495 }
10496 
10497 static void extendRight(SourceRange &R, SourceRange After) {
10498   if (After.isInvalid())
10499     return;
10500   if (R.getBegin().isInvalid())
10501     R.setBegin(After.getBegin());
10502   R.setEnd(After.getEnd());
10503 }
10504 
10505 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10506 /// well-formednes of the conversion function declarator @p D with
10507 /// type @p R. If there are any errors in the declarator, this routine
10508 /// will emit diagnostics and return true. Otherwise, it will return
10509 /// false. Either way, the type @p R will be updated to reflect a
10510 /// well-formed type for the conversion operator.
10511 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10512                                      StorageClass& SC) {
10513   // C++ [class.conv.fct]p1:
10514   //   Neither parameter types nor return type can be specified. The
10515   //   type of a conversion function (8.3.5) is "function taking no
10516   //   parameter returning conversion-type-id."
10517   if (SC == SC_Static) {
10518     if (!D.isInvalidType())
10519       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10520         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10521         << D.getName().getSourceRange();
10522     D.setInvalidType();
10523     SC = SC_None;
10524   }
10525 
10526   TypeSourceInfo *ConvTSI = nullptr;
10527   QualType ConvType =
10528       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10529 
10530   const DeclSpec &DS = D.getDeclSpec();
10531   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10532     // Conversion functions don't have return types, but the parser will
10533     // happily parse something like:
10534     //
10535     //   class X {
10536     //     float operator bool();
10537     //   };
10538     //
10539     // The return type will be changed later anyway.
10540     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10541       << SourceRange(DS.getTypeSpecTypeLoc())
10542       << SourceRange(D.getIdentifierLoc());
10543     D.setInvalidType();
10544   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10545     // It's also plausible that the user writes type qualifiers in the wrong
10546     // place, such as:
10547     //   struct S { const operator int(); };
10548     // FIXME: we could provide a fixit to move the qualifiers onto the
10549     // conversion type.
10550     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10551         << SourceRange(D.getIdentifierLoc()) << 0;
10552     D.setInvalidType();
10553   }
10554 
10555   const auto *Proto = R->castAs<FunctionProtoType>();
10556 
10557   // Make sure we don't have any parameters.
10558   if (Proto->getNumParams() > 0) {
10559     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10560 
10561     // Delete the parameters.
10562     D.getFunctionTypeInfo().freeParams();
10563     D.setInvalidType();
10564   } else if (Proto->isVariadic()) {
10565     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10566     D.setInvalidType();
10567   }
10568 
10569   // Diagnose "&operator bool()" and other such nonsense.  This
10570   // is actually a gcc extension which we don't support.
10571   if (Proto->getReturnType() != ConvType) {
10572     bool NeedsTypedef = false;
10573     SourceRange Before, After;
10574 
10575     // Walk the chunks and extract information on them for our diagnostic.
10576     bool PastFunctionChunk = false;
10577     for (auto &Chunk : D.type_objects()) {
10578       switch (Chunk.Kind) {
10579       case DeclaratorChunk::Function:
10580         if (!PastFunctionChunk) {
10581           if (Chunk.Fun.HasTrailingReturnType) {
10582             TypeSourceInfo *TRT = nullptr;
10583             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10584             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10585           }
10586           PastFunctionChunk = true;
10587           break;
10588         }
10589         LLVM_FALLTHROUGH;
10590       case DeclaratorChunk::Array:
10591         NeedsTypedef = true;
10592         extendRight(After, Chunk.getSourceRange());
10593         break;
10594 
10595       case DeclaratorChunk::Pointer:
10596       case DeclaratorChunk::BlockPointer:
10597       case DeclaratorChunk::Reference:
10598       case DeclaratorChunk::MemberPointer:
10599       case DeclaratorChunk::Pipe:
10600         extendLeft(Before, Chunk.getSourceRange());
10601         break;
10602 
10603       case DeclaratorChunk::Paren:
10604         extendLeft(Before, Chunk.Loc);
10605         extendRight(After, Chunk.EndLoc);
10606         break;
10607       }
10608     }
10609 
10610     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10611                          After.isValid()  ? After.getBegin() :
10612                                             D.getIdentifierLoc();
10613     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10614     DB << Before << After;
10615 
10616     if (!NeedsTypedef) {
10617       DB << /*don't need a typedef*/0;
10618 
10619       // If we can provide a correct fix-it hint, do so.
10620       if (After.isInvalid() && ConvTSI) {
10621         SourceLocation InsertLoc =
10622             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10623         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10624            << FixItHint::CreateInsertionFromRange(
10625                   InsertLoc, CharSourceRange::getTokenRange(Before))
10626            << FixItHint::CreateRemoval(Before);
10627       }
10628     } else if (!Proto->getReturnType()->isDependentType()) {
10629       DB << /*typedef*/1 << Proto->getReturnType();
10630     } else if (getLangOpts().CPlusPlus11) {
10631       DB << /*alias template*/2 << Proto->getReturnType();
10632     } else {
10633       DB << /*might not be fixable*/3;
10634     }
10635 
10636     // Recover by incorporating the other type chunks into the result type.
10637     // Note, this does *not* change the name of the function. This is compatible
10638     // with the GCC extension:
10639     //   struct S { &operator int(); } s;
10640     //   int &r = s.operator int(); // ok in GCC
10641     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10642     ConvType = Proto->getReturnType();
10643   }
10644 
10645   // C++ [class.conv.fct]p4:
10646   //   The conversion-type-id shall not represent a function type nor
10647   //   an array type.
10648   if (ConvType->isArrayType()) {
10649     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10650     ConvType = Context.getPointerType(ConvType);
10651     D.setInvalidType();
10652   } else if (ConvType->isFunctionType()) {
10653     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10654     ConvType = Context.getPointerType(ConvType);
10655     D.setInvalidType();
10656   }
10657 
10658   // Rebuild the function type "R" without any parameters (in case any
10659   // of the errors above fired) and with the conversion type as the
10660   // return type.
10661   if (D.isInvalidType())
10662     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10663 
10664   // C++0x explicit conversion operators.
10665   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10666     Diag(DS.getExplicitSpecLoc(),
10667          getLangOpts().CPlusPlus11
10668              ? diag::warn_cxx98_compat_explicit_conversion_functions
10669              : diag::ext_explicit_conversion_functions)
10670         << SourceRange(DS.getExplicitSpecRange());
10671 }
10672 
10673 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10674 /// the declaration of the given C++ conversion function. This routine
10675 /// is responsible for recording the conversion function in the C++
10676 /// class, if possible.
10677 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10678   assert(Conversion && "Expected to receive a conversion function declaration");
10679 
10680   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10681 
10682   // Make sure we aren't redeclaring the conversion function.
10683   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10684   // C++ [class.conv.fct]p1:
10685   //   [...] A conversion function is never used to convert a
10686   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10687   //   same object type (or a reference to it), to a (possibly
10688   //   cv-qualified) base class of that type (or a reference to it),
10689   //   or to (possibly cv-qualified) void.
10690   QualType ClassType
10691     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10692   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10693     ConvType = ConvTypeRef->getPointeeType();
10694   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10695       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10696     /* Suppress diagnostics for instantiations. */;
10697   else if (Conversion->size_overridden_methods() != 0)
10698     /* Suppress diagnostics for overriding virtual function in a base class. */;
10699   else if (ConvType->isRecordType()) {
10700     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10701     if (ConvType == ClassType)
10702       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10703         << ClassType;
10704     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10705       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10706         <<  ClassType << ConvType;
10707   } else if (ConvType->isVoidType()) {
10708     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10709       << ClassType << ConvType;
10710   }
10711 
10712   if (FunctionTemplateDecl *ConversionTemplate
10713                                 = Conversion->getDescribedFunctionTemplate())
10714     return ConversionTemplate;
10715 
10716   return Conversion;
10717 }
10718 
10719 namespace {
10720 /// Utility class to accumulate and print a diagnostic listing the invalid
10721 /// specifier(s) on a declaration.
10722 struct BadSpecifierDiagnoser {
10723   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10724       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10725   ~BadSpecifierDiagnoser() {
10726     Diagnostic << Specifiers;
10727   }
10728 
10729   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10730     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10731   }
10732   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10733     return check(SpecLoc,
10734                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10735   }
10736   void check(SourceLocation SpecLoc, const char *Spec) {
10737     if (SpecLoc.isInvalid()) return;
10738     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10739     if (!Specifiers.empty()) Specifiers += " ";
10740     Specifiers += Spec;
10741   }
10742 
10743   Sema &S;
10744   Sema::SemaDiagnosticBuilder Diagnostic;
10745   std::string Specifiers;
10746 };
10747 }
10748 
10749 /// Check the validity of a declarator that we parsed for a deduction-guide.
10750 /// These aren't actually declarators in the grammar, so we need to check that
10751 /// the user didn't specify any pieces that are not part of the deduction-guide
10752 /// grammar.
10753 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10754                                          StorageClass &SC) {
10755   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10756   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10757   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10758 
10759   // C++ [temp.deduct.guide]p3:
10760   //   A deduction-gide shall be declared in the same scope as the
10761   //   corresponding class template.
10762   if (!CurContext->getRedeclContext()->Equals(
10763           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10764     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10765       << GuidedTemplateDecl;
10766     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10767   }
10768 
10769   auto &DS = D.getMutableDeclSpec();
10770   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10771   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10772       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10773       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10774     BadSpecifierDiagnoser Diagnoser(
10775         *this, D.getIdentifierLoc(),
10776         diag::err_deduction_guide_invalid_specifier);
10777 
10778     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10779     DS.ClearStorageClassSpecs();
10780     SC = SC_None;
10781 
10782     // 'explicit' is permitted.
10783     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10784     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10785     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10786     DS.ClearConstexprSpec();
10787 
10788     Diagnoser.check(DS.getConstSpecLoc(), "const");
10789     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10790     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10791     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10792     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10793     DS.ClearTypeQualifiers();
10794 
10795     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10796     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10797     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10798     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10799     DS.ClearTypeSpecType();
10800   }
10801 
10802   if (D.isInvalidType())
10803     return;
10804 
10805   // Check the declarator is simple enough.
10806   bool FoundFunction = false;
10807   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10808     if (Chunk.Kind == DeclaratorChunk::Paren)
10809       continue;
10810     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10811       Diag(D.getDeclSpec().getBeginLoc(),
10812            diag::err_deduction_guide_with_complex_decl)
10813           << D.getSourceRange();
10814       break;
10815     }
10816     if (!Chunk.Fun.hasTrailingReturnType()) {
10817       Diag(D.getName().getBeginLoc(),
10818            diag::err_deduction_guide_no_trailing_return_type);
10819       break;
10820     }
10821 
10822     // Check that the return type is written as a specialization of
10823     // the template specified as the deduction-guide's name.
10824     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10825     TypeSourceInfo *TSI = nullptr;
10826     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10827     assert(TSI && "deduction guide has valid type but invalid return type?");
10828     bool AcceptableReturnType = false;
10829     bool MightInstantiateToSpecialization = false;
10830     if (auto RetTST =
10831             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10832       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10833       bool TemplateMatches =
10834           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10835       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10836         AcceptableReturnType = true;
10837       else {
10838         // This could still instantiate to the right type, unless we know it
10839         // names the wrong class template.
10840         auto *TD = SpecifiedName.getAsTemplateDecl();
10841         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10842                                              !TemplateMatches);
10843       }
10844     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10845       MightInstantiateToSpecialization = true;
10846     }
10847 
10848     if (!AcceptableReturnType) {
10849       Diag(TSI->getTypeLoc().getBeginLoc(),
10850            diag::err_deduction_guide_bad_trailing_return_type)
10851           << GuidedTemplate << TSI->getType()
10852           << MightInstantiateToSpecialization
10853           << TSI->getTypeLoc().getSourceRange();
10854     }
10855 
10856     // Keep going to check that we don't have any inner declarator pieces (we
10857     // could still have a function returning a pointer to a function).
10858     FoundFunction = true;
10859   }
10860 
10861   if (D.isFunctionDefinition())
10862     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10863 }
10864 
10865 //===----------------------------------------------------------------------===//
10866 // Namespace Handling
10867 //===----------------------------------------------------------------------===//
10868 
10869 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10870 /// reopened.
10871 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10872                                             SourceLocation Loc,
10873                                             IdentifierInfo *II, bool *IsInline,
10874                                             NamespaceDecl *PrevNS) {
10875   assert(*IsInline != PrevNS->isInline());
10876 
10877   if (PrevNS->isInline())
10878     // The user probably just forgot the 'inline', so suggest that it
10879     // be added back.
10880     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10881       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10882   else
10883     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10884 
10885   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10886   *IsInline = PrevNS->isInline();
10887 }
10888 
10889 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10890 /// definition.
10891 Decl *Sema::ActOnStartNamespaceDef(
10892     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10893     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10894     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10895   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10896   // For anonymous namespace, take the location of the left brace.
10897   SourceLocation Loc = II ? IdentLoc : LBrace;
10898   bool IsInline = InlineLoc.isValid();
10899   bool IsInvalid = false;
10900   bool IsStd = false;
10901   bool AddToKnown = false;
10902   Scope *DeclRegionScope = NamespcScope->getParent();
10903 
10904   NamespaceDecl *PrevNS = nullptr;
10905   if (II) {
10906     // C++ [namespace.def]p2:
10907     //   The identifier in an original-namespace-definition shall not
10908     //   have been previously defined in the declarative region in
10909     //   which the original-namespace-definition appears. The
10910     //   identifier in an original-namespace-definition is the name of
10911     //   the namespace. Subsequently in that declarative region, it is
10912     //   treated as an original-namespace-name.
10913     //
10914     // Since namespace names are unique in their scope, and we don't
10915     // look through using directives, just look for any ordinary names
10916     // as if by qualified name lookup.
10917     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10918                    ForExternalRedeclaration);
10919     LookupQualifiedName(R, CurContext->getRedeclContext());
10920     NamedDecl *PrevDecl =
10921         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10922     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10923 
10924     if (PrevNS) {
10925       // This is an extended namespace definition.
10926       if (IsInline != PrevNS->isInline())
10927         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10928                                         &IsInline, PrevNS);
10929     } else if (PrevDecl) {
10930       // This is an invalid name redefinition.
10931       Diag(Loc, diag::err_redefinition_different_kind)
10932         << II;
10933       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10934       IsInvalid = true;
10935       // Continue on to push Namespc as current DeclContext and return it.
10936     } else if (II->isStr("std") &&
10937                CurContext->getRedeclContext()->isTranslationUnit()) {
10938       // This is the first "real" definition of the namespace "std", so update
10939       // our cache of the "std" namespace to point at this definition.
10940       PrevNS = getStdNamespace();
10941       IsStd = true;
10942       AddToKnown = !IsInline;
10943     } else {
10944       // We've seen this namespace for the first time.
10945       AddToKnown = !IsInline;
10946     }
10947   } else {
10948     // Anonymous namespaces.
10949 
10950     // Determine whether the parent already has an anonymous namespace.
10951     DeclContext *Parent = CurContext->getRedeclContext();
10952     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10953       PrevNS = TU->getAnonymousNamespace();
10954     } else {
10955       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10956       PrevNS = ND->getAnonymousNamespace();
10957     }
10958 
10959     if (PrevNS && IsInline != PrevNS->isInline())
10960       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10961                                       &IsInline, PrevNS);
10962   }
10963 
10964   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10965                                                  StartLoc, Loc, II, PrevNS);
10966   if (IsInvalid)
10967     Namespc->setInvalidDecl();
10968 
10969   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10970   AddPragmaAttributes(DeclRegionScope, Namespc);
10971 
10972   // FIXME: Should we be merging attributes?
10973   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10974     PushNamespaceVisibilityAttr(Attr, Loc);
10975 
10976   if (IsStd)
10977     StdNamespace = Namespc;
10978   if (AddToKnown)
10979     KnownNamespaces[Namespc] = false;
10980 
10981   if (II) {
10982     PushOnScopeChains(Namespc, DeclRegionScope);
10983   } else {
10984     // Link the anonymous namespace into its parent.
10985     DeclContext *Parent = CurContext->getRedeclContext();
10986     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10987       TU->setAnonymousNamespace(Namespc);
10988     } else {
10989       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10990     }
10991 
10992     CurContext->addDecl(Namespc);
10993 
10994     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10995     //   behaves as if it were replaced by
10996     //     namespace unique { /* empty body */ }
10997     //     using namespace unique;
10998     //     namespace unique { namespace-body }
10999     //   where all occurrences of 'unique' in a translation unit are
11000     //   replaced by the same identifier and this identifier differs
11001     //   from all other identifiers in the entire program.
11002 
11003     // We just create the namespace with an empty name and then add an
11004     // implicit using declaration, just like the standard suggests.
11005     //
11006     // CodeGen enforces the "universally unique" aspect by giving all
11007     // declarations semantically contained within an anonymous
11008     // namespace internal linkage.
11009 
11010     if (!PrevNS) {
11011       UD = UsingDirectiveDecl::Create(Context, Parent,
11012                                       /* 'using' */ LBrace,
11013                                       /* 'namespace' */ SourceLocation(),
11014                                       /* qualifier */ NestedNameSpecifierLoc(),
11015                                       /* identifier */ SourceLocation(),
11016                                       Namespc,
11017                                       /* Ancestor */ Parent);
11018       UD->setImplicit();
11019       Parent->addDecl(UD);
11020     }
11021   }
11022 
11023   ActOnDocumentableDecl(Namespc);
11024 
11025   // Although we could have an invalid decl (i.e. the namespace name is a
11026   // redefinition), push it as current DeclContext and try to continue parsing.
11027   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11028   // for the namespace has the declarations that showed up in that particular
11029   // namespace definition.
11030   PushDeclContext(NamespcScope, Namespc);
11031   return Namespc;
11032 }
11033 
11034 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11035 /// is a namespace alias, returns the namespace it points to.
11036 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11037   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11038     return AD->getNamespace();
11039   return dyn_cast_or_null<NamespaceDecl>(D);
11040 }
11041 
11042 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11043 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11044 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11045   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11046   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11047   Namespc->setRBraceLoc(RBrace);
11048   PopDeclContext();
11049   if (Namespc->hasAttr<VisibilityAttr>())
11050     PopPragmaVisibility(true, RBrace);
11051   // If this namespace contains an export-declaration, export it now.
11052   if (DeferredExportedNamespaces.erase(Namespc))
11053     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11054 }
11055 
11056 CXXRecordDecl *Sema::getStdBadAlloc() const {
11057   return cast_or_null<CXXRecordDecl>(
11058                                   StdBadAlloc.get(Context.getExternalSource()));
11059 }
11060 
11061 EnumDecl *Sema::getStdAlignValT() const {
11062   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11063 }
11064 
11065 NamespaceDecl *Sema::getStdNamespace() const {
11066   return cast_or_null<NamespaceDecl>(
11067                                  StdNamespace.get(Context.getExternalSource()));
11068 }
11069 
11070 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11071   if (!StdExperimentalNamespaceCache) {
11072     if (auto Std = getStdNamespace()) {
11073       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11074                           SourceLocation(), LookupNamespaceName);
11075       if (!LookupQualifiedName(Result, Std) ||
11076           !(StdExperimentalNamespaceCache =
11077                 Result.getAsSingle<NamespaceDecl>()))
11078         Result.suppressDiagnostics();
11079     }
11080   }
11081   return StdExperimentalNamespaceCache;
11082 }
11083 
11084 namespace {
11085 
11086 enum UnsupportedSTLSelect {
11087   USS_InvalidMember,
11088   USS_MissingMember,
11089   USS_NonTrivial,
11090   USS_Other
11091 };
11092 
11093 struct InvalidSTLDiagnoser {
11094   Sema &S;
11095   SourceLocation Loc;
11096   QualType TyForDiags;
11097 
11098   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11099                       const VarDecl *VD = nullptr) {
11100     {
11101       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11102                << TyForDiags << ((int)Sel);
11103       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11104         assert(!Name.empty());
11105         D << Name;
11106       }
11107     }
11108     if (Sel == USS_InvalidMember) {
11109       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11110           << VD << VD->getSourceRange();
11111     }
11112     return QualType();
11113   }
11114 };
11115 } // namespace
11116 
11117 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11118                                            SourceLocation Loc,
11119                                            ComparisonCategoryUsage Usage) {
11120   assert(getLangOpts().CPlusPlus &&
11121          "Looking for comparison category type outside of C++.");
11122 
11123   // Use an elaborated type for diagnostics which has a name containing the
11124   // prepended 'std' namespace but not any inline namespace names.
11125   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11126     auto *NNS =
11127         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11128     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11129   };
11130 
11131   // Check if we've already successfully checked the comparison category type
11132   // before. If so, skip checking it again.
11133   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11134   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11135     // The only thing we need to check is that the type has a reachable
11136     // definition in the current context.
11137     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11138       return QualType();
11139 
11140     return Info->getType();
11141   }
11142 
11143   // If lookup failed
11144   if (!Info) {
11145     std::string NameForDiags = "std::";
11146     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11147     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11148         << NameForDiags << (int)Usage;
11149     return QualType();
11150   }
11151 
11152   assert(Info->Kind == Kind);
11153   assert(Info->Record);
11154 
11155   // Update the Record decl in case we encountered a forward declaration on our
11156   // first pass. FIXME: This is a bit of a hack.
11157   if (Info->Record->hasDefinition())
11158     Info->Record = Info->Record->getDefinition();
11159 
11160   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11161     return QualType();
11162 
11163   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11164 
11165   if (!Info->Record->isTriviallyCopyable())
11166     return UnsupportedSTLError(USS_NonTrivial);
11167 
11168   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11169     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11170     // Tolerate empty base classes.
11171     if (Base->isEmpty())
11172       continue;
11173     // Reject STL implementations which have at least one non-empty base.
11174     return UnsupportedSTLError();
11175   }
11176 
11177   // Check that the STL has implemented the types using a single integer field.
11178   // This expectation allows better codegen for builtin operators. We require:
11179   //   (1) The class has exactly one field.
11180   //   (2) The field is an integral or enumeration type.
11181   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11182   if (std::distance(FIt, FEnd) != 1 ||
11183       !FIt->getType()->isIntegralOrEnumerationType()) {
11184     return UnsupportedSTLError();
11185   }
11186 
11187   // Build each of the require values and store them in Info.
11188   for (ComparisonCategoryResult CCR :
11189        ComparisonCategories::getPossibleResultsForType(Kind)) {
11190     StringRef MemName = ComparisonCategories::getResultString(CCR);
11191     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11192 
11193     if (!ValInfo)
11194       return UnsupportedSTLError(USS_MissingMember, MemName);
11195 
11196     VarDecl *VD = ValInfo->VD;
11197     assert(VD && "should not be null!");
11198 
11199     // Attempt to diagnose reasons why the STL definition of this type
11200     // might be foobar, including it failing to be a constant expression.
11201     // TODO Handle more ways the lookup or result can be invalid.
11202     if (!VD->isStaticDataMember() ||
11203         !VD->isUsableInConstantExpressions(Context))
11204       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11205 
11206     // Attempt to evaluate the var decl as a constant expression and extract
11207     // the value of its first field as a ICE. If this fails, the STL
11208     // implementation is not supported.
11209     if (!ValInfo->hasValidIntValue())
11210       return UnsupportedSTLError();
11211 
11212     MarkVariableReferenced(Loc, VD);
11213   }
11214 
11215   // We've successfully built the required types and expressions. Update
11216   // the cache and return the newly cached value.
11217   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11218   return Info->getType();
11219 }
11220 
11221 /// Retrieve the special "std" namespace, which may require us to
11222 /// implicitly define the namespace.
11223 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11224   if (!StdNamespace) {
11225     // The "std" namespace has not yet been defined, so build one implicitly.
11226     StdNamespace = NamespaceDecl::Create(Context,
11227                                          Context.getTranslationUnitDecl(),
11228                                          /*Inline=*/false,
11229                                          SourceLocation(), SourceLocation(),
11230                                          &PP.getIdentifierTable().get("std"),
11231                                          /*PrevDecl=*/nullptr);
11232     getStdNamespace()->setImplicit(true);
11233   }
11234 
11235   return getStdNamespace();
11236 }
11237 
11238 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11239   assert(getLangOpts().CPlusPlus &&
11240          "Looking for std::initializer_list outside of C++.");
11241 
11242   // We're looking for implicit instantiations of
11243   // template <typename E> class std::initializer_list.
11244 
11245   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11246     return false;
11247 
11248   ClassTemplateDecl *Template = nullptr;
11249   const TemplateArgument *Arguments = nullptr;
11250 
11251   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11252 
11253     ClassTemplateSpecializationDecl *Specialization =
11254         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11255     if (!Specialization)
11256       return false;
11257 
11258     Template = Specialization->getSpecializedTemplate();
11259     Arguments = Specialization->getTemplateArgs().data();
11260   } else if (const TemplateSpecializationType *TST =
11261                  Ty->getAs<TemplateSpecializationType>()) {
11262     Template = dyn_cast_or_null<ClassTemplateDecl>(
11263         TST->getTemplateName().getAsTemplateDecl());
11264     Arguments = TST->getArgs();
11265   }
11266   if (!Template)
11267     return false;
11268 
11269   if (!StdInitializerList) {
11270     // Haven't recognized std::initializer_list yet, maybe this is it.
11271     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11272     if (TemplateClass->getIdentifier() !=
11273             &PP.getIdentifierTable().get("initializer_list") ||
11274         !getStdNamespace()->InEnclosingNamespaceSetOf(
11275             TemplateClass->getDeclContext()))
11276       return false;
11277     // This is a template called std::initializer_list, but is it the right
11278     // template?
11279     TemplateParameterList *Params = Template->getTemplateParameters();
11280     if (Params->getMinRequiredArguments() != 1)
11281       return false;
11282     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11283       return false;
11284 
11285     // It's the right template.
11286     StdInitializerList = Template;
11287   }
11288 
11289   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11290     return false;
11291 
11292   // This is an instance of std::initializer_list. Find the argument type.
11293   if (Element)
11294     *Element = Arguments[0].getAsType();
11295   return true;
11296 }
11297 
11298 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11299   NamespaceDecl *Std = S.getStdNamespace();
11300   if (!Std) {
11301     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11302     return nullptr;
11303   }
11304 
11305   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11306                       Loc, Sema::LookupOrdinaryName);
11307   if (!S.LookupQualifiedName(Result, Std)) {
11308     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11309     return nullptr;
11310   }
11311   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11312   if (!Template) {
11313     Result.suppressDiagnostics();
11314     // We found something weird. Complain about the first thing we found.
11315     NamedDecl *Found = *Result.begin();
11316     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11317     return nullptr;
11318   }
11319 
11320   // We found some template called std::initializer_list. Now verify that it's
11321   // correct.
11322   TemplateParameterList *Params = Template->getTemplateParameters();
11323   if (Params->getMinRequiredArguments() != 1 ||
11324       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11325     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11326     return nullptr;
11327   }
11328 
11329   return Template;
11330 }
11331 
11332 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11333   if (!StdInitializerList) {
11334     StdInitializerList = LookupStdInitializerList(*this, Loc);
11335     if (!StdInitializerList)
11336       return QualType();
11337   }
11338 
11339   TemplateArgumentListInfo Args(Loc, Loc);
11340   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11341                                        Context.getTrivialTypeSourceInfo(Element,
11342                                                                         Loc)));
11343   return Context.getCanonicalType(
11344       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11345 }
11346 
11347 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11348   // C++ [dcl.init.list]p2:
11349   //   A constructor is an initializer-list constructor if its first parameter
11350   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11351   //   std::initializer_list<E> for some type E, and either there are no other
11352   //   parameters or else all other parameters have default arguments.
11353   if (!Ctor->hasOneParamOrDefaultArgs())
11354     return false;
11355 
11356   QualType ArgType = Ctor->getParamDecl(0)->getType();
11357   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11358     ArgType = RT->getPointeeType().getUnqualifiedType();
11359 
11360   return isStdInitializerList(ArgType, nullptr);
11361 }
11362 
11363 /// Determine whether a using statement is in a context where it will be
11364 /// apply in all contexts.
11365 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11366   switch (CurContext->getDeclKind()) {
11367     case Decl::TranslationUnit:
11368       return true;
11369     case Decl::LinkageSpec:
11370       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11371     default:
11372       return false;
11373   }
11374 }
11375 
11376 namespace {
11377 
11378 // Callback to only accept typo corrections that are namespaces.
11379 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11380 public:
11381   bool ValidateCandidate(const TypoCorrection &candidate) override {
11382     if (NamedDecl *ND = candidate.getCorrectionDecl())
11383       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11384     return false;
11385   }
11386 
11387   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11388     return std::make_unique<NamespaceValidatorCCC>(*this);
11389   }
11390 };
11391 
11392 }
11393 
11394 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11395                                        CXXScopeSpec &SS,
11396                                        SourceLocation IdentLoc,
11397                                        IdentifierInfo *Ident) {
11398   R.clear();
11399   NamespaceValidatorCCC CCC{};
11400   if (TypoCorrection Corrected =
11401           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11402                         Sema::CTK_ErrorRecovery)) {
11403     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11404       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11405       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11406                               Ident->getName().equals(CorrectedStr);
11407       S.diagnoseTypo(Corrected,
11408                      S.PDiag(diag::err_using_directive_member_suggest)
11409                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11410                      S.PDiag(diag::note_namespace_defined_here));
11411     } else {
11412       S.diagnoseTypo(Corrected,
11413                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11414                      S.PDiag(diag::note_namespace_defined_here));
11415     }
11416     R.addDecl(Corrected.getFoundDecl());
11417     return true;
11418   }
11419   return false;
11420 }
11421 
11422 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11423                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11424                                 SourceLocation IdentLoc,
11425                                 IdentifierInfo *NamespcName,
11426                                 const ParsedAttributesView &AttrList) {
11427   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11428   assert(NamespcName && "Invalid NamespcName.");
11429   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11430 
11431   // This can only happen along a recovery path.
11432   while (S->isTemplateParamScope())
11433     S = S->getParent();
11434   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11435 
11436   UsingDirectiveDecl *UDir = nullptr;
11437   NestedNameSpecifier *Qualifier = nullptr;
11438   if (SS.isSet())
11439     Qualifier = SS.getScopeRep();
11440 
11441   // Lookup namespace name.
11442   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11443   LookupParsedName(R, S, &SS);
11444   if (R.isAmbiguous())
11445     return nullptr;
11446 
11447   if (R.empty()) {
11448     R.clear();
11449     // Allow "using namespace std;" or "using namespace ::std;" even if
11450     // "std" hasn't been defined yet, for GCC compatibility.
11451     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11452         NamespcName->isStr("std")) {
11453       Diag(IdentLoc, diag::ext_using_undefined_std);
11454       R.addDecl(getOrCreateStdNamespace());
11455       R.resolveKind();
11456     }
11457     // Otherwise, attempt typo correction.
11458     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11459   }
11460 
11461   if (!R.empty()) {
11462     NamedDecl *Named = R.getRepresentativeDecl();
11463     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11464     assert(NS && "expected namespace decl");
11465 
11466     // The use of a nested name specifier may trigger deprecation warnings.
11467     DiagnoseUseOfDecl(Named, IdentLoc);
11468 
11469     // C++ [namespace.udir]p1:
11470     //   A using-directive specifies that the names in the nominated
11471     //   namespace can be used in the scope in which the
11472     //   using-directive appears after the using-directive. During
11473     //   unqualified name lookup (3.4.1), the names appear as if they
11474     //   were declared in the nearest enclosing namespace which
11475     //   contains both the using-directive and the nominated
11476     //   namespace. [Note: in this context, "contains" means "contains
11477     //   directly or indirectly". ]
11478 
11479     // Find enclosing context containing both using-directive and
11480     // nominated namespace.
11481     DeclContext *CommonAncestor = NS;
11482     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11483       CommonAncestor = CommonAncestor->getParent();
11484 
11485     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11486                                       SS.getWithLocInContext(Context),
11487                                       IdentLoc, Named, CommonAncestor);
11488 
11489     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11490         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11491       Diag(IdentLoc, diag::warn_using_directive_in_header);
11492     }
11493 
11494     PushUsingDirective(S, UDir);
11495   } else {
11496     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11497   }
11498 
11499   if (UDir)
11500     ProcessDeclAttributeList(S, UDir, AttrList);
11501 
11502   return UDir;
11503 }
11504 
11505 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11506   // If the scope has an associated entity and the using directive is at
11507   // namespace or translation unit scope, add the UsingDirectiveDecl into
11508   // its lookup structure so qualified name lookup can find it.
11509   DeclContext *Ctx = S->getEntity();
11510   if (Ctx && !Ctx->isFunctionOrMethod())
11511     Ctx->addDecl(UDir);
11512   else
11513     // Otherwise, it is at block scope. The using-directives will affect lookup
11514     // only to the end of the scope.
11515     S->PushUsingDirective(UDir);
11516 }
11517 
11518 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11519                                   SourceLocation UsingLoc,
11520                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11521                                   UnqualifiedId &Name,
11522                                   SourceLocation EllipsisLoc,
11523                                   const ParsedAttributesView &AttrList) {
11524   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11525 
11526   if (SS.isEmpty()) {
11527     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11528     return nullptr;
11529   }
11530 
11531   switch (Name.getKind()) {
11532   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11533   case UnqualifiedIdKind::IK_Identifier:
11534   case UnqualifiedIdKind::IK_OperatorFunctionId:
11535   case UnqualifiedIdKind::IK_LiteralOperatorId:
11536   case UnqualifiedIdKind::IK_ConversionFunctionId:
11537     break;
11538 
11539   case UnqualifiedIdKind::IK_ConstructorName:
11540   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11541     // C++11 inheriting constructors.
11542     Diag(Name.getBeginLoc(),
11543          getLangOpts().CPlusPlus11
11544              ? diag::warn_cxx98_compat_using_decl_constructor
11545              : diag::err_using_decl_constructor)
11546         << SS.getRange();
11547 
11548     if (getLangOpts().CPlusPlus11) break;
11549 
11550     return nullptr;
11551 
11552   case UnqualifiedIdKind::IK_DestructorName:
11553     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11554     return nullptr;
11555 
11556   case UnqualifiedIdKind::IK_TemplateId:
11557     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11558         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11559     return nullptr;
11560 
11561   case UnqualifiedIdKind::IK_DeductionGuideName:
11562     llvm_unreachable("cannot parse qualified deduction guide name");
11563   }
11564 
11565   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11566   DeclarationName TargetName = TargetNameInfo.getName();
11567   if (!TargetName)
11568     return nullptr;
11569 
11570   // Warn about access declarations.
11571   if (UsingLoc.isInvalid()) {
11572     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11573                                  ? diag::err_access_decl
11574                                  : diag::warn_access_decl_deprecated)
11575         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11576   }
11577 
11578   if (EllipsisLoc.isInvalid()) {
11579     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11580         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11581       return nullptr;
11582   } else {
11583     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11584         !TargetNameInfo.containsUnexpandedParameterPack()) {
11585       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11586         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11587       EllipsisLoc = SourceLocation();
11588     }
11589   }
11590 
11591   NamedDecl *UD =
11592       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11593                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11594                             /*IsInstantiation*/false);
11595   if (UD)
11596     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11597 
11598   return UD;
11599 }
11600 
11601 /// Determine whether a using declaration considers the given
11602 /// declarations as "equivalent", e.g., if they are redeclarations of
11603 /// the same entity or are both typedefs of the same type.
11604 static bool
11605 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11606   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11607     return true;
11608 
11609   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11610     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11611       return Context.hasSameType(TD1->getUnderlyingType(),
11612                                  TD2->getUnderlyingType());
11613 
11614   return false;
11615 }
11616 
11617 
11618 /// Determines whether to create a using shadow decl for a particular
11619 /// decl, given the set of decls existing prior to this using lookup.
11620 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11621                                 const LookupResult &Previous,
11622                                 UsingShadowDecl *&PrevShadow) {
11623   // Diagnose finding a decl which is not from a base class of the
11624   // current class.  We do this now because there are cases where this
11625   // function will silently decide not to build a shadow decl, which
11626   // will pre-empt further diagnostics.
11627   //
11628   // We don't need to do this in C++11 because we do the check once on
11629   // the qualifier.
11630   //
11631   // FIXME: diagnose the following if we care enough:
11632   //   struct A { int foo; };
11633   //   struct B : A { using A::foo; };
11634   //   template <class T> struct C : A {};
11635   //   template <class T> struct D : C<T> { using B::foo; } // <---
11636   // This is invalid (during instantiation) in C++03 because B::foo
11637   // resolves to the using decl in B, which is not a base class of D<T>.
11638   // We can't diagnose it immediately because C<T> is an unknown
11639   // specialization.  The UsingShadowDecl in D<T> then points directly
11640   // to A::foo, which will look well-formed when we instantiate.
11641   // The right solution is to not collapse the shadow-decl chain.
11642   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11643     DeclContext *OrigDC = Orig->getDeclContext();
11644 
11645     // Handle enums and anonymous structs.
11646     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11647     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11648     while (OrigRec->isAnonymousStructOrUnion())
11649       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11650 
11651     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11652       if (OrigDC == CurContext) {
11653         Diag(Using->getLocation(),
11654              diag::err_using_decl_nested_name_specifier_is_current_class)
11655           << Using->getQualifierLoc().getSourceRange();
11656         Diag(Orig->getLocation(), diag::note_using_decl_target);
11657         Using->setInvalidDecl();
11658         return true;
11659       }
11660 
11661       Diag(Using->getQualifierLoc().getBeginLoc(),
11662            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11663         << Using->getQualifier()
11664         << cast<CXXRecordDecl>(CurContext)
11665         << Using->getQualifierLoc().getSourceRange();
11666       Diag(Orig->getLocation(), diag::note_using_decl_target);
11667       Using->setInvalidDecl();
11668       return true;
11669     }
11670   }
11671 
11672   if (Previous.empty()) return false;
11673 
11674   NamedDecl *Target = Orig;
11675   if (isa<UsingShadowDecl>(Target))
11676     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11677 
11678   // If the target happens to be one of the previous declarations, we
11679   // don't have a conflict.
11680   //
11681   // FIXME: but we might be increasing its access, in which case we
11682   // should redeclare it.
11683   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11684   bool FoundEquivalentDecl = false;
11685   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11686          I != E; ++I) {
11687     NamedDecl *D = (*I)->getUnderlyingDecl();
11688     // We can have UsingDecls in our Previous results because we use the same
11689     // LookupResult for checking whether the UsingDecl itself is a valid
11690     // redeclaration.
11691     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11692       continue;
11693 
11694     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11695       // C++ [class.mem]p19:
11696       //   If T is the name of a class, then [every named member other than
11697       //   a non-static data member] shall have a name different from T
11698       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11699           !isa<IndirectFieldDecl>(Target) &&
11700           !isa<UnresolvedUsingValueDecl>(Target) &&
11701           DiagnoseClassNameShadow(
11702               CurContext,
11703               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11704         return true;
11705     }
11706 
11707     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11708       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11709         PrevShadow = Shadow;
11710       FoundEquivalentDecl = true;
11711     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11712       // We don't conflict with an existing using shadow decl of an equivalent
11713       // declaration, but we're not a redeclaration of it.
11714       FoundEquivalentDecl = true;
11715     }
11716 
11717     if (isVisible(D))
11718       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11719   }
11720 
11721   if (FoundEquivalentDecl)
11722     return false;
11723 
11724   if (FunctionDecl *FD = Target->getAsFunction()) {
11725     NamedDecl *OldDecl = nullptr;
11726     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11727                           /*IsForUsingDecl*/ true)) {
11728     case Ovl_Overload:
11729       return false;
11730 
11731     case Ovl_NonFunction:
11732       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11733       break;
11734 
11735     // We found a decl with the exact signature.
11736     case Ovl_Match:
11737       // If we're in a record, we want to hide the target, so we
11738       // return true (without a diagnostic) to tell the caller not to
11739       // build a shadow decl.
11740       if (CurContext->isRecord())
11741         return true;
11742 
11743       // If we're not in a record, this is an error.
11744       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11745       break;
11746     }
11747 
11748     Diag(Target->getLocation(), diag::note_using_decl_target);
11749     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11750     Using->setInvalidDecl();
11751     return true;
11752   }
11753 
11754   // Target is not a function.
11755 
11756   if (isa<TagDecl>(Target)) {
11757     // No conflict between a tag and a non-tag.
11758     if (!Tag) return false;
11759 
11760     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11761     Diag(Target->getLocation(), diag::note_using_decl_target);
11762     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11763     Using->setInvalidDecl();
11764     return true;
11765   }
11766 
11767   // No conflict between a tag and a non-tag.
11768   if (!NonTag) return false;
11769 
11770   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11771   Diag(Target->getLocation(), diag::note_using_decl_target);
11772   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11773   Using->setInvalidDecl();
11774   return true;
11775 }
11776 
11777 /// Determine whether a direct base class is a virtual base class.
11778 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11779   if (!Derived->getNumVBases())
11780     return false;
11781   for (auto &B : Derived->bases())
11782     if (B.getType()->getAsCXXRecordDecl() == Base)
11783       return B.isVirtual();
11784   llvm_unreachable("not a direct base class");
11785 }
11786 
11787 /// Builds a shadow declaration corresponding to a 'using' declaration.
11788 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11789                                             UsingDecl *UD,
11790                                             NamedDecl *Orig,
11791                                             UsingShadowDecl *PrevDecl) {
11792   // If we resolved to another shadow declaration, just coalesce them.
11793   NamedDecl *Target = Orig;
11794   if (isa<UsingShadowDecl>(Target)) {
11795     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11796     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11797   }
11798 
11799   NamedDecl *NonTemplateTarget = Target;
11800   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11801     NonTemplateTarget = TargetTD->getTemplatedDecl();
11802 
11803   UsingShadowDecl *Shadow;
11804   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11805     bool IsVirtualBase =
11806         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11807                             UD->getQualifier()->getAsRecordDecl());
11808     Shadow = ConstructorUsingShadowDecl::Create(
11809         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11810   } else {
11811     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11812                                      Target);
11813   }
11814   UD->addShadowDecl(Shadow);
11815 
11816   Shadow->setAccess(UD->getAccess());
11817   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11818     Shadow->setInvalidDecl();
11819 
11820   Shadow->setPreviousDecl(PrevDecl);
11821 
11822   if (S)
11823     PushOnScopeChains(Shadow, S);
11824   else
11825     CurContext->addDecl(Shadow);
11826 
11827 
11828   return Shadow;
11829 }
11830 
11831 /// Hides a using shadow declaration.  This is required by the current
11832 /// using-decl implementation when a resolvable using declaration in a
11833 /// class is followed by a declaration which would hide or override
11834 /// one or more of the using decl's targets; for example:
11835 ///
11836 ///   struct Base { void foo(int); };
11837 ///   struct Derived : Base {
11838 ///     using Base::foo;
11839 ///     void foo(int);
11840 ///   };
11841 ///
11842 /// The governing language is C++03 [namespace.udecl]p12:
11843 ///
11844 ///   When a using-declaration brings names from a base class into a
11845 ///   derived class scope, member functions in the derived class
11846 ///   override and/or hide member functions with the same name and
11847 ///   parameter types in a base class (rather than conflicting).
11848 ///
11849 /// There are two ways to implement this:
11850 ///   (1) optimistically create shadow decls when they're not hidden
11851 ///       by existing declarations, or
11852 ///   (2) don't create any shadow decls (or at least don't make them
11853 ///       visible) until we've fully parsed/instantiated the class.
11854 /// The problem with (1) is that we might have to retroactively remove
11855 /// a shadow decl, which requires several O(n) operations because the
11856 /// decl structures are (very reasonably) not designed for removal.
11857 /// (2) avoids this but is very fiddly and phase-dependent.
11858 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11859   if (Shadow->getDeclName().getNameKind() ==
11860         DeclarationName::CXXConversionFunctionName)
11861     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11862 
11863   // Remove it from the DeclContext...
11864   Shadow->getDeclContext()->removeDecl(Shadow);
11865 
11866   // ...and the scope, if applicable...
11867   if (S) {
11868     S->RemoveDecl(Shadow);
11869     IdResolver.RemoveDecl(Shadow);
11870   }
11871 
11872   // ...and the using decl.
11873   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11874 
11875   // TODO: complain somehow if Shadow was used.  It shouldn't
11876   // be possible for this to happen, because...?
11877 }
11878 
11879 /// Find the base specifier for a base class with the given type.
11880 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11881                                                 QualType DesiredBase,
11882                                                 bool &AnyDependentBases) {
11883   // Check whether the named type is a direct base class.
11884   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11885     .getUnqualifiedType();
11886   for (auto &Base : Derived->bases()) {
11887     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11888     if (CanonicalDesiredBase == BaseType)
11889       return &Base;
11890     if (BaseType->isDependentType())
11891       AnyDependentBases = true;
11892   }
11893   return nullptr;
11894 }
11895 
11896 namespace {
11897 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11898 public:
11899   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11900                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11901       : HasTypenameKeyword(HasTypenameKeyword),
11902         IsInstantiation(IsInstantiation), OldNNS(NNS),
11903         RequireMemberOf(RequireMemberOf) {}
11904 
11905   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11906     NamedDecl *ND = Candidate.getCorrectionDecl();
11907 
11908     // Keywords are not valid here.
11909     if (!ND || isa<NamespaceDecl>(ND))
11910       return false;
11911 
11912     // Completely unqualified names are invalid for a 'using' declaration.
11913     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11914       return false;
11915 
11916     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11917     // reject.
11918 
11919     if (RequireMemberOf) {
11920       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11921       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11922         // No-one ever wants a using-declaration to name an injected-class-name
11923         // of a base class, unless they're declaring an inheriting constructor.
11924         ASTContext &Ctx = ND->getASTContext();
11925         if (!Ctx.getLangOpts().CPlusPlus11)
11926           return false;
11927         QualType FoundType = Ctx.getRecordType(FoundRecord);
11928 
11929         // Check that the injected-class-name is named as a member of its own
11930         // type; we don't want to suggest 'using Derived::Base;', since that
11931         // means something else.
11932         NestedNameSpecifier *Specifier =
11933             Candidate.WillReplaceSpecifier()
11934                 ? Candidate.getCorrectionSpecifier()
11935                 : OldNNS;
11936         if (!Specifier->getAsType() ||
11937             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11938           return false;
11939 
11940         // Check that this inheriting constructor declaration actually names a
11941         // direct base class of the current class.
11942         bool AnyDependentBases = false;
11943         if (!findDirectBaseWithType(RequireMemberOf,
11944                                     Ctx.getRecordType(FoundRecord),
11945                                     AnyDependentBases) &&
11946             !AnyDependentBases)
11947           return false;
11948       } else {
11949         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11950         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11951           return false;
11952 
11953         // FIXME: Check that the base class member is accessible?
11954       }
11955     } else {
11956       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11957       if (FoundRecord && FoundRecord->isInjectedClassName())
11958         return false;
11959     }
11960 
11961     if (isa<TypeDecl>(ND))
11962       return HasTypenameKeyword || !IsInstantiation;
11963 
11964     return !HasTypenameKeyword;
11965   }
11966 
11967   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11968     return std::make_unique<UsingValidatorCCC>(*this);
11969   }
11970 
11971 private:
11972   bool HasTypenameKeyword;
11973   bool IsInstantiation;
11974   NestedNameSpecifier *OldNNS;
11975   CXXRecordDecl *RequireMemberOf;
11976 };
11977 } // end anonymous namespace
11978 
11979 /// Builds a using declaration.
11980 ///
11981 /// \param IsInstantiation - Whether this call arises from an
11982 ///   instantiation of an unresolved using declaration.  We treat
11983 ///   the lookup differently for these declarations.
11984 NamedDecl *Sema::BuildUsingDeclaration(
11985     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11986     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11987     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11988     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11989   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11990   SourceLocation IdentLoc = NameInfo.getLoc();
11991   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11992 
11993   // FIXME: We ignore attributes for now.
11994 
11995   // For an inheriting constructor declaration, the name of the using
11996   // declaration is the name of a constructor in this class, not in the
11997   // base class.
11998   DeclarationNameInfo UsingName = NameInfo;
11999   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12000     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12001       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12002           Context.getCanonicalType(Context.getRecordType(RD))));
12003 
12004   // Do the redeclaration lookup in the current scope.
12005   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12006                         ForVisibleRedeclaration);
12007   Previous.setHideTags(false);
12008   if (S) {
12009     LookupName(Previous, S);
12010 
12011     // It is really dumb that we have to do this.
12012     LookupResult::Filter F = Previous.makeFilter();
12013     while (F.hasNext()) {
12014       NamedDecl *D = F.next();
12015       if (!isDeclInScope(D, CurContext, S))
12016         F.erase();
12017       // If we found a local extern declaration that's not ordinarily visible,
12018       // and this declaration is being added to a non-block scope, ignore it.
12019       // We're only checking for scope conflicts here, not also for violations
12020       // of the linkage rules.
12021       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12022                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12023         F.erase();
12024     }
12025     F.done();
12026   } else {
12027     assert(IsInstantiation && "no scope in non-instantiation");
12028     if (CurContext->isRecord())
12029       LookupQualifiedName(Previous, CurContext);
12030     else {
12031       // No redeclaration check is needed here; in non-member contexts we
12032       // diagnosed all possible conflicts with other using-declarations when
12033       // building the template:
12034       //
12035       // For a dependent non-type using declaration, the only valid case is
12036       // if we instantiate to a single enumerator. We check for conflicts
12037       // between shadow declarations we introduce, and we check in the template
12038       // definition for conflicts between a non-type using declaration and any
12039       // other declaration, which together covers all cases.
12040       //
12041       // A dependent typename using declaration will never successfully
12042       // instantiate, since it will always name a class member, so we reject
12043       // that in the template definition.
12044     }
12045   }
12046 
12047   // Check for invalid redeclarations.
12048   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12049                                   SS, IdentLoc, Previous))
12050     return nullptr;
12051 
12052   // Check for bad qualifiers.
12053   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12054                               IdentLoc))
12055     return nullptr;
12056 
12057   DeclContext *LookupContext = computeDeclContext(SS);
12058   NamedDecl *D;
12059   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12060   if (!LookupContext || EllipsisLoc.isValid()) {
12061     if (HasTypenameKeyword) {
12062       // FIXME: not all declaration name kinds are legal here
12063       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12064                                               UsingLoc, TypenameLoc,
12065                                               QualifierLoc,
12066                                               IdentLoc, NameInfo.getName(),
12067                                               EllipsisLoc);
12068     } else {
12069       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12070                                            QualifierLoc, NameInfo, EllipsisLoc);
12071     }
12072     D->setAccess(AS);
12073     CurContext->addDecl(D);
12074     return D;
12075   }
12076 
12077   auto Build = [&](bool Invalid) {
12078     UsingDecl *UD =
12079         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12080                           UsingName, HasTypenameKeyword);
12081     UD->setAccess(AS);
12082     CurContext->addDecl(UD);
12083     UD->setInvalidDecl(Invalid);
12084     return UD;
12085   };
12086   auto BuildInvalid = [&]{ return Build(true); };
12087   auto BuildValid = [&]{ return Build(false); };
12088 
12089   if (RequireCompleteDeclContext(SS, LookupContext))
12090     return BuildInvalid();
12091 
12092   // Look up the target name.
12093   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12094 
12095   // Unlike most lookups, we don't always want to hide tag
12096   // declarations: tag names are visible through the using declaration
12097   // even if hidden by ordinary names, *except* in a dependent context
12098   // where it's important for the sanity of two-phase lookup.
12099   if (!IsInstantiation)
12100     R.setHideTags(false);
12101 
12102   // For the purposes of this lookup, we have a base object type
12103   // equal to that of the current context.
12104   if (CurContext->isRecord()) {
12105     R.setBaseObjectType(
12106                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12107   }
12108 
12109   LookupQualifiedName(R, LookupContext);
12110 
12111   // Try to correct typos if possible. If constructor name lookup finds no
12112   // results, that means the named class has no explicit constructors, and we
12113   // suppressed declaring implicit ones (probably because it's dependent or
12114   // invalid).
12115   if (R.empty() &&
12116       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12117     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12118     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12119     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12120     auto *II = NameInfo.getName().getAsIdentifierInfo();
12121     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12122         CurContext->isStdNamespace() &&
12123         isa<TranslationUnitDecl>(LookupContext) &&
12124         getSourceManager().isInSystemHeader(UsingLoc))
12125       return nullptr;
12126     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12127                           dyn_cast<CXXRecordDecl>(CurContext));
12128     if (TypoCorrection Corrected =
12129             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12130                         CTK_ErrorRecovery)) {
12131       // We reject candidates where DroppedSpecifier == true, hence the
12132       // literal '0' below.
12133       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12134                                 << NameInfo.getName() << LookupContext << 0
12135                                 << SS.getRange());
12136 
12137       // If we picked a correction with no attached Decl we can't do anything
12138       // useful with it, bail out.
12139       NamedDecl *ND = Corrected.getCorrectionDecl();
12140       if (!ND)
12141         return BuildInvalid();
12142 
12143       // If we corrected to an inheriting constructor, handle it as one.
12144       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12145       if (RD && RD->isInjectedClassName()) {
12146         // The parent of the injected class name is the class itself.
12147         RD = cast<CXXRecordDecl>(RD->getParent());
12148 
12149         // Fix up the information we'll use to build the using declaration.
12150         if (Corrected.WillReplaceSpecifier()) {
12151           NestedNameSpecifierLocBuilder Builder;
12152           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12153                               QualifierLoc.getSourceRange());
12154           QualifierLoc = Builder.getWithLocInContext(Context);
12155         }
12156 
12157         // In this case, the name we introduce is the name of a derived class
12158         // constructor.
12159         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12160         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12161             Context.getCanonicalType(Context.getRecordType(CurClass))));
12162         UsingName.setNamedTypeInfo(nullptr);
12163         for (auto *Ctor : LookupConstructors(RD))
12164           R.addDecl(Ctor);
12165         R.resolveKind();
12166       } else {
12167         // FIXME: Pick up all the declarations if we found an overloaded
12168         // function.
12169         UsingName.setName(ND->getDeclName());
12170         R.addDecl(ND);
12171       }
12172     } else {
12173       Diag(IdentLoc, diag::err_no_member)
12174         << NameInfo.getName() << LookupContext << SS.getRange();
12175       return BuildInvalid();
12176     }
12177   }
12178 
12179   if (R.isAmbiguous())
12180     return BuildInvalid();
12181 
12182   if (HasTypenameKeyword) {
12183     // If we asked for a typename and got a non-type decl, error out.
12184     if (!R.getAsSingle<TypeDecl>()) {
12185       Diag(IdentLoc, diag::err_using_typename_non_type);
12186       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12187         Diag((*I)->getUnderlyingDecl()->getLocation(),
12188              diag::note_using_decl_target);
12189       return BuildInvalid();
12190     }
12191   } else {
12192     // If we asked for a non-typename and we got a type, error out,
12193     // but only if this is an instantiation of an unresolved using
12194     // decl.  Otherwise just silently find the type name.
12195     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12196       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12197       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12198       return BuildInvalid();
12199     }
12200   }
12201 
12202   // C++14 [namespace.udecl]p6:
12203   // A using-declaration shall not name a namespace.
12204   if (R.getAsSingle<NamespaceDecl>()) {
12205     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12206       << SS.getRange();
12207     return BuildInvalid();
12208   }
12209 
12210   // C++14 [namespace.udecl]p7:
12211   // A using-declaration shall not name a scoped enumerator.
12212   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12213     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12214       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12215         << SS.getRange();
12216       return BuildInvalid();
12217     }
12218   }
12219 
12220   UsingDecl *UD = BuildValid();
12221 
12222   // Some additional rules apply to inheriting constructors.
12223   if (UsingName.getName().getNameKind() ==
12224         DeclarationName::CXXConstructorName) {
12225     // Suppress access diagnostics; the access check is instead performed at the
12226     // point of use for an inheriting constructor.
12227     R.suppressDiagnostics();
12228     if (CheckInheritingConstructorUsingDecl(UD))
12229       return UD;
12230   }
12231 
12232   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12233     UsingShadowDecl *PrevDecl = nullptr;
12234     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12235       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12236   }
12237 
12238   return UD;
12239 }
12240 
12241 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12242                                     ArrayRef<NamedDecl *> Expansions) {
12243   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12244          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12245          isa<UsingPackDecl>(InstantiatedFrom));
12246 
12247   auto *UPD =
12248       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12249   UPD->setAccess(InstantiatedFrom->getAccess());
12250   CurContext->addDecl(UPD);
12251   return UPD;
12252 }
12253 
12254 /// Additional checks for a using declaration referring to a constructor name.
12255 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12256   assert(!UD->hasTypename() && "expecting a constructor name");
12257 
12258   const Type *SourceType = UD->getQualifier()->getAsType();
12259   assert(SourceType &&
12260          "Using decl naming constructor doesn't have type in scope spec.");
12261   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12262 
12263   // Check whether the named type is a direct base class.
12264   bool AnyDependentBases = false;
12265   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12266                                       AnyDependentBases);
12267   if (!Base && !AnyDependentBases) {
12268     Diag(UD->getUsingLoc(),
12269          diag::err_using_decl_constructor_not_in_direct_base)
12270       << UD->getNameInfo().getSourceRange()
12271       << QualType(SourceType, 0) << TargetClass;
12272     UD->setInvalidDecl();
12273     return true;
12274   }
12275 
12276   if (Base)
12277     Base->setInheritConstructors();
12278 
12279   return false;
12280 }
12281 
12282 /// Checks that the given using declaration is not an invalid
12283 /// redeclaration.  Note that this is checking only for the using decl
12284 /// itself, not for any ill-formedness among the UsingShadowDecls.
12285 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12286                                        bool HasTypenameKeyword,
12287                                        const CXXScopeSpec &SS,
12288                                        SourceLocation NameLoc,
12289                                        const LookupResult &Prev) {
12290   NestedNameSpecifier *Qual = SS.getScopeRep();
12291 
12292   // C++03 [namespace.udecl]p8:
12293   // C++0x [namespace.udecl]p10:
12294   //   A using-declaration is a declaration and can therefore be used
12295   //   repeatedly where (and only where) multiple declarations are
12296   //   allowed.
12297   //
12298   // That's in non-member contexts.
12299   if (!CurContext->getRedeclContext()->isRecord()) {
12300     // A dependent qualifier outside a class can only ever resolve to an
12301     // enumeration type. Therefore it conflicts with any other non-type
12302     // declaration in the same scope.
12303     // FIXME: How should we check for dependent type-type conflicts at block
12304     // scope?
12305     if (Qual->isDependent() && !HasTypenameKeyword) {
12306       for (auto *D : Prev) {
12307         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12308           bool OldCouldBeEnumerator =
12309               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12310           Diag(NameLoc,
12311                OldCouldBeEnumerator ? diag::err_redefinition
12312                                     : diag::err_redefinition_different_kind)
12313               << Prev.getLookupName();
12314           Diag(D->getLocation(), diag::note_previous_definition);
12315           return true;
12316         }
12317       }
12318     }
12319     return false;
12320   }
12321 
12322   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12323     NamedDecl *D = *I;
12324 
12325     bool DTypename;
12326     NestedNameSpecifier *DQual;
12327     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12328       DTypename = UD->hasTypename();
12329       DQual = UD->getQualifier();
12330     } else if (UnresolvedUsingValueDecl *UD
12331                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12332       DTypename = false;
12333       DQual = UD->getQualifier();
12334     } else if (UnresolvedUsingTypenameDecl *UD
12335                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12336       DTypename = true;
12337       DQual = UD->getQualifier();
12338     } else continue;
12339 
12340     // using decls differ if one says 'typename' and the other doesn't.
12341     // FIXME: non-dependent using decls?
12342     if (HasTypenameKeyword != DTypename) continue;
12343 
12344     // using decls differ if they name different scopes (but note that
12345     // template instantiation can cause this check to trigger when it
12346     // didn't before instantiation).
12347     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12348         Context.getCanonicalNestedNameSpecifier(DQual))
12349       continue;
12350 
12351     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12352     Diag(D->getLocation(), diag::note_using_decl) << 1;
12353     return true;
12354   }
12355 
12356   return false;
12357 }
12358 
12359 
12360 /// Checks that the given nested-name qualifier used in a using decl
12361 /// in the current context is appropriately related to the current
12362 /// scope.  If an error is found, diagnoses it and returns true.
12363 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12364                                    bool HasTypename,
12365                                    const CXXScopeSpec &SS,
12366                                    const DeclarationNameInfo &NameInfo,
12367                                    SourceLocation NameLoc) {
12368   DeclContext *NamedContext = computeDeclContext(SS);
12369 
12370   if (!CurContext->isRecord()) {
12371     // C++03 [namespace.udecl]p3:
12372     // C++0x [namespace.udecl]p8:
12373     //   A using-declaration for a class member shall be a member-declaration.
12374 
12375     // If we weren't able to compute a valid scope, it might validly be a
12376     // dependent class scope or a dependent enumeration unscoped scope. If
12377     // we have a 'typename' keyword, the scope must resolve to a class type.
12378     if ((HasTypename && !NamedContext) ||
12379         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12380       auto *RD = NamedContext
12381                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12382                      : nullptr;
12383       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12384         RD = nullptr;
12385 
12386       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12387         << SS.getRange();
12388 
12389       // If we have a complete, non-dependent source type, try to suggest a
12390       // way to get the same effect.
12391       if (!RD)
12392         return true;
12393 
12394       // Find what this using-declaration was referring to.
12395       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12396       R.setHideTags(false);
12397       R.suppressDiagnostics();
12398       LookupQualifiedName(R, RD);
12399 
12400       if (R.getAsSingle<TypeDecl>()) {
12401         if (getLangOpts().CPlusPlus11) {
12402           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12403           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12404             << 0 // alias declaration
12405             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12406                                           NameInfo.getName().getAsString() +
12407                                               " = ");
12408         } else {
12409           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12410           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12411           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12412             << 1 // typedef declaration
12413             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12414             << FixItHint::CreateInsertion(
12415                    InsertLoc, " " + NameInfo.getName().getAsString());
12416         }
12417       } else if (R.getAsSingle<VarDecl>()) {
12418         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12419         // repeating the type of the static data member here.
12420         FixItHint FixIt;
12421         if (getLangOpts().CPlusPlus11) {
12422           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12423           FixIt = FixItHint::CreateReplacement(
12424               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12425         }
12426 
12427         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12428           << 2 // reference declaration
12429           << FixIt;
12430       } else if (R.getAsSingle<EnumConstantDecl>()) {
12431         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12432         // repeating the type of the enumeration here, and we can't do so if
12433         // the type is anonymous.
12434         FixItHint FixIt;
12435         if (getLangOpts().CPlusPlus11) {
12436           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12437           FixIt = FixItHint::CreateReplacement(
12438               UsingLoc,
12439               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12440         }
12441 
12442         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12443           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12444           << FixIt;
12445       }
12446       return true;
12447     }
12448 
12449     // Otherwise, this might be valid.
12450     return false;
12451   }
12452 
12453   // The current scope is a record.
12454 
12455   // If the named context is dependent, we can't decide much.
12456   if (!NamedContext) {
12457     // FIXME: in C++0x, we can diagnose if we can prove that the
12458     // nested-name-specifier does not refer to a base class, which is
12459     // still possible in some cases.
12460 
12461     // Otherwise we have to conservatively report that things might be
12462     // okay.
12463     return false;
12464   }
12465 
12466   if (!NamedContext->isRecord()) {
12467     // Ideally this would point at the last name in the specifier,
12468     // but we don't have that level of source info.
12469     Diag(SS.getRange().getBegin(),
12470          diag::err_using_decl_nested_name_specifier_is_not_class)
12471       << SS.getScopeRep() << SS.getRange();
12472     return true;
12473   }
12474 
12475   if (!NamedContext->isDependentContext() &&
12476       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12477     return true;
12478 
12479   if (getLangOpts().CPlusPlus11) {
12480     // C++11 [namespace.udecl]p3:
12481     //   In a using-declaration used as a member-declaration, the
12482     //   nested-name-specifier shall name a base class of the class
12483     //   being defined.
12484 
12485     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12486                                  cast<CXXRecordDecl>(NamedContext))) {
12487       if (CurContext == NamedContext) {
12488         Diag(NameLoc,
12489              diag::err_using_decl_nested_name_specifier_is_current_class)
12490           << SS.getRange();
12491         return true;
12492       }
12493 
12494       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12495         Diag(SS.getRange().getBegin(),
12496              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12497           << SS.getScopeRep()
12498           << cast<CXXRecordDecl>(CurContext)
12499           << SS.getRange();
12500       }
12501       return true;
12502     }
12503 
12504     return false;
12505   }
12506 
12507   // C++03 [namespace.udecl]p4:
12508   //   A using-declaration used as a member-declaration shall refer
12509   //   to a member of a base class of the class being defined [etc.].
12510 
12511   // Salient point: SS doesn't have to name a base class as long as
12512   // lookup only finds members from base classes.  Therefore we can
12513   // diagnose here only if we can prove that that can't happen,
12514   // i.e. if the class hierarchies provably don't intersect.
12515 
12516   // TODO: it would be nice if "definitely valid" results were cached
12517   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12518   // need to be repeated.
12519 
12520   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12521   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12522     Bases.insert(Base);
12523     return true;
12524   };
12525 
12526   // Collect all bases. Return false if we find a dependent base.
12527   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12528     return false;
12529 
12530   // Returns true if the base is dependent or is one of the accumulated base
12531   // classes.
12532   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12533     return !Bases.count(Base);
12534   };
12535 
12536   // Return false if the class has a dependent base or if it or one
12537   // of its bases is present in the base set of the current context.
12538   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12539       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12540     return false;
12541 
12542   Diag(SS.getRange().getBegin(),
12543        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12544     << SS.getScopeRep()
12545     << cast<CXXRecordDecl>(CurContext)
12546     << SS.getRange();
12547 
12548   return true;
12549 }
12550 
12551 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12552                                   MultiTemplateParamsArg TemplateParamLists,
12553                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12554                                   const ParsedAttributesView &AttrList,
12555                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12556   // Skip up to the relevant declaration scope.
12557   while (S->isTemplateParamScope())
12558     S = S->getParent();
12559   assert((S->getFlags() & Scope::DeclScope) &&
12560          "got alias-declaration outside of declaration scope");
12561 
12562   if (Type.isInvalid())
12563     return nullptr;
12564 
12565   bool Invalid = false;
12566   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12567   TypeSourceInfo *TInfo = nullptr;
12568   GetTypeFromParser(Type.get(), &TInfo);
12569 
12570   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12571     return nullptr;
12572 
12573   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12574                                       UPPC_DeclarationType)) {
12575     Invalid = true;
12576     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12577                                              TInfo->getTypeLoc().getBeginLoc());
12578   }
12579 
12580   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12581                         TemplateParamLists.size()
12582                             ? forRedeclarationInCurContext()
12583                             : ForVisibleRedeclaration);
12584   LookupName(Previous, S);
12585 
12586   // Warn about shadowing the name of a template parameter.
12587   if (Previous.isSingleResult() &&
12588       Previous.getFoundDecl()->isTemplateParameter()) {
12589     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12590     Previous.clear();
12591   }
12592 
12593   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12594          "name in alias declaration must be an identifier");
12595   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12596                                                Name.StartLocation,
12597                                                Name.Identifier, TInfo);
12598 
12599   NewTD->setAccess(AS);
12600 
12601   if (Invalid)
12602     NewTD->setInvalidDecl();
12603 
12604   ProcessDeclAttributeList(S, NewTD, AttrList);
12605   AddPragmaAttributes(S, NewTD);
12606 
12607   CheckTypedefForVariablyModifiedType(S, NewTD);
12608   Invalid |= NewTD->isInvalidDecl();
12609 
12610   bool Redeclaration = false;
12611 
12612   NamedDecl *NewND;
12613   if (TemplateParamLists.size()) {
12614     TypeAliasTemplateDecl *OldDecl = nullptr;
12615     TemplateParameterList *OldTemplateParams = nullptr;
12616 
12617     if (TemplateParamLists.size() != 1) {
12618       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12619         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12620          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12621     }
12622     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12623 
12624     // Check that we can declare a template here.
12625     if (CheckTemplateDeclScope(S, TemplateParams))
12626       return nullptr;
12627 
12628     // Only consider previous declarations in the same scope.
12629     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12630                          /*ExplicitInstantiationOrSpecialization*/false);
12631     if (!Previous.empty()) {
12632       Redeclaration = true;
12633 
12634       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12635       if (!OldDecl && !Invalid) {
12636         Diag(UsingLoc, diag::err_redefinition_different_kind)
12637           << Name.Identifier;
12638 
12639         NamedDecl *OldD = Previous.getRepresentativeDecl();
12640         if (OldD->getLocation().isValid())
12641           Diag(OldD->getLocation(), diag::note_previous_definition);
12642 
12643         Invalid = true;
12644       }
12645 
12646       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12647         if (TemplateParameterListsAreEqual(TemplateParams,
12648                                            OldDecl->getTemplateParameters(),
12649                                            /*Complain=*/true,
12650                                            TPL_TemplateMatch))
12651           OldTemplateParams =
12652               OldDecl->getMostRecentDecl()->getTemplateParameters();
12653         else
12654           Invalid = true;
12655 
12656         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12657         if (!Invalid &&
12658             !Context.hasSameType(OldTD->getUnderlyingType(),
12659                                  NewTD->getUnderlyingType())) {
12660           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12661           // but we can't reasonably accept it.
12662           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12663             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12664           if (OldTD->getLocation().isValid())
12665             Diag(OldTD->getLocation(), diag::note_previous_definition);
12666           Invalid = true;
12667         }
12668       }
12669     }
12670 
12671     // Merge any previous default template arguments into our parameters,
12672     // and check the parameter list.
12673     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12674                                    TPC_TypeAliasTemplate))
12675       return nullptr;
12676 
12677     TypeAliasTemplateDecl *NewDecl =
12678       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12679                                     Name.Identifier, TemplateParams,
12680                                     NewTD);
12681     NewTD->setDescribedAliasTemplate(NewDecl);
12682 
12683     NewDecl->setAccess(AS);
12684 
12685     if (Invalid)
12686       NewDecl->setInvalidDecl();
12687     else if (OldDecl) {
12688       NewDecl->setPreviousDecl(OldDecl);
12689       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12690     }
12691 
12692     NewND = NewDecl;
12693   } else {
12694     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12695       setTagNameForLinkagePurposes(TD, NewTD);
12696       handleTagNumbering(TD, S);
12697     }
12698     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12699     NewND = NewTD;
12700   }
12701 
12702   PushOnScopeChains(NewND, S);
12703   ActOnDocumentableDecl(NewND);
12704   return NewND;
12705 }
12706 
12707 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12708                                    SourceLocation AliasLoc,
12709                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12710                                    SourceLocation IdentLoc,
12711                                    IdentifierInfo *Ident) {
12712 
12713   // Lookup the namespace name.
12714   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12715   LookupParsedName(R, S, &SS);
12716 
12717   if (R.isAmbiguous())
12718     return nullptr;
12719 
12720   if (R.empty()) {
12721     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12722       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12723       return nullptr;
12724     }
12725   }
12726   assert(!R.isAmbiguous() && !R.empty());
12727   NamedDecl *ND = R.getRepresentativeDecl();
12728 
12729   // Check if we have a previous declaration with the same name.
12730   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12731                      ForVisibleRedeclaration);
12732   LookupName(PrevR, S);
12733 
12734   // Check we're not shadowing a template parameter.
12735   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12736     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12737     PrevR.clear();
12738   }
12739 
12740   // Filter out any other lookup result from an enclosing scope.
12741   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12742                        /*AllowInlineNamespace*/false);
12743 
12744   // Find the previous declaration and check that we can redeclare it.
12745   NamespaceAliasDecl *Prev = nullptr;
12746   if (PrevR.isSingleResult()) {
12747     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12748     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12749       // We already have an alias with the same name that points to the same
12750       // namespace; check that it matches.
12751       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12752         Prev = AD;
12753       } else if (isVisible(PrevDecl)) {
12754         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12755           << Alias;
12756         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12757           << AD->getNamespace();
12758         return nullptr;
12759       }
12760     } else if (isVisible(PrevDecl)) {
12761       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12762                             ? diag::err_redefinition
12763                             : diag::err_redefinition_different_kind;
12764       Diag(AliasLoc, DiagID) << Alias;
12765       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12766       return nullptr;
12767     }
12768   }
12769 
12770   // The use of a nested name specifier may trigger deprecation warnings.
12771   DiagnoseUseOfDecl(ND, IdentLoc);
12772 
12773   NamespaceAliasDecl *AliasDecl =
12774     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12775                                Alias, SS.getWithLocInContext(Context),
12776                                IdentLoc, ND);
12777   if (Prev)
12778     AliasDecl->setPreviousDecl(Prev);
12779 
12780   PushOnScopeChains(AliasDecl, S);
12781   return AliasDecl;
12782 }
12783 
12784 namespace {
12785 struct SpecialMemberExceptionSpecInfo
12786     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12787   SourceLocation Loc;
12788   Sema::ImplicitExceptionSpecification ExceptSpec;
12789 
12790   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12791                                  Sema::CXXSpecialMember CSM,
12792                                  Sema::InheritedConstructorInfo *ICI,
12793                                  SourceLocation Loc)
12794       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12795 
12796   bool visitBase(CXXBaseSpecifier *Base);
12797   bool visitField(FieldDecl *FD);
12798 
12799   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12800                            unsigned Quals);
12801 
12802   void visitSubobjectCall(Subobject Subobj,
12803                           Sema::SpecialMemberOverloadResult SMOR);
12804 };
12805 }
12806 
12807 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12808   auto *RT = Base->getType()->getAs<RecordType>();
12809   if (!RT)
12810     return false;
12811 
12812   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12813   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12814   if (auto *BaseCtor = SMOR.getMethod()) {
12815     visitSubobjectCall(Base, BaseCtor);
12816     return false;
12817   }
12818 
12819   visitClassSubobject(BaseClass, Base, 0);
12820   return false;
12821 }
12822 
12823 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12824   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12825     Expr *E = FD->getInClassInitializer();
12826     if (!E)
12827       // FIXME: It's a little wasteful to build and throw away a
12828       // CXXDefaultInitExpr here.
12829       // FIXME: We should have a single context note pointing at Loc, and
12830       // this location should be MD->getLocation() instead, since that's
12831       // the location where we actually use the default init expression.
12832       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12833     if (E)
12834       ExceptSpec.CalledExpr(E);
12835   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12836                             ->getAs<RecordType>()) {
12837     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12838                         FD->getType().getCVRQualifiers());
12839   }
12840   return false;
12841 }
12842 
12843 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12844                                                          Subobject Subobj,
12845                                                          unsigned Quals) {
12846   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12847   bool IsMutable = Field && Field->isMutable();
12848   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12849 }
12850 
12851 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12852     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12853   // Note, if lookup fails, it doesn't matter what exception specification we
12854   // choose because the special member will be deleted.
12855   if (CXXMethodDecl *MD = SMOR.getMethod())
12856     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12857 }
12858 
12859 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12860   llvm::APSInt Result;
12861   ExprResult Converted = CheckConvertedConstantExpression(
12862       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12863   ExplicitSpec.setExpr(Converted.get());
12864   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12865     ExplicitSpec.setKind(Result.getBoolValue()
12866                              ? ExplicitSpecKind::ResolvedTrue
12867                              : ExplicitSpecKind::ResolvedFalse);
12868     return true;
12869   }
12870   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12871   return false;
12872 }
12873 
12874 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12875   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12876   if (!ExplicitExpr->isTypeDependent())
12877     tryResolveExplicitSpecifier(ES);
12878   return ES;
12879 }
12880 
12881 static Sema::ImplicitExceptionSpecification
12882 ComputeDefaultedSpecialMemberExceptionSpec(
12883     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12884     Sema::InheritedConstructorInfo *ICI) {
12885   ComputingExceptionSpec CES(S, MD, Loc);
12886 
12887   CXXRecordDecl *ClassDecl = MD->getParent();
12888 
12889   // C++ [except.spec]p14:
12890   //   An implicitly declared special member function (Clause 12) shall have an
12891   //   exception-specification. [...]
12892   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12893   if (ClassDecl->isInvalidDecl())
12894     return Info.ExceptSpec;
12895 
12896   // FIXME: If this diagnostic fires, we're probably missing a check for
12897   // attempting to resolve an exception specification before it's known
12898   // at a higher level.
12899   if (S.RequireCompleteType(MD->getLocation(),
12900                             S.Context.getRecordType(ClassDecl),
12901                             diag::err_exception_spec_incomplete_type))
12902     return Info.ExceptSpec;
12903 
12904   // C++1z [except.spec]p7:
12905   //   [Look for exceptions thrown by] a constructor selected [...] to
12906   //   initialize a potentially constructed subobject,
12907   // C++1z [except.spec]p8:
12908   //   The exception specification for an implicitly-declared destructor, or a
12909   //   destructor without a noexcept-specifier, is potentially-throwing if and
12910   //   only if any of the destructors for any of its potentially constructed
12911   //   subojects is potentially throwing.
12912   // FIXME: We respect the first rule but ignore the "potentially constructed"
12913   // in the second rule to resolve a core issue (no number yet) that would have
12914   // us reject:
12915   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12916   //   struct B : A {};
12917   //   struct C : B { void f(); };
12918   // ... due to giving B::~B() a non-throwing exception specification.
12919   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12920                                 : Info.VisitAllBases);
12921 
12922   return Info.ExceptSpec;
12923 }
12924 
12925 namespace {
12926 /// RAII object to register a special member as being currently declared.
12927 struct DeclaringSpecialMember {
12928   Sema &S;
12929   Sema::SpecialMemberDecl D;
12930   Sema::ContextRAII SavedContext;
12931   bool WasAlreadyBeingDeclared;
12932 
12933   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12934       : S(S), D(RD, CSM), SavedContext(S, RD) {
12935     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12936     if (WasAlreadyBeingDeclared)
12937       // This almost never happens, but if it does, ensure that our cache
12938       // doesn't contain a stale result.
12939       S.SpecialMemberCache.clear();
12940     else {
12941       // Register a note to be produced if we encounter an error while
12942       // declaring the special member.
12943       Sema::CodeSynthesisContext Ctx;
12944       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12945       // FIXME: We don't have a location to use here. Using the class's
12946       // location maintains the fiction that we declare all special members
12947       // with the class, but (1) it's not clear that lying about that helps our
12948       // users understand what's going on, and (2) there may be outer contexts
12949       // on the stack (some of which are relevant) and printing them exposes
12950       // our lies.
12951       Ctx.PointOfInstantiation = RD->getLocation();
12952       Ctx.Entity = RD;
12953       Ctx.SpecialMember = CSM;
12954       S.pushCodeSynthesisContext(Ctx);
12955     }
12956   }
12957   ~DeclaringSpecialMember() {
12958     if (!WasAlreadyBeingDeclared) {
12959       S.SpecialMembersBeingDeclared.erase(D);
12960       S.popCodeSynthesisContext();
12961     }
12962   }
12963 
12964   /// Are we already trying to declare this special member?
12965   bool isAlreadyBeingDeclared() const {
12966     return WasAlreadyBeingDeclared;
12967   }
12968 };
12969 }
12970 
12971 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12972   // Look up any existing declarations, but don't trigger declaration of all
12973   // implicit special members with this name.
12974   DeclarationName Name = FD->getDeclName();
12975   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12976                  ForExternalRedeclaration);
12977   for (auto *D : FD->getParent()->lookup(Name))
12978     if (auto *Acceptable = R.getAcceptableDecl(D))
12979       R.addDecl(Acceptable);
12980   R.resolveKind();
12981   R.suppressDiagnostics();
12982 
12983   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12984 }
12985 
12986 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12987                                           QualType ResultTy,
12988                                           ArrayRef<QualType> Args) {
12989   // Build an exception specification pointing back at this constructor.
12990   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12991 
12992   LangAS AS = getDefaultCXXMethodAddrSpace();
12993   if (AS != LangAS::Default) {
12994     EPI.TypeQuals.addAddressSpace(AS);
12995   }
12996 
12997   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12998   SpecialMem->setType(QT);
12999 }
13000 
13001 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13002                                                      CXXRecordDecl *ClassDecl) {
13003   // C++ [class.ctor]p5:
13004   //   A default constructor for a class X is a constructor of class X
13005   //   that can be called without an argument. If there is no
13006   //   user-declared constructor for class X, a default constructor is
13007   //   implicitly declared. An implicitly-declared default constructor
13008   //   is an inline public member of its class.
13009   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13010          "Should not build implicit default constructor!");
13011 
13012   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13013   if (DSM.isAlreadyBeingDeclared())
13014     return nullptr;
13015 
13016   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13017                                                      CXXDefaultConstructor,
13018                                                      false);
13019 
13020   // Create the actual constructor declaration.
13021   CanQualType ClassType
13022     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13023   SourceLocation ClassLoc = ClassDecl->getLocation();
13024   DeclarationName Name
13025     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13026   DeclarationNameInfo NameInfo(Name, ClassLoc);
13027   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13028       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13029       /*TInfo=*/nullptr, ExplicitSpecifier(),
13030       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13031       Constexpr ? ConstexprSpecKind::Constexpr
13032                 : ConstexprSpecKind::Unspecified);
13033   DefaultCon->setAccess(AS_public);
13034   DefaultCon->setDefaulted();
13035 
13036   if (getLangOpts().CUDA) {
13037     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13038                                             DefaultCon,
13039                                             /* ConstRHS */ false,
13040                                             /* Diagnose */ false);
13041   }
13042 
13043   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13044 
13045   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13046   // constructors is easy to compute.
13047   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13048 
13049   // Note that we have declared this constructor.
13050   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13051 
13052   Scope *S = getScopeForContext(ClassDecl);
13053   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13054 
13055   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13056     SetDeclDeleted(DefaultCon, ClassLoc);
13057 
13058   if (S)
13059     PushOnScopeChains(DefaultCon, S, false);
13060   ClassDecl->addDecl(DefaultCon);
13061 
13062   return DefaultCon;
13063 }
13064 
13065 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13066                                             CXXConstructorDecl *Constructor) {
13067   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13068           !Constructor->doesThisDeclarationHaveABody() &&
13069           !Constructor->isDeleted()) &&
13070     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13071   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13072     return;
13073 
13074   CXXRecordDecl *ClassDecl = Constructor->getParent();
13075   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13076 
13077   SynthesizedFunctionScope Scope(*this, Constructor);
13078 
13079   // The exception specification is needed because we are defining the
13080   // function.
13081   ResolveExceptionSpec(CurrentLocation,
13082                        Constructor->getType()->castAs<FunctionProtoType>());
13083   MarkVTableUsed(CurrentLocation, ClassDecl);
13084 
13085   // Add a context note for diagnostics produced after this point.
13086   Scope.addContextNote(CurrentLocation);
13087 
13088   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13089     Constructor->setInvalidDecl();
13090     return;
13091   }
13092 
13093   SourceLocation Loc = Constructor->getEndLoc().isValid()
13094                            ? Constructor->getEndLoc()
13095                            : Constructor->getLocation();
13096   Constructor->setBody(new (Context) CompoundStmt(Loc));
13097   Constructor->markUsed(Context);
13098 
13099   if (ASTMutationListener *L = getASTMutationListener()) {
13100     L->CompletedImplicitDefinition(Constructor);
13101   }
13102 
13103   DiagnoseUninitializedFields(*this, Constructor);
13104 }
13105 
13106 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13107   // Perform any delayed checks on exception specifications.
13108   CheckDelayedMemberExceptionSpecs();
13109 }
13110 
13111 /// Find or create the fake constructor we synthesize to model constructing an
13112 /// object of a derived class via a constructor of a base class.
13113 CXXConstructorDecl *
13114 Sema::findInheritingConstructor(SourceLocation Loc,
13115                                 CXXConstructorDecl *BaseCtor,
13116                                 ConstructorUsingShadowDecl *Shadow) {
13117   CXXRecordDecl *Derived = Shadow->getParent();
13118   SourceLocation UsingLoc = Shadow->getLocation();
13119 
13120   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13121   // For now we use the name of the base class constructor as a member of the
13122   // derived class to indicate a (fake) inherited constructor name.
13123   DeclarationName Name = BaseCtor->getDeclName();
13124 
13125   // Check to see if we already have a fake constructor for this inherited
13126   // constructor call.
13127   for (NamedDecl *Ctor : Derived->lookup(Name))
13128     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13129                                ->getInheritedConstructor()
13130                                .getConstructor(),
13131                            BaseCtor))
13132       return cast<CXXConstructorDecl>(Ctor);
13133 
13134   DeclarationNameInfo NameInfo(Name, UsingLoc);
13135   TypeSourceInfo *TInfo =
13136       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13137   FunctionProtoTypeLoc ProtoLoc =
13138       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13139 
13140   // Check the inherited constructor is valid and find the list of base classes
13141   // from which it was inherited.
13142   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13143 
13144   bool Constexpr =
13145       BaseCtor->isConstexpr() &&
13146       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13147                                         false, BaseCtor, &ICI);
13148 
13149   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13150       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13151       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13152       /*isImplicitlyDeclared=*/true,
13153       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13154       InheritedConstructor(Shadow, BaseCtor),
13155       BaseCtor->getTrailingRequiresClause());
13156   if (Shadow->isInvalidDecl())
13157     DerivedCtor->setInvalidDecl();
13158 
13159   // Build an unevaluated exception specification for this fake constructor.
13160   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13161   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13162   EPI.ExceptionSpec.Type = EST_Unevaluated;
13163   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13164   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13165                                                FPT->getParamTypes(), EPI));
13166 
13167   // Build the parameter declarations.
13168   SmallVector<ParmVarDecl *, 16> ParamDecls;
13169   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13170     TypeSourceInfo *TInfo =
13171         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13172     ParmVarDecl *PD = ParmVarDecl::Create(
13173         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13174         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13175     PD->setScopeInfo(0, I);
13176     PD->setImplicit();
13177     // Ensure attributes are propagated onto parameters (this matters for
13178     // format, pass_object_size, ...).
13179     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13180     ParamDecls.push_back(PD);
13181     ProtoLoc.setParam(I, PD);
13182   }
13183 
13184   // Set up the new constructor.
13185   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13186   DerivedCtor->setAccess(BaseCtor->getAccess());
13187   DerivedCtor->setParams(ParamDecls);
13188   Derived->addDecl(DerivedCtor);
13189 
13190   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13191     SetDeclDeleted(DerivedCtor, UsingLoc);
13192 
13193   return DerivedCtor;
13194 }
13195 
13196 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13197   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13198                                Ctor->getInheritedConstructor().getShadowDecl());
13199   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13200                             /*Diagnose*/true);
13201 }
13202 
13203 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13204                                        CXXConstructorDecl *Constructor) {
13205   CXXRecordDecl *ClassDecl = Constructor->getParent();
13206   assert(Constructor->getInheritedConstructor() &&
13207          !Constructor->doesThisDeclarationHaveABody() &&
13208          !Constructor->isDeleted());
13209   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13210     return;
13211 
13212   // Initializations are performed "as if by a defaulted default constructor",
13213   // so enter the appropriate scope.
13214   SynthesizedFunctionScope Scope(*this, Constructor);
13215 
13216   // The exception specification is needed because we are defining the
13217   // function.
13218   ResolveExceptionSpec(CurrentLocation,
13219                        Constructor->getType()->castAs<FunctionProtoType>());
13220   MarkVTableUsed(CurrentLocation, ClassDecl);
13221 
13222   // Add a context note for diagnostics produced after this point.
13223   Scope.addContextNote(CurrentLocation);
13224 
13225   ConstructorUsingShadowDecl *Shadow =
13226       Constructor->getInheritedConstructor().getShadowDecl();
13227   CXXConstructorDecl *InheritedCtor =
13228       Constructor->getInheritedConstructor().getConstructor();
13229 
13230   // [class.inhctor.init]p1:
13231   //   initialization proceeds as if a defaulted default constructor is used to
13232   //   initialize the D object and each base class subobject from which the
13233   //   constructor was inherited
13234 
13235   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13236   CXXRecordDecl *RD = Shadow->getParent();
13237   SourceLocation InitLoc = Shadow->getLocation();
13238 
13239   // Build explicit initializers for all base classes from which the
13240   // constructor was inherited.
13241   SmallVector<CXXCtorInitializer*, 8> Inits;
13242   for (bool VBase : {false, true}) {
13243     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13244       if (B.isVirtual() != VBase)
13245         continue;
13246 
13247       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13248       if (!BaseRD)
13249         continue;
13250 
13251       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13252       if (!BaseCtor.first)
13253         continue;
13254 
13255       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13256       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13257           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13258 
13259       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13260       Inits.push_back(new (Context) CXXCtorInitializer(
13261           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13262           SourceLocation()));
13263     }
13264   }
13265 
13266   // We now proceed as if for a defaulted default constructor, with the relevant
13267   // initializers replaced.
13268 
13269   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13270     Constructor->setInvalidDecl();
13271     return;
13272   }
13273 
13274   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13275   Constructor->markUsed(Context);
13276 
13277   if (ASTMutationListener *L = getASTMutationListener()) {
13278     L->CompletedImplicitDefinition(Constructor);
13279   }
13280 
13281   DiagnoseUninitializedFields(*this, Constructor);
13282 }
13283 
13284 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13285   // C++ [class.dtor]p2:
13286   //   If a class has no user-declared destructor, a destructor is
13287   //   declared implicitly. An implicitly-declared destructor is an
13288   //   inline public member of its class.
13289   assert(ClassDecl->needsImplicitDestructor());
13290 
13291   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13292   if (DSM.isAlreadyBeingDeclared())
13293     return nullptr;
13294 
13295   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13296                                                      CXXDestructor,
13297                                                      false);
13298 
13299   // Create the actual destructor declaration.
13300   CanQualType ClassType
13301     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13302   SourceLocation ClassLoc = ClassDecl->getLocation();
13303   DeclarationName Name
13304     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13305   DeclarationNameInfo NameInfo(Name, ClassLoc);
13306   CXXDestructorDecl *Destructor =
13307       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13308                                 QualType(), nullptr, /*isInline=*/true,
13309                                 /*isImplicitlyDeclared=*/true,
13310                                 Constexpr ? ConstexprSpecKind::Constexpr
13311                                           : ConstexprSpecKind::Unspecified);
13312   Destructor->setAccess(AS_public);
13313   Destructor->setDefaulted();
13314 
13315   if (getLangOpts().CUDA) {
13316     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13317                                             Destructor,
13318                                             /* ConstRHS */ false,
13319                                             /* Diagnose */ false);
13320   }
13321 
13322   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13323 
13324   // We don't need to use SpecialMemberIsTrivial here; triviality for
13325   // destructors is easy to compute.
13326   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13327   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13328                                 ClassDecl->hasTrivialDestructorForCall());
13329 
13330   // Note that we have declared this destructor.
13331   ++getASTContext().NumImplicitDestructorsDeclared;
13332 
13333   Scope *S = getScopeForContext(ClassDecl);
13334   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13335 
13336   // We can't check whether an implicit destructor is deleted before we complete
13337   // the definition of the class, because its validity depends on the alignment
13338   // of the class. We'll check this from ActOnFields once the class is complete.
13339   if (ClassDecl->isCompleteDefinition() &&
13340       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13341     SetDeclDeleted(Destructor, ClassLoc);
13342 
13343   // Introduce this destructor into its scope.
13344   if (S)
13345     PushOnScopeChains(Destructor, S, false);
13346   ClassDecl->addDecl(Destructor);
13347 
13348   return Destructor;
13349 }
13350 
13351 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13352                                     CXXDestructorDecl *Destructor) {
13353   assert((Destructor->isDefaulted() &&
13354           !Destructor->doesThisDeclarationHaveABody() &&
13355           !Destructor->isDeleted()) &&
13356          "DefineImplicitDestructor - call it for implicit default dtor");
13357   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13358     return;
13359 
13360   CXXRecordDecl *ClassDecl = Destructor->getParent();
13361   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13362 
13363   SynthesizedFunctionScope Scope(*this, Destructor);
13364 
13365   // The exception specification is needed because we are defining the
13366   // function.
13367   ResolveExceptionSpec(CurrentLocation,
13368                        Destructor->getType()->castAs<FunctionProtoType>());
13369   MarkVTableUsed(CurrentLocation, ClassDecl);
13370 
13371   // Add a context note for diagnostics produced after this point.
13372   Scope.addContextNote(CurrentLocation);
13373 
13374   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13375                                          Destructor->getParent());
13376 
13377   if (CheckDestructor(Destructor)) {
13378     Destructor->setInvalidDecl();
13379     return;
13380   }
13381 
13382   SourceLocation Loc = Destructor->getEndLoc().isValid()
13383                            ? Destructor->getEndLoc()
13384                            : Destructor->getLocation();
13385   Destructor->setBody(new (Context) CompoundStmt(Loc));
13386   Destructor->markUsed(Context);
13387 
13388   if (ASTMutationListener *L = getASTMutationListener()) {
13389     L->CompletedImplicitDefinition(Destructor);
13390   }
13391 }
13392 
13393 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13394                                           CXXDestructorDecl *Destructor) {
13395   if (Destructor->isInvalidDecl())
13396     return;
13397 
13398   CXXRecordDecl *ClassDecl = Destructor->getParent();
13399   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13400          "implicit complete dtors unneeded outside MS ABI");
13401   assert(ClassDecl->getNumVBases() > 0 &&
13402          "complete dtor only exists for classes with vbases");
13403 
13404   SynthesizedFunctionScope Scope(*this, Destructor);
13405 
13406   // Add a context note for diagnostics produced after this point.
13407   Scope.addContextNote(CurrentLocation);
13408 
13409   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13410 }
13411 
13412 /// Perform any semantic analysis which needs to be delayed until all
13413 /// pending class member declarations have been parsed.
13414 void Sema::ActOnFinishCXXMemberDecls() {
13415   // If the context is an invalid C++ class, just suppress these checks.
13416   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13417     if (Record->isInvalidDecl()) {
13418       DelayedOverridingExceptionSpecChecks.clear();
13419       DelayedEquivalentExceptionSpecChecks.clear();
13420       return;
13421     }
13422     checkForMultipleExportedDefaultConstructors(*this, Record);
13423   }
13424 }
13425 
13426 void Sema::ActOnFinishCXXNonNestedClass() {
13427   referenceDLLExportedClassMethods();
13428 
13429   if (!DelayedDllExportMemberFunctions.empty()) {
13430     SmallVector<CXXMethodDecl*, 4> WorkList;
13431     std::swap(DelayedDllExportMemberFunctions, WorkList);
13432     for (CXXMethodDecl *M : WorkList) {
13433       DefineDefaultedFunction(*this, M, M->getLocation());
13434 
13435       // Pass the method to the consumer to get emitted. This is not necessary
13436       // for explicit instantiation definitions, as they will get emitted
13437       // anyway.
13438       if (M->getParent()->getTemplateSpecializationKind() !=
13439           TSK_ExplicitInstantiationDefinition)
13440         ActOnFinishInlineFunctionDef(M);
13441     }
13442   }
13443 }
13444 
13445 void Sema::referenceDLLExportedClassMethods() {
13446   if (!DelayedDllExportClasses.empty()) {
13447     // Calling ReferenceDllExportedMembers might cause the current function to
13448     // be called again, so use a local copy of DelayedDllExportClasses.
13449     SmallVector<CXXRecordDecl *, 4> WorkList;
13450     std::swap(DelayedDllExportClasses, WorkList);
13451     for (CXXRecordDecl *Class : WorkList)
13452       ReferenceDllExportedMembers(*this, Class);
13453   }
13454 }
13455 
13456 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13457   assert(getLangOpts().CPlusPlus11 &&
13458          "adjusting dtor exception specs was introduced in c++11");
13459 
13460   if (Destructor->isDependentContext())
13461     return;
13462 
13463   // C++11 [class.dtor]p3:
13464   //   A declaration of a destructor that does not have an exception-
13465   //   specification is implicitly considered to have the same exception-
13466   //   specification as an implicit declaration.
13467   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13468   if (DtorType->hasExceptionSpec())
13469     return;
13470 
13471   // Replace the destructor's type, building off the existing one. Fortunately,
13472   // the only thing of interest in the destructor type is its extended info.
13473   // The return and arguments are fixed.
13474   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13475   EPI.ExceptionSpec.Type = EST_Unevaluated;
13476   EPI.ExceptionSpec.SourceDecl = Destructor;
13477   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13478 
13479   // FIXME: If the destructor has a body that could throw, and the newly created
13480   // spec doesn't allow exceptions, we should emit a warning, because this
13481   // change in behavior can break conforming C++03 programs at runtime.
13482   // However, we don't have a body or an exception specification yet, so it
13483   // needs to be done somewhere else.
13484 }
13485 
13486 namespace {
13487 /// An abstract base class for all helper classes used in building the
13488 //  copy/move operators. These classes serve as factory functions and help us
13489 //  avoid using the same Expr* in the AST twice.
13490 class ExprBuilder {
13491   ExprBuilder(const ExprBuilder&) = delete;
13492   ExprBuilder &operator=(const ExprBuilder&) = delete;
13493 
13494 protected:
13495   static Expr *assertNotNull(Expr *E) {
13496     assert(E && "Expression construction must not fail.");
13497     return E;
13498   }
13499 
13500 public:
13501   ExprBuilder() {}
13502   virtual ~ExprBuilder() {}
13503 
13504   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13505 };
13506 
13507 class RefBuilder: public ExprBuilder {
13508   VarDecl *Var;
13509   QualType VarType;
13510 
13511 public:
13512   Expr *build(Sema &S, SourceLocation Loc) const override {
13513     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13514   }
13515 
13516   RefBuilder(VarDecl *Var, QualType VarType)
13517       : Var(Var), VarType(VarType) {}
13518 };
13519 
13520 class ThisBuilder: public ExprBuilder {
13521 public:
13522   Expr *build(Sema &S, SourceLocation Loc) const override {
13523     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13524   }
13525 };
13526 
13527 class CastBuilder: public ExprBuilder {
13528   const ExprBuilder &Builder;
13529   QualType Type;
13530   ExprValueKind Kind;
13531   const CXXCastPath &Path;
13532 
13533 public:
13534   Expr *build(Sema &S, SourceLocation Loc) const override {
13535     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13536                                              CK_UncheckedDerivedToBase, Kind,
13537                                              &Path).get());
13538   }
13539 
13540   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13541               const CXXCastPath &Path)
13542       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13543 };
13544 
13545 class DerefBuilder: public ExprBuilder {
13546   const ExprBuilder &Builder;
13547 
13548 public:
13549   Expr *build(Sema &S, SourceLocation Loc) const override {
13550     return assertNotNull(
13551         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13552   }
13553 
13554   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13555 };
13556 
13557 class MemberBuilder: public ExprBuilder {
13558   const ExprBuilder &Builder;
13559   QualType Type;
13560   CXXScopeSpec SS;
13561   bool IsArrow;
13562   LookupResult &MemberLookup;
13563 
13564 public:
13565   Expr *build(Sema &S, SourceLocation Loc) const override {
13566     return assertNotNull(S.BuildMemberReferenceExpr(
13567         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13568         nullptr, MemberLookup, nullptr, nullptr).get());
13569   }
13570 
13571   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13572                 LookupResult &MemberLookup)
13573       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13574         MemberLookup(MemberLookup) {}
13575 };
13576 
13577 class MoveCastBuilder: public ExprBuilder {
13578   const ExprBuilder &Builder;
13579 
13580 public:
13581   Expr *build(Sema &S, SourceLocation Loc) const override {
13582     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13583   }
13584 
13585   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13586 };
13587 
13588 class LvalueConvBuilder: public ExprBuilder {
13589   const ExprBuilder &Builder;
13590 
13591 public:
13592   Expr *build(Sema &S, SourceLocation Loc) const override {
13593     return assertNotNull(
13594         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13595   }
13596 
13597   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13598 };
13599 
13600 class SubscriptBuilder: public ExprBuilder {
13601   const ExprBuilder &Base;
13602   const ExprBuilder &Index;
13603 
13604 public:
13605   Expr *build(Sema &S, SourceLocation Loc) const override {
13606     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13607         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13608   }
13609 
13610   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13611       : Base(Base), Index(Index) {}
13612 };
13613 
13614 } // end anonymous namespace
13615 
13616 /// When generating a defaulted copy or move assignment operator, if a field
13617 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13618 /// do so. This optimization only applies for arrays of scalars, and for arrays
13619 /// of class type where the selected copy/move-assignment operator is trivial.
13620 static StmtResult
13621 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13622                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13623   // Compute the size of the memory buffer to be copied.
13624   QualType SizeType = S.Context.getSizeType();
13625   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13626                    S.Context.getTypeSizeInChars(T).getQuantity());
13627 
13628   // Take the address of the field references for "from" and "to". We
13629   // directly construct UnaryOperators here because semantic analysis
13630   // does not permit us to take the address of an xvalue.
13631   Expr *From = FromB.build(S, Loc);
13632   From = UnaryOperator::Create(
13633       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13634       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13635   Expr *To = ToB.build(S, Loc);
13636   To = UnaryOperator::Create(
13637       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13638       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13639 
13640   const Type *E = T->getBaseElementTypeUnsafe();
13641   bool NeedsCollectableMemCpy =
13642       E->isRecordType() &&
13643       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13644 
13645   // Create a reference to the __builtin_objc_memmove_collectable function
13646   StringRef MemCpyName = NeedsCollectableMemCpy ?
13647     "__builtin_objc_memmove_collectable" :
13648     "__builtin_memcpy";
13649   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13650                  Sema::LookupOrdinaryName);
13651   S.LookupName(R, S.TUScope, true);
13652 
13653   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13654   if (!MemCpy)
13655     // Something went horribly wrong earlier, and we will have complained
13656     // about it.
13657     return StmtError();
13658 
13659   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13660                                             VK_RValue, Loc, nullptr);
13661   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13662 
13663   Expr *CallArgs[] = {
13664     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13665   };
13666   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13667                                     Loc, CallArgs, Loc);
13668 
13669   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13670   return Call.getAs<Stmt>();
13671 }
13672 
13673 /// Builds a statement that copies/moves the given entity from \p From to
13674 /// \c To.
13675 ///
13676 /// This routine is used to copy/move the members of a class with an
13677 /// implicitly-declared copy/move assignment operator. When the entities being
13678 /// copied are arrays, this routine builds for loops to copy them.
13679 ///
13680 /// \param S The Sema object used for type-checking.
13681 ///
13682 /// \param Loc The location where the implicit copy/move is being generated.
13683 ///
13684 /// \param T The type of the expressions being copied/moved. Both expressions
13685 /// must have this type.
13686 ///
13687 /// \param To The expression we are copying/moving to.
13688 ///
13689 /// \param From The expression we are copying/moving from.
13690 ///
13691 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13692 /// Otherwise, it's a non-static member subobject.
13693 ///
13694 /// \param Copying Whether we're copying or moving.
13695 ///
13696 /// \param Depth Internal parameter recording the depth of the recursion.
13697 ///
13698 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13699 /// if a memcpy should be used instead.
13700 static StmtResult
13701 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13702                                  const ExprBuilder &To, const ExprBuilder &From,
13703                                  bool CopyingBaseSubobject, bool Copying,
13704                                  unsigned Depth = 0) {
13705   // C++11 [class.copy]p28:
13706   //   Each subobject is assigned in the manner appropriate to its type:
13707   //
13708   //     - if the subobject is of class type, as if by a call to operator= with
13709   //       the subobject as the object expression and the corresponding
13710   //       subobject of x as a single function argument (as if by explicit
13711   //       qualification; that is, ignoring any possible virtual overriding
13712   //       functions in more derived classes);
13713   //
13714   // C++03 [class.copy]p13:
13715   //     - if the subobject is of class type, the copy assignment operator for
13716   //       the class is used (as if by explicit qualification; that is,
13717   //       ignoring any possible virtual overriding functions in more derived
13718   //       classes);
13719   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13720     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13721 
13722     // Look for operator=.
13723     DeclarationName Name
13724       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13725     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13726     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13727 
13728     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13729     // operator.
13730     if (!S.getLangOpts().CPlusPlus11) {
13731       LookupResult::Filter F = OpLookup.makeFilter();
13732       while (F.hasNext()) {
13733         NamedDecl *D = F.next();
13734         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13735           if (Method->isCopyAssignmentOperator() ||
13736               (!Copying && Method->isMoveAssignmentOperator()))
13737             continue;
13738 
13739         F.erase();
13740       }
13741       F.done();
13742     }
13743 
13744     // Suppress the protected check (C++ [class.protected]) for each of the
13745     // assignment operators we found. This strange dance is required when
13746     // we're assigning via a base classes's copy-assignment operator. To
13747     // ensure that we're getting the right base class subobject (without
13748     // ambiguities), we need to cast "this" to that subobject type; to
13749     // ensure that we don't go through the virtual call mechanism, we need
13750     // to qualify the operator= name with the base class (see below). However,
13751     // this means that if the base class has a protected copy assignment
13752     // operator, the protected member access check will fail. So, we
13753     // rewrite "protected" access to "public" access in this case, since we
13754     // know by construction that we're calling from a derived class.
13755     if (CopyingBaseSubobject) {
13756       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13757            L != LEnd; ++L) {
13758         if (L.getAccess() == AS_protected)
13759           L.setAccess(AS_public);
13760       }
13761     }
13762 
13763     // Create the nested-name-specifier that will be used to qualify the
13764     // reference to operator=; this is required to suppress the virtual
13765     // call mechanism.
13766     CXXScopeSpec SS;
13767     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13768     SS.MakeTrivial(S.Context,
13769                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13770                                                CanonicalT),
13771                    Loc);
13772 
13773     // Create the reference to operator=.
13774     ExprResult OpEqualRef
13775       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13776                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13777                                    /*FirstQualifierInScope=*/nullptr,
13778                                    OpLookup,
13779                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13780                                    /*SuppressQualifierCheck=*/true);
13781     if (OpEqualRef.isInvalid())
13782       return StmtError();
13783 
13784     // Build the call to the assignment operator.
13785 
13786     Expr *FromInst = From.build(S, Loc);
13787     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13788                                                   OpEqualRef.getAs<Expr>(),
13789                                                   Loc, FromInst, Loc);
13790     if (Call.isInvalid())
13791       return StmtError();
13792 
13793     // If we built a call to a trivial 'operator=' while copying an array,
13794     // bail out. We'll replace the whole shebang with a memcpy.
13795     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13796     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13797       return StmtResult((Stmt*)nullptr);
13798 
13799     // Convert to an expression-statement, and clean up any produced
13800     // temporaries.
13801     return S.ActOnExprStmt(Call);
13802   }
13803 
13804   //     - if the subobject is of scalar type, the built-in assignment
13805   //       operator is used.
13806   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13807   if (!ArrayTy) {
13808     ExprResult Assignment = S.CreateBuiltinBinOp(
13809         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13810     if (Assignment.isInvalid())
13811       return StmtError();
13812     return S.ActOnExprStmt(Assignment);
13813   }
13814 
13815   //     - if the subobject is an array, each element is assigned, in the
13816   //       manner appropriate to the element type;
13817 
13818   // Construct a loop over the array bounds, e.g.,
13819   //
13820   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13821   //
13822   // that will copy each of the array elements.
13823   QualType SizeType = S.Context.getSizeType();
13824 
13825   // Create the iteration variable.
13826   IdentifierInfo *IterationVarName = nullptr;
13827   {
13828     SmallString<8> Str;
13829     llvm::raw_svector_ostream OS(Str);
13830     OS << "__i" << Depth;
13831     IterationVarName = &S.Context.Idents.get(OS.str());
13832   }
13833   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13834                                           IterationVarName, SizeType,
13835                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13836                                           SC_None);
13837 
13838   // Initialize the iteration variable to zero.
13839   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13840   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13841 
13842   // Creates a reference to the iteration variable.
13843   RefBuilder IterationVarRef(IterationVar, SizeType);
13844   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13845 
13846   // Create the DeclStmt that holds the iteration variable.
13847   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13848 
13849   // Subscript the "from" and "to" expressions with the iteration variable.
13850   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13851   MoveCastBuilder FromIndexMove(FromIndexCopy);
13852   const ExprBuilder *FromIndex;
13853   if (Copying)
13854     FromIndex = &FromIndexCopy;
13855   else
13856     FromIndex = &FromIndexMove;
13857 
13858   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13859 
13860   // Build the copy/move for an individual element of the array.
13861   StmtResult Copy =
13862     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13863                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13864                                      Copying, Depth + 1);
13865   // Bail out if copying fails or if we determined that we should use memcpy.
13866   if (Copy.isInvalid() || !Copy.get())
13867     return Copy;
13868 
13869   // Create the comparison against the array bound.
13870   llvm::APInt Upper
13871     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13872   Expr *Comparison = BinaryOperator::Create(
13873       S.Context, IterationVarRefRVal.build(S, Loc),
13874       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13875       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13876 
13877   // Create the pre-increment of the iteration variable. We can determine
13878   // whether the increment will overflow based on the value of the array
13879   // bound.
13880   Expr *Increment = UnaryOperator::Create(
13881       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13882       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13883 
13884   // Construct the loop that copies all elements of this array.
13885   return S.ActOnForStmt(
13886       Loc, Loc, InitStmt,
13887       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13888       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13889 }
13890 
13891 static StmtResult
13892 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13893                       const ExprBuilder &To, const ExprBuilder &From,
13894                       bool CopyingBaseSubobject, bool Copying) {
13895   // Maybe we should use a memcpy?
13896   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13897       T.isTriviallyCopyableType(S.Context))
13898     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13899 
13900   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13901                                                      CopyingBaseSubobject,
13902                                                      Copying, 0));
13903 
13904   // If we ended up picking a trivial assignment operator for an array of a
13905   // non-trivially-copyable class type, just emit a memcpy.
13906   if (!Result.isInvalid() && !Result.get())
13907     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13908 
13909   return Result;
13910 }
13911 
13912 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13913   // Note: The following rules are largely analoguous to the copy
13914   // constructor rules. Note that virtual bases are not taken into account
13915   // for determining the argument type of the operator. Note also that
13916   // operators taking an object instead of a reference are allowed.
13917   assert(ClassDecl->needsImplicitCopyAssignment());
13918 
13919   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13920   if (DSM.isAlreadyBeingDeclared())
13921     return nullptr;
13922 
13923   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13924   LangAS AS = getDefaultCXXMethodAddrSpace();
13925   if (AS != LangAS::Default)
13926     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13927   QualType RetType = Context.getLValueReferenceType(ArgType);
13928   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13929   if (Const)
13930     ArgType = ArgType.withConst();
13931 
13932   ArgType = Context.getLValueReferenceType(ArgType);
13933 
13934   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13935                                                      CXXCopyAssignment,
13936                                                      Const);
13937 
13938   //   An implicitly-declared copy assignment operator is an inline public
13939   //   member of its class.
13940   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13941   SourceLocation ClassLoc = ClassDecl->getLocation();
13942   DeclarationNameInfo NameInfo(Name, ClassLoc);
13943   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13944       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13945       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13946       /*isInline=*/true,
13947       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
13948       SourceLocation());
13949   CopyAssignment->setAccess(AS_public);
13950   CopyAssignment->setDefaulted();
13951   CopyAssignment->setImplicit();
13952 
13953   if (getLangOpts().CUDA) {
13954     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13955                                             CopyAssignment,
13956                                             /* ConstRHS */ Const,
13957                                             /* Diagnose */ false);
13958   }
13959 
13960   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13961 
13962   // Add the parameter to the operator.
13963   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13964                                                ClassLoc, ClassLoc,
13965                                                /*Id=*/nullptr, ArgType,
13966                                                /*TInfo=*/nullptr, SC_None,
13967                                                nullptr);
13968   CopyAssignment->setParams(FromParam);
13969 
13970   CopyAssignment->setTrivial(
13971     ClassDecl->needsOverloadResolutionForCopyAssignment()
13972       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13973       : ClassDecl->hasTrivialCopyAssignment());
13974 
13975   // Note that we have added this copy-assignment operator.
13976   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13977 
13978   Scope *S = getScopeForContext(ClassDecl);
13979   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13980 
13981   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13982     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13983     SetDeclDeleted(CopyAssignment, ClassLoc);
13984   }
13985 
13986   if (S)
13987     PushOnScopeChains(CopyAssignment, S, false);
13988   ClassDecl->addDecl(CopyAssignment);
13989 
13990   return CopyAssignment;
13991 }
13992 
13993 /// Diagnose an implicit copy operation for a class which is odr-used, but
13994 /// which is deprecated because the class has a user-declared copy constructor,
13995 /// copy assignment operator, or destructor.
13996 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13997   assert(CopyOp->isImplicit());
13998 
13999   CXXRecordDecl *RD = CopyOp->getParent();
14000   CXXMethodDecl *UserDeclaredOperation = nullptr;
14001 
14002   // In Microsoft mode, assignment operations don't affect constructors and
14003   // vice versa.
14004   if (RD->hasUserDeclaredDestructor()) {
14005     UserDeclaredOperation = RD->getDestructor();
14006   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14007              RD->hasUserDeclaredCopyConstructor() &&
14008              !S.getLangOpts().MSVCCompat) {
14009     // Find any user-declared copy constructor.
14010     for (auto *I : RD->ctors()) {
14011       if (I->isCopyConstructor()) {
14012         UserDeclaredOperation = I;
14013         break;
14014       }
14015     }
14016     assert(UserDeclaredOperation);
14017   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14018              RD->hasUserDeclaredCopyAssignment() &&
14019              !S.getLangOpts().MSVCCompat) {
14020     // Find any user-declared move assignment operator.
14021     for (auto *I : RD->methods()) {
14022       if (I->isCopyAssignmentOperator()) {
14023         UserDeclaredOperation = I;
14024         break;
14025       }
14026     }
14027     assert(UserDeclaredOperation);
14028   }
14029 
14030   if (UserDeclaredOperation) {
14031     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14032     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14033     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14034     unsigned DiagID =
14035         (UDOIsUserProvided && UDOIsDestructor)
14036             ? diag::warn_deprecated_copy_with_user_provided_dtor
14037         : (UDOIsUserProvided && !UDOIsDestructor)
14038             ? diag::warn_deprecated_copy_with_user_provided_copy
14039         : (!UDOIsUserProvided && UDOIsDestructor)
14040             ? diag::warn_deprecated_copy_with_dtor
14041             : diag::warn_deprecated_copy;
14042     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14043         << RD << IsCopyAssignment;
14044   }
14045 }
14046 
14047 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14048                                         CXXMethodDecl *CopyAssignOperator) {
14049   assert((CopyAssignOperator->isDefaulted() &&
14050           CopyAssignOperator->isOverloadedOperator() &&
14051           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14052           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14053           !CopyAssignOperator->isDeleted()) &&
14054          "DefineImplicitCopyAssignment called for wrong function");
14055   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14056     return;
14057 
14058   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14059   if (ClassDecl->isInvalidDecl()) {
14060     CopyAssignOperator->setInvalidDecl();
14061     return;
14062   }
14063 
14064   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14065 
14066   // The exception specification is needed because we are defining the
14067   // function.
14068   ResolveExceptionSpec(CurrentLocation,
14069                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14070 
14071   // Add a context note for diagnostics produced after this point.
14072   Scope.addContextNote(CurrentLocation);
14073 
14074   // C++11 [class.copy]p18:
14075   //   The [definition of an implicitly declared copy assignment operator] is
14076   //   deprecated if the class has a user-declared copy constructor or a
14077   //   user-declared destructor.
14078   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14079     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14080 
14081   // C++0x [class.copy]p30:
14082   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14083   //   for a non-union class X performs memberwise copy assignment of its
14084   //   subobjects. The direct base classes of X are assigned first, in the
14085   //   order of their declaration in the base-specifier-list, and then the
14086   //   immediate non-static data members of X are assigned, in the order in
14087   //   which they were declared in the class definition.
14088 
14089   // The statements that form the synthesized function body.
14090   SmallVector<Stmt*, 8> Statements;
14091 
14092   // The parameter for the "other" object, which we are copying from.
14093   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14094   Qualifiers OtherQuals = Other->getType().getQualifiers();
14095   QualType OtherRefType = Other->getType();
14096   if (const LValueReferenceType *OtherRef
14097                                 = OtherRefType->getAs<LValueReferenceType>()) {
14098     OtherRefType = OtherRef->getPointeeType();
14099     OtherQuals = OtherRefType.getQualifiers();
14100   }
14101 
14102   // Our location for everything implicitly-generated.
14103   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14104                            ? CopyAssignOperator->getEndLoc()
14105                            : CopyAssignOperator->getLocation();
14106 
14107   // Builds a DeclRefExpr for the "other" object.
14108   RefBuilder OtherRef(Other, OtherRefType);
14109 
14110   // Builds the "this" pointer.
14111   ThisBuilder This;
14112 
14113   // Assign base classes.
14114   bool Invalid = false;
14115   for (auto &Base : ClassDecl->bases()) {
14116     // Form the assignment:
14117     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14118     QualType BaseType = Base.getType().getUnqualifiedType();
14119     if (!BaseType->isRecordType()) {
14120       Invalid = true;
14121       continue;
14122     }
14123 
14124     CXXCastPath BasePath;
14125     BasePath.push_back(&Base);
14126 
14127     // Construct the "from" expression, which is an implicit cast to the
14128     // appropriately-qualified base type.
14129     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14130                      VK_LValue, BasePath);
14131 
14132     // Dereference "this".
14133     DerefBuilder DerefThis(This);
14134     CastBuilder To(DerefThis,
14135                    Context.getQualifiedType(
14136                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14137                    VK_LValue, BasePath);
14138 
14139     // Build the copy.
14140     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14141                                             To, From,
14142                                             /*CopyingBaseSubobject=*/true,
14143                                             /*Copying=*/true);
14144     if (Copy.isInvalid()) {
14145       CopyAssignOperator->setInvalidDecl();
14146       return;
14147     }
14148 
14149     // Success! Record the copy.
14150     Statements.push_back(Copy.getAs<Expr>());
14151   }
14152 
14153   // Assign non-static members.
14154   for (auto *Field : ClassDecl->fields()) {
14155     // FIXME: We should form some kind of AST representation for the implied
14156     // memcpy in a union copy operation.
14157     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14158       continue;
14159 
14160     if (Field->isInvalidDecl()) {
14161       Invalid = true;
14162       continue;
14163     }
14164 
14165     // Check for members of reference type; we can't copy those.
14166     if (Field->getType()->isReferenceType()) {
14167       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14168         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14169       Diag(Field->getLocation(), diag::note_declared_at);
14170       Invalid = true;
14171       continue;
14172     }
14173 
14174     // Check for members of const-qualified, non-class type.
14175     QualType BaseType = Context.getBaseElementType(Field->getType());
14176     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14177       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14178         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14179       Diag(Field->getLocation(), diag::note_declared_at);
14180       Invalid = true;
14181       continue;
14182     }
14183 
14184     // Suppress assigning zero-width bitfields.
14185     if (Field->isZeroLengthBitField(Context))
14186       continue;
14187 
14188     QualType FieldType = Field->getType().getNonReferenceType();
14189     if (FieldType->isIncompleteArrayType()) {
14190       assert(ClassDecl->hasFlexibleArrayMember() &&
14191              "Incomplete array type is not valid");
14192       continue;
14193     }
14194 
14195     // Build references to the field in the object we're copying from and to.
14196     CXXScopeSpec SS; // Intentionally empty
14197     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14198                               LookupMemberName);
14199     MemberLookup.addDecl(Field);
14200     MemberLookup.resolveKind();
14201 
14202     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14203 
14204     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14205 
14206     // Build the copy of this field.
14207     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14208                                             To, From,
14209                                             /*CopyingBaseSubobject=*/false,
14210                                             /*Copying=*/true);
14211     if (Copy.isInvalid()) {
14212       CopyAssignOperator->setInvalidDecl();
14213       return;
14214     }
14215 
14216     // Success! Record the copy.
14217     Statements.push_back(Copy.getAs<Stmt>());
14218   }
14219 
14220   if (!Invalid) {
14221     // Add a "return *this;"
14222     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14223 
14224     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14225     if (Return.isInvalid())
14226       Invalid = true;
14227     else
14228       Statements.push_back(Return.getAs<Stmt>());
14229   }
14230 
14231   if (Invalid) {
14232     CopyAssignOperator->setInvalidDecl();
14233     return;
14234   }
14235 
14236   StmtResult Body;
14237   {
14238     CompoundScopeRAII CompoundScope(*this);
14239     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14240                              /*isStmtExpr=*/false);
14241     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14242   }
14243   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14244   CopyAssignOperator->markUsed(Context);
14245 
14246   if (ASTMutationListener *L = getASTMutationListener()) {
14247     L->CompletedImplicitDefinition(CopyAssignOperator);
14248   }
14249 }
14250 
14251 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14252   assert(ClassDecl->needsImplicitMoveAssignment());
14253 
14254   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14255   if (DSM.isAlreadyBeingDeclared())
14256     return nullptr;
14257 
14258   // Note: The following rules are largely analoguous to the move
14259   // constructor rules.
14260 
14261   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14262   LangAS AS = getDefaultCXXMethodAddrSpace();
14263   if (AS != LangAS::Default)
14264     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14265   QualType RetType = Context.getLValueReferenceType(ArgType);
14266   ArgType = Context.getRValueReferenceType(ArgType);
14267 
14268   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14269                                                      CXXMoveAssignment,
14270                                                      false);
14271 
14272   //   An implicitly-declared move assignment operator is an inline public
14273   //   member of its class.
14274   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14275   SourceLocation ClassLoc = ClassDecl->getLocation();
14276   DeclarationNameInfo NameInfo(Name, ClassLoc);
14277   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14278       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14279       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14280       /*isInline=*/true,
14281       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14282       SourceLocation());
14283   MoveAssignment->setAccess(AS_public);
14284   MoveAssignment->setDefaulted();
14285   MoveAssignment->setImplicit();
14286 
14287   if (getLangOpts().CUDA) {
14288     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14289                                             MoveAssignment,
14290                                             /* ConstRHS */ false,
14291                                             /* Diagnose */ false);
14292   }
14293 
14294   // Build an exception specification pointing back at this member.
14295   FunctionProtoType::ExtProtoInfo EPI =
14296       getImplicitMethodEPI(*this, MoveAssignment);
14297   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14298 
14299   // Add the parameter to the operator.
14300   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14301                                                ClassLoc, ClassLoc,
14302                                                /*Id=*/nullptr, ArgType,
14303                                                /*TInfo=*/nullptr, SC_None,
14304                                                nullptr);
14305   MoveAssignment->setParams(FromParam);
14306 
14307   MoveAssignment->setTrivial(
14308     ClassDecl->needsOverloadResolutionForMoveAssignment()
14309       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14310       : ClassDecl->hasTrivialMoveAssignment());
14311 
14312   // Note that we have added this copy-assignment operator.
14313   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14314 
14315   Scope *S = getScopeForContext(ClassDecl);
14316   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14317 
14318   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14319     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14320     SetDeclDeleted(MoveAssignment, ClassLoc);
14321   }
14322 
14323   if (S)
14324     PushOnScopeChains(MoveAssignment, S, false);
14325   ClassDecl->addDecl(MoveAssignment);
14326 
14327   return MoveAssignment;
14328 }
14329 
14330 /// Check if we're implicitly defining a move assignment operator for a class
14331 /// with virtual bases. Such a move assignment might move-assign the virtual
14332 /// base multiple times.
14333 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14334                                                SourceLocation CurrentLocation) {
14335   assert(!Class->isDependentContext() && "should not define dependent move");
14336 
14337   // Only a virtual base could get implicitly move-assigned multiple times.
14338   // Only a non-trivial move assignment can observe this. We only want to
14339   // diagnose if we implicitly define an assignment operator that assigns
14340   // two base classes, both of which move-assign the same virtual base.
14341   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14342       Class->getNumBases() < 2)
14343     return;
14344 
14345   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14346   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14347   VBaseMap VBases;
14348 
14349   for (auto &BI : Class->bases()) {
14350     Worklist.push_back(&BI);
14351     while (!Worklist.empty()) {
14352       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14353       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14354 
14355       // If the base has no non-trivial move assignment operators,
14356       // we don't care about moves from it.
14357       if (!Base->hasNonTrivialMoveAssignment())
14358         continue;
14359 
14360       // If there's nothing virtual here, skip it.
14361       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14362         continue;
14363 
14364       // If we're not actually going to call a move assignment for this base,
14365       // or the selected move assignment is trivial, skip it.
14366       Sema::SpecialMemberOverloadResult SMOR =
14367         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14368                               /*ConstArg*/false, /*VolatileArg*/false,
14369                               /*RValueThis*/true, /*ConstThis*/false,
14370                               /*VolatileThis*/false);
14371       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14372           !SMOR.getMethod()->isMoveAssignmentOperator())
14373         continue;
14374 
14375       if (BaseSpec->isVirtual()) {
14376         // We're going to move-assign this virtual base, and its move
14377         // assignment operator is not trivial. If this can happen for
14378         // multiple distinct direct bases of Class, diagnose it. (If it
14379         // only happens in one base, we'll diagnose it when synthesizing
14380         // that base class's move assignment operator.)
14381         CXXBaseSpecifier *&Existing =
14382             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14383                 .first->second;
14384         if (Existing && Existing != &BI) {
14385           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14386             << Class << Base;
14387           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14388               << (Base->getCanonicalDecl() ==
14389                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14390               << Base << Existing->getType() << Existing->getSourceRange();
14391           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14392               << (Base->getCanonicalDecl() ==
14393                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14394               << Base << BI.getType() << BaseSpec->getSourceRange();
14395 
14396           // Only diagnose each vbase once.
14397           Existing = nullptr;
14398         }
14399       } else {
14400         // Only walk over bases that have defaulted move assignment operators.
14401         // We assume that any user-provided move assignment operator handles
14402         // the multiple-moves-of-vbase case itself somehow.
14403         if (!SMOR.getMethod()->isDefaulted())
14404           continue;
14405 
14406         // We're going to move the base classes of Base. Add them to the list.
14407         for (auto &BI : Base->bases())
14408           Worklist.push_back(&BI);
14409       }
14410     }
14411   }
14412 }
14413 
14414 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14415                                         CXXMethodDecl *MoveAssignOperator) {
14416   assert((MoveAssignOperator->isDefaulted() &&
14417           MoveAssignOperator->isOverloadedOperator() &&
14418           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14419           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14420           !MoveAssignOperator->isDeleted()) &&
14421          "DefineImplicitMoveAssignment called for wrong function");
14422   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14423     return;
14424 
14425   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14426   if (ClassDecl->isInvalidDecl()) {
14427     MoveAssignOperator->setInvalidDecl();
14428     return;
14429   }
14430 
14431   // C++0x [class.copy]p28:
14432   //   The implicitly-defined or move assignment operator for a non-union class
14433   //   X performs memberwise move assignment of its subobjects. The direct base
14434   //   classes of X are assigned first, in the order of their declaration in the
14435   //   base-specifier-list, and then the immediate non-static data members of X
14436   //   are assigned, in the order in which they were declared in the class
14437   //   definition.
14438 
14439   // Issue a warning if our implicit move assignment operator will move
14440   // from a virtual base more than once.
14441   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14442 
14443   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14444 
14445   // The exception specification is needed because we are defining the
14446   // function.
14447   ResolveExceptionSpec(CurrentLocation,
14448                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14449 
14450   // Add a context note for diagnostics produced after this point.
14451   Scope.addContextNote(CurrentLocation);
14452 
14453   // The statements that form the synthesized function body.
14454   SmallVector<Stmt*, 8> Statements;
14455 
14456   // The parameter for the "other" object, which we are move from.
14457   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14458   QualType OtherRefType =
14459       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14460 
14461   // Our location for everything implicitly-generated.
14462   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14463                            ? MoveAssignOperator->getEndLoc()
14464                            : MoveAssignOperator->getLocation();
14465 
14466   // Builds a reference to the "other" object.
14467   RefBuilder OtherRef(Other, OtherRefType);
14468   // Cast to rvalue.
14469   MoveCastBuilder MoveOther(OtherRef);
14470 
14471   // Builds the "this" pointer.
14472   ThisBuilder This;
14473 
14474   // Assign base classes.
14475   bool Invalid = false;
14476   for (auto &Base : ClassDecl->bases()) {
14477     // C++11 [class.copy]p28:
14478     //   It is unspecified whether subobjects representing virtual base classes
14479     //   are assigned more than once by the implicitly-defined copy assignment
14480     //   operator.
14481     // FIXME: Do not assign to a vbase that will be assigned by some other base
14482     // class. For a move-assignment, this can result in the vbase being moved
14483     // multiple times.
14484 
14485     // Form the assignment:
14486     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14487     QualType BaseType = Base.getType().getUnqualifiedType();
14488     if (!BaseType->isRecordType()) {
14489       Invalid = true;
14490       continue;
14491     }
14492 
14493     CXXCastPath BasePath;
14494     BasePath.push_back(&Base);
14495 
14496     // Construct the "from" expression, which is an implicit cast to the
14497     // appropriately-qualified base type.
14498     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14499 
14500     // Dereference "this".
14501     DerefBuilder DerefThis(This);
14502 
14503     // Implicitly cast "this" to the appropriately-qualified base type.
14504     CastBuilder To(DerefThis,
14505                    Context.getQualifiedType(
14506                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14507                    VK_LValue, BasePath);
14508 
14509     // Build the move.
14510     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14511                                             To, From,
14512                                             /*CopyingBaseSubobject=*/true,
14513                                             /*Copying=*/false);
14514     if (Move.isInvalid()) {
14515       MoveAssignOperator->setInvalidDecl();
14516       return;
14517     }
14518 
14519     // Success! Record the move.
14520     Statements.push_back(Move.getAs<Expr>());
14521   }
14522 
14523   // Assign non-static members.
14524   for (auto *Field : ClassDecl->fields()) {
14525     // FIXME: We should form some kind of AST representation for the implied
14526     // memcpy in a union copy operation.
14527     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14528       continue;
14529 
14530     if (Field->isInvalidDecl()) {
14531       Invalid = true;
14532       continue;
14533     }
14534 
14535     // Check for members of reference type; we can't move those.
14536     if (Field->getType()->isReferenceType()) {
14537       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14538         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14539       Diag(Field->getLocation(), diag::note_declared_at);
14540       Invalid = true;
14541       continue;
14542     }
14543 
14544     // Check for members of const-qualified, non-class type.
14545     QualType BaseType = Context.getBaseElementType(Field->getType());
14546     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14547       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14548         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14549       Diag(Field->getLocation(), diag::note_declared_at);
14550       Invalid = true;
14551       continue;
14552     }
14553 
14554     // Suppress assigning zero-width bitfields.
14555     if (Field->isZeroLengthBitField(Context))
14556       continue;
14557 
14558     QualType FieldType = Field->getType().getNonReferenceType();
14559     if (FieldType->isIncompleteArrayType()) {
14560       assert(ClassDecl->hasFlexibleArrayMember() &&
14561              "Incomplete array type is not valid");
14562       continue;
14563     }
14564 
14565     // Build references to the field in the object we're copying from and to.
14566     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14567                               LookupMemberName);
14568     MemberLookup.addDecl(Field);
14569     MemberLookup.resolveKind();
14570     MemberBuilder From(MoveOther, OtherRefType,
14571                        /*IsArrow=*/false, MemberLookup);
14572     MemberBuilder To(This, getCurrentThisType(),
14573                      /*IsArrow=*/true, MemberLookup);
14574 
14575     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14576         "Member reference with rvalue base must be rvalue except for reference "
14577         "members, which aren't allowed for move assignment.");
14578 
14579     // Build the move of this field.
14580     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14581                                             To, From,
14582                                             /*CopyingBaseSubobject=*/false,
14583                                             /*Copying=*/false);
14584     if (Move.isInvalid()) {
14585       MoveAssignOperator->setInvalidDecl();
14586       return;
14587     }
14588 
14589     // Success! Record the copy.
14590     Statements.push_back(Move.getAs<Stmt>());
14591   }
14592 
14593   if (!Invalid) {
14594     // Add a "return *this;"
14595     ExprResult ThisObj =
14596         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14597 
14598     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14599     if (Return.isInvalid())
14600       Invalid = true;
14601     else
14602       Statements.push_back(Return.getAs<Stmt>());
14603   }
14604 
14605   if (Invalid) {
14606     MoveAssignOperator->setInvalidDecl();
14607     return;
14608   }
14609 
14610   StmtResult Body;
14611   {
14612     CompoundScopeRAII CompoundScope(*this);
14613     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14614                              /*isStmtExpr=*/false);
14615     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14616   }
14617   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14618   MoveAssignOperator->markUsed(Context);
14619 
14620   if (ASTMutationListener *L = getASTMutationListener()) {
14621     L->CompletedImplicitDefinition(MoveAssignOperator);
14622   }
14623 }
14624 
14625 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14626                                                     CXXRecordDecl *ClassDecl) {
14627   // C++ [class.copy]p4:
14628   //   If the class definition does not explicitly declare a copy
14629   //   constructor, one is declared implicitly.
14630   assert(ClassDecl->needsImplicitCopyConstructor());
14631 
14632   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14633   if (DSM.isAlreadyBeingDeclared())
14634     return nullptr;
14635 
14636   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14637   QualType ArgType = ClassType;
14638   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14639   if (Const)
14640     ArgType = ArgType.withConst();
14641 
14642   LangAS AS = getDefaultCXXMethodAddrSpace();
14643   if (AS != LangAS::Default)
14644     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14645 
14646   ArgType = Context.getLValueReferenceType(ArgType);
14647 
14648   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14649                                                      CXXCopyConstructor,
14650                                                      Const);
14651 
14652   DeclarationName Name
14653     = Context.DeclarationNames.getCXXConstructorName(
14654                                            Context.getCanonicalType(ClassType));
14655   SourceLocation ClassLoc = ClassDecl->getLocation();
14656   DeclarationNameInfo NameInfo(Name, ClassLoc);
14657 
14658   //   An implicitly-declared copy constructor is an inline public
14659   //   member of its class.
14660   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14661       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14662       ExplicitSpecifier(),
14663       /*isInline=*/true,
14664       /*isImplicitlyDeclared=*/true,
14665       Constexpr ? ConstexprSpecKind::Constexpr
14666                 : ConstexprSpecKind::Unspecified);
14667   CopyConstructor->setAccess(AS_public);
14668   CopyConstructor->setDefaulted();
14669 
14670   if (getLangOpts().CUDA) {
14671     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14672                                             CopyConstructor,
14673                                             /* ConstRHS */ Const,
14674                                             /* Diagnose */ false);
14675   }
14676 
14677   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14678 
14679   // Add the parameter to the constructor.
14680   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14681                                                ClassLoc, ClassLoc,
14682                                                /*IdentifierInfo=*/nullptr,
14683                                                ArgType, /*TInfo=*/nullptr,
14684                                                SC_None, nullptr);
14685   CopyConstructor->setParams(FromParam);
14686 
14687   CopyConstructor->setTrivial(
14688       ClassDecl->needsOverloadResolutionForCopyConstructor()
14689           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14690           : ClassDecl->hasTrivialCopyConstructor());
14691 
14692   CopyConstructor->setTrivialForCall(
14693       ClassDecl->hasAttr<TrivialABIAttr>() ||
14694       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14695            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14696              TAH_ConsiderTrivialABI)
14697            : ClassDecl->hasTrivialCopyConstructorForCall()));
14698 
14699   // Note that we have declared this constructor.
14700   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14701 
14702   Scope *S = getScopeForContext(ClassDecl);
14703   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14704 
14705   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14706     ClassDecl->setImplicitCopyConstructorIsDeleted();
14707     SetDeclDeleted(CopyConstructor, ClassLoc);
14708   }
14709 
14710   if (S)
14711     PushOnScopeChains(CopyConstructor, S, false);
14712   ClassDecl->addDecl(CopyConstructor);
14713 
14714   return CopyConstructor;
14715 }
14716 
14717 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14718                                          CXXConstructorDecl *CopyConstructor) {
14719   assert((CopyConstructor->isDefaulted() &&
14720           CopyConstructor->isCopyConstructor() &&
14721           !CopyConstructor->doesThisDeclarationHaveABody() &&
14722           !CopyConstructor->isDeleted()) &&
14723          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14724   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14725     return;
14726 
14727   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14728   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14729 
14730   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14731 
14732   // The exception specification is needed because we are defining the
14733   // function.
14734   ResolveExceptionSpec(CurrentLocation,
14735                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14736   MarkVTableUsed(CurrentLocation, ClassDecl);
14737 
14738   // Add a context note for diagnostics produced after this point.
14739   Scope.addContextNote(CurrentLocation);
14740 
14741   // C++11 [class.copy]p7:
14742   //   The [definition of an implicitly declared copy constructor] is
14743   //   deprecated if the class has a user-declared copy assignment operator
14744   //   or a user-declared destructor.
14745   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14746     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14747 
14748   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14749     CopyConstructor->setInvalidDecl();
14750   }  else {
14751     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14752                              ? CopyConstructor->getEndLoc()
14753                              : CopyConstructor->getLocation();
14754     Sema::CompoundScopeRAII CompoundScope(*this);
14755     CopyConstructor->setBody(
14756         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14757     CopyConstructor->markUsed(Context);
14758   }
14759 
14760   if (ASTMutationListener *L = getASTMutationListener()) {
14761     L->CompletedImplicitDefinition(CopyConstructor);
14762   }
14763 }
14764 
14765 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14766                                                     CXXRecordDecl *ClassDecl) {
14767   assert(ClassDecl->needsImplicitMoveConstructor());
14768 
14769   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14770   if (DSM.isAlreadyBeingDeclared())
14771     return nullptr;
14772 
14773   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14774 
14775   QualType ArgType = ClassType;
14776   LangAS AS = getDefaultCXXMethodAddrSpace();
14777   if (AS != LangAS::Default)
14778     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14779   ArgType = Context.getRValueReferenceType(ArgType);
14780 
14781   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14782                                                      CXXMoveConstructor,
14783                                                      false);
14784 
14785   DeclarationName Name
14786     = Context.DeclarationNames.getCXXConstructorName(
14787                                            Context.getCanonicalType(ClassType));
14788   SourceLocation ClassLoc = ClassDecl->getLocation();
14789   DeclarationNameInfo NameInfo(Name, ClassLoc);
14790 
14791   // C++11 [class.copy]p11:
14792   //   An implicitly-declared copy/move constructor is an inline public
14793   //   member of its class.
14794   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14795       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14796       ExplicitSpecifier(),
14797       /*isInline=*/true,
14798       /*isImplicitlyDeclared=*/true,
14799       Constexpr ? ConstexprSpecKind::Constexpr
14800                 : ConstexprSpecKind::Unspecified);
14801   MoveConstructor->setAccess(AS_public);
14802   MoveConstructor->setDefaulted();
14803 
14804   if (getLangOpts().CUDA) {
14805     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14806                                             MoveConstructor,
14807                                             /* ConstRHS */ false,
14808                                             /* Diagnose */ false);
14809   }
14810 
14811   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14812 
14813   // Add the parameter to the constructor.
14814   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14815                                                ClassLoc, ClassLoc,
14816                                                /*IdentifierInfo=*/nullptr,
14817                                                ArgType, /*TInfo=*/nullptr,
14818                                                SC_None, nullptr);
14819   MoveConstructor->setParams(FromParam);
14820 
14821   MoveConstructor->setTrivial(
14822       ClassDecl->needsOverloadResolutionForMoveConstructor()
14823           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14824           : ClassDecl->hasTrivialMoveConstructor());
14825 
14826   MoveConstructor->setTrivialForCall(
14827       ClassDecl->hasAttr<TrivialABIAttr>() ||
14828       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14829            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14830                                     TAH_ConsiderTrivialABI)
14831            : ClassDecl->hasTrivialMoveConstructorForCall()));
14832 
14833   // Note that we have declared this constructor.
14834   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14835 
14836   Scope *S = getScopeForContext(ClassDecl);
14837   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14838 
14839   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14840     ClassDecl->setImplicitMoveConstructorIsDeleted();
14841     SetDeclDeleted(MoveConstructor, ClassLoc);
14842   }
14843 
14844   if (S)
14845     PushOnScopeChains(MoveConstructor, S, false);
14846   ClassDecl->addDecl(MoveConstructor);
14847 
14848   return MoveConstructor;
14849 }
14850 
14851 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14852                                          CXXConstructorDecl *MoveConstructor) {
14853   assert((MoveConstructor->isDefaulted() &&
14854           MoveConstructor->isMoveConstructor() &&
14855           !MoveConstructor->doesThisDeclarationHaveABody() &&
14856           !MoveConstructor->isDeleted()) &&
14857          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14858   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14859     return;
14860 
14861   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14862   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14863 
14864   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14865 
14866   // The exception specification is needed because we are defining the
14867   // function.
14868   ResolveExceptionSpec(CurrentLocation,
14869                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14870   MarkVTableUsed(CurrentLocation, ClassDecl);
14871 
14872   // Add a context note for diagnostics produced after this point.
14873   Scope.addContextNote(CurrentLocation);
14874 
14875   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14876     MoveConstructor->setInvalidDecl();
14877   } else {
14878     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14879                              ? MoveConstructor->getEndLoc()
14880                              : MoveConstructor->getLocation();
14881     Sema::CompoundScopeRAII CompoundScope(*this);
14882     MoveConstructor->setBody(ActOnCompoundStmt(
14883         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14884     MoveConstructor->markUsed(Context);
14885   }
14886 
14887   if (ASTMutationListener *L = getASTMutationListener()) {
14888     L->CompletedImplicitDefinition(MoveConstructor);
14889   }
14890 }
14891 
14892 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14893   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14894 }
14895 
14896 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14897                             SourceLocation CurrentLocation,
14898                             CXXConversionDecl *Conv) {
14899   SynthesizedFunctionScope Scope(*this, Conv);
14900   assert(!Conv->getReturnType()->isUndeducedType());
14901 
14902   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
14903   CallingConv CC =
14904       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
14905 
14906   CXXRecordDecl *Lambda = Conv->getParent();
14907   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14908   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
14909 
14910   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14911     CallOp = InstantiateFunctionDeclaration(
14912         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14913     if (!CallOp)
14914       return;
14915 
14916     Invoker = InstantiateFunctionDeclaration(
14917         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14918     if (!Invoker)
14919       return;
14920   }
14921 
14922   if (CallOp->isInvalidDecl())
14923     return;
14924 
14925   // Mark the call operator referenced (and add to pending instantiations
14926   // if necessary).
14927   // For both the conversion and static-invoker template specializations
14928   // we construct their body's in this function, so no need to add them
14929   // to the PendingInstantiations.
14930   MarkFunctionReferenced(CurrentLocation, CallOp);
14931 
14932   // Fill in the __invoke function with a dummy implementation. IR generation
14933   // will fill in the actual details. Update its type in case it contained
14934   // an 'auto'.
14935   Invoker->markUsed(Context);
14936   Invoker->setReferenced();
14937   Invoker->setType(Conv->getReturnType()->getPointeeType());
14938   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14939 
14940   // Construct the body of the conversion function { return __invoke; }.
14941   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14942                                        VK_LValue, Conv->getLocation());
14943   assert(FunctionRef && "Can't refer to __invoke function?");
14944   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14945   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14946                                      Conv->getLocation()));
14947   Conv->markUsed(Context);
14948   Conv->setReferenced();
14949 
14950   if (ASTMutationListener *L = getASTMutationListener()) {
14951     L->CompletedImplicitDefinition(Conv);
14952     L->CompletedImplicitDefinition(Invoker);
14953   }
14954 }
14955 
14956 
14957 
14958 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14959        SourceLocation CurrentLocation,
14960        CXXConversionDecl *Conv)
14961 {
14962   assert(!Conv->getParent()->isGenericLambda());
14963 
14964   SynthesizedFunctionScope Scope(*this, Conv);
14965 
14966   // Copy-initialize the lambda object as needed to capture it.
14967   Expr *This = ActOnCXXThis(CurrentLocation).get();
14968   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14969 
14970   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14971                                                         Conv->getLocation(),
14972                                                         Conv, DerefThis);
14973 
14974   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14975   // behavior.  Note that only the general conversion function does this
14976   // (since it's unusable otherwise); in the case where we inline the
14977   // block literal, it has block literal lifetime semantics.
14978   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14979     BuildBlock = ImplicitCastExpr::Create(
14980         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14981         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14982 
14983   if (BuildBlock.isInvalid()) {
14984     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14985     Conv->setInvalidDecl();
14986     return;
14987   }
14988 
14989   // Create the return statement that returns the block from the conversion
14990   // function.
14991   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14992   if (Return.isInvalid()) {
14993     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14994     Conv->setInvalidDecl();
14995     return;
14996   }
14997 
14998   // Set the body of the conversion function.
14999   Stmt *ReturnS = Return.get();
15000   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15001                                      Conv->getLocation()));
15002   Conv->markUsed(Context);
15003 
15004   // We're done; notify the mutation listener, if any.
15005   if (ASTMutationListener *L = getASTMutationListener()) {
15006     L->CompletedImplicitDefinition(Conv);
15007   }
15008 }
15009 
15010 /// Determine whether the given list arguments contains exactly one
15011 /// "real" (non-default) argument.
15012 static bool hasOneRealArgument(MultiExprArg Args) {
15013   switch (Args.size()) {
15014   case 0:
15015     return false;
15016 
15017   default:
15018     if (!Args[1]->isDefaultArgument())
15019       return false;
15020 
15021     LLVM_FALLTHROUGH;
15022   case 1:
15023     return !Args[0]->isDefaultArgument();
15024   }
15025 
15026   return false;
15027 }
15028 
15029 ExprResult
15030 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15031                             NamedDecl *FoundDecl,
15032                             CXXConstructorDecl *Constructor,
15033                             MultiExprArg ExprArgs,
15034                             bool HadMultipleCandidates,
15035                             bool IsListInitialization,
15036                             bool IsStdInitListInitialization,
15037                             bool RequiresZeroInit,
15038                             unsigned ConstructKind,
15039                             SourceRange ParenRange) {
15040   bool Elidable = false;
15041 
15042   // C++0x [class.copy]p34:
15043   //   When certain criteria are met, an implementation is allowed to
15044   //   omit the copy/move construction of a class object, even if the
15045   //   copy/move constructor and/or destructor for the object have
15046   //   side effects. [...]
15047   //     - when a temporary class object that has not been bound to a
15048   //       reference (12.2) would be copied/moved to a class object
15049   //       with the same cv-unqualified type, the copy/move operation
15050   //       can be omitted by constructing the temporary object
15051   //       directly into the target of the omitted copy/move
15052   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15053       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15054     Expr *SubExpr = ExprArgs[0];
15055     Elidable = SubExpr->isTemporaryObject(
15056         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15057   }
15058 
15059   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15060                                FoundDecl, Constructor,
15061                                Elidable, ExprArgs, HadMultipleCandidates,
15062                                IsListInitialization,
15063                                IsStdInitListInitialization, RequiresZeroInit,
15064                                ConstructKind, ParenRange);
15065 }
15066 
15067 ExprResult
15068 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15069                             NamedDecl *FoundDecl,
15070                             CXXConstructorDecl *Constructor,
15071                             bool Elidable,
15072                             MultiExprArg ExprArgs,
15073                             bool HadMultipleCandidates,
15074                             bool IsListInitialization,
15075                             bool IsStdInitListInitialization,
15076                             bool RequiresZeroInit,
15077                             unsigned ConstructKind,
15078                             SourceRange ParenRange) {
15079   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15080     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15081     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15082       return ExprError();
15083   }
15084 
15085   return BuildCXXConstructExpr(
15086       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15087       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15088       RequiresZeroInit, ConstructKind, ParenRange);
15089 }
15090 
15091 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15092 /// including handling of its default argument expressions.
15093 ExprResult
15094 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15095                             CXXConstructorDecl *Constructor,
15096                             bool Elidable,
15097                             MultiExprArg ExprArgs,
15098                             bool HadMultipleCandidates,
15099                             bool IsListInitialization,
15100                             bool IsStdInitListInitialization,
15101                             bool RequiresZeroInit,
15102                             unsigned ConstructKind,
15103                             SourceRange ParenRange) {
15104   assert(declaresSameEntity(
15105              Constructor->getParent(),
15106              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15107          "given constructor for wrong type");
15108   MarkFunctionReferenced(ConstructLoc, Constructor);
15109   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15110     return ExprError();
15111   if (getLangOpts().SYCLIsDevice &&
15112       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15113     return ExprError();
15114 
15115   return CheckForImmediateInvocation(
15116       CXXConstructExpr::Create(
15117           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15118           HadMultipleCandidates, IsListInitialization,
15119           IsStdInitListInitialization, RequiresZeroInit,
15120           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15121           ParenRange),
15122       Constructor);
15123 }
15124 
15125 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15126   assert(Field->hasInClassInitializer());
15127 
15128   // If we already have the in-class initializer nothing needs to be done.
15129   if (Field->getInClassInitializer())
15130     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15131 
15132   // If we might have already tried and failed to instantiate, don't try again.
15133   if (Field->isInvalidDecl())
15134     return ExprError();
15135 
15136   // Maybe we haven't instantiated the in-class initializer. Go check the
15137   // pattern FieldDecl to see if it has one.
15138   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15139 
15140   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15141     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15142     DeclContext::lookup_result Lookup =
15143         ClassPattern->lookup(Field->getDeclName());
15144 
15145     FieldDecl *Pattern = nullptr;
15146     for (auto L : Lookup) {
15147       if (isa<FieldDecl>(L)) {
15148         Pattern = cast<FieldDecl>(L);
15149         break;
15150       }
15151     }
15152     assert(Pattern && "We must have set the Pattern!");
15153 
15154     if (!Pattern->hasInClassInitializer() ||
15155         InstantiateInClassInitializer(Loc, Field, Pattern,
15156                                       getTemplateInstantiationArgs(Field))) {
15157       // Don't diagnose this again.
15158       Field->setInvalidDecl();
15159       return ExprError();
15160     }
15161     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15162   }
15163 
15164   // DR1351:
15165   //   If the brace-or-equal-initializer of a non-static data member
15166   //   invokes a defaulted default constructor of its class or of an
15167   //   enclosing class in a potentially evaluated subexpression, the
15168   //   program is ill-formed.
15169   //
15170   // This resolution is unworkable: the exception specification of the
15171   // default constructor can be needed in an unevaluated context, in
15172   // particular, in the operand of a noexcept-expression, and we can be
15173   // unable to compute an exception specification for an enclosed class.
15174   //
15175   // Any attempt to resolve the exception specification of a defaulted default
15176   // constructor before the initializer is lexically complete will ultimately
15177   // come here at which point we can diagnose it.
15178   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15179   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15180       << OutermostClass << Field;
15181   Diag(Field->getEndLoc(),
15182        diag::note_default_member_initializer_not_yet_parsed);
15183   // Recover by marking the field invalid, unless we're in a SFINAE context.
15184   if (!isSFINAEContext())
15185     Field->setInvalidDecl();
15186   return ExprError();
15187 }
15188 
15189 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15190   if (VD->isInvalidDecl()) return;
15191   // If initializing the variable failed, don't also diagnose problems with
15192   // the desctructor, they're likely related.
15193   if (VD->getInit() && VD->getInit()->containsErrors())
15194     return;
15195 
15196   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15197   if (ClassDecl->isInvalidDecl()) return;
15198   if (ClassDecl->hasIrrelevantDestructor()) return;
15199   if (ClassDecl->isDependentContext()) return;
15200 
15201   if (VD->isNoDestroy(getASTContext()))
15202     return;
15203 
15204   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15205 
15206   // If this is an array, we'll require the destructor during initialization, so
15207   // we can skip over this. We still want to emit exit-time destructor warnings
15208   // though.
15209   if (!VD->getType()->isArrayType()) {
15210     MarkFunctionReferenced(VD->getLocation(), Destructor);
15211     CheckDestructorAccess(VD->getLocation(), Destructor,
15212                           PDiag(diag::err_access_dtor_var)
15213                               << VD->getDeclName() << VD->getType());
15214     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15215   }
15216 
15217   if (Destructor->isTrivial()) return;
15218 
15219   // If the destructor is constexpr, check whether the variable has constant
15220   // destruction now.
15221   if (Destructor->isConstexpr()) {
15222     bool HasConstantInit = false;
15223     if (VD->getInit() && !VD->getInit()->isValueDependent())
15224       HasConstantInit = VD->evaluateValue();
15225     SmallVector<PartialDiagnosticAt, 8> Notes;
15226     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15227         HasConstantInit) {
15228       Diag(VD->getLocation(),
15229            diag::err_constexpr_var_requires_const_destruction) << VD;
15230       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15231         Diag(Notes[I].first, Notes[I].second);
15232     }
15233   }
15234 
15235   if (!VD->hasGlobalStorage()) return;
15236 
15237   // Emit warning for non-trivial dtor in global scope (a real global,
15238   // class-static, function-static).
15239   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15240 
15241   // TODO: this should be re-enabled for static locals by !CXAAtExit
15242   if (!VD->isStaticLocal())
15243     Diag(VD->getLocation(), diag::warn_global_destructor);
15244 }
15245 
15246 /// Given a constructor and the set of arguments provided for the
15247 /// constructor, convert the arguments and add any required default arguments
15248 /// to form a proper call to this constructor.
15249 ///
15250 /// \returns true if an error occurred, false otherwise.
15251 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15252                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15253                                    SourceLocation Loc,
15254                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15255                                    bool AllowExplicit,
15256                                    bool IsListInitialization) {
15257   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15258   unsigned NumArgs = ArgsPtr.size();
15259   Expr **Args = ArgsPtr.data();
15260 
15261   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15262   unsigned NumParams = Proto->getNumParams();
15263 
15264   // If too few arguments are available, we'll fill in the rest with defaults.
15265   if (NumArgs < NumParams)
15266     ConvertedArgs.reserve(NumParams);
15267   else
15268     ConvertedArgs.reserve(NumArgs);
15269 
15270   VariadicCallType CallType =
15271     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15272   SmallVector<Expr *, 8> AllArgs;
15273   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15274                                         Proto, 0,
15275                                         llvm::makeArrayRef(Args, NumArgs),
15276                                         AllArgs,
15277                                         CallType, AllowExplicit,
15278                                         IsListInitialization);
15279   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15280 
15281   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15282 
15283   CheckConstructorCall(Constructor, DeclInitType,
15284                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15285                        Proto, Loc);
15286 
15287   return Invalid;
15288 }
15289 
15290 static inline bool
15291 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15292                                        const FunctionDecl *FnDecl) {
15293   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15294   if (isa<NamespaceDecl>(DC)) {
15295     return SemaRef.Diag(FnDecl->getLocation(),
15296                         diag::err_operator_new_delete_declared_in_namespace)
15297       << FnDecl->getDeclName();
15298   }
15299 
15300   if (isa<TranslationUnitDecl>(DC) &&
15301       FnDecl->getStorageClass() == SC_Static) {
15302     return SemaRef.Diag(FnDecl->getLocation(),
15303                         diag::err_operator_new_delete_declared_static)
15304       << FnDecl->getDeclName();
15305   }
15306 
15307   return false;
15308 }
15309 
15310 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15311                                              const PointerType *PtrTy) {
15312   auto &Ctx = SemaRef.Context;
15313   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15314   PtrQuals.removeAddressSpace();
15315   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15316       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15317 }
15318 
15319 static inline bool
15320 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15321                             CanQualType ExpectedResultType,
15322                             CanQualType ExpectedFirstParamType,
15323                             unsigned DependentParamTypeDiag,
15324                             unsigned InvalidParamTypeDiag) {
15325   QualType ResultType =
15326       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15327 
15328   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15329     // The operator is valid on any address space for OpenCL.
15330     // Drop address space from actual and expected result types.
15331     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15332       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15333 
15334     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15335       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15336   }
15337 
15338   // Check that the result type is what we expect.
15339   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15340     // Reject even if the type is dependent; an operator delete function is
15341     // required to have a non-dependent result type.
15342     return SemaRef.Diag(
15343                FnDecl->getLocation(),
15344                ResultType->isDependentType()
15345                    ? diag::err_operator_new_delete_dependent_result_type
15346                    : diag::err_operator_new_delete_invalid_result_type)
15347            << FnDecl->getDeclName() << ExpectedResultType;
15348   }
15349 
15350   // A function template must have at least 2 parameters.
15351   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15352     return SemaRef.Diag(FnDecl->getLocation(),
15353                       diag::err_operator_new_delete_template_too_few_parameters)
15354         << FnDecl->getDeclName();
15355 
15356   // The function decl must have at least 1 parameter.
15357   if (FnDecl->getNumParams() == 0)
15358     return SemaRef.Diag(FnDecl->getLocation(),
15359                         diag::err_operator_new_delete_too_few_parameters)
15360       << FnDecl->getDeclName();
15361 
15362   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15363   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15364     // The operator is valid on any address space for OpenCL.
15365     // Drop address space from actual and expected first parameter types.
15366     if (const auto *PtrTy =
15367             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15368       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15369 
15370     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15371       ExpectedFirstParamType =
15372           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15373   }
15374 
15375   // Check that the first parameter type is what we expect.
15376   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15377       ExpectedFirstParamType) {
15378     // The first parameter type is not allowed to be dependent. As a tentative
15379     // DR resolution, we allow a dependent parameter type if it is the right
15380     // type anyway, to allow destroying operator delete in class templates.
15381     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15382                                                    ? DependentParamTypeDiag
15383                                                    : InvalidParamTypeDiag)
15384            << FnDecl->getDeclName() << ExpectedFirstParamType;
15385   }
15386 
15387   return false;
15388 }
15389 
15390 static bool
15391 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15392   // C++ [basic.stc.dynamic.allocation]p1:
15393   //   A program is ill-formed if an allocation function is declared in a
15394   //   namespace scope other than global scope or declared static in global
15395   //   scope.
15396   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15397     return true;
15398 
15399   CanQualType SizeTy =
15400     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15401 
15402   // C++ [basic.stc.dynamic.allocation]p1:
15403   //  The return type shall be void*. The first parameter shall have type
15404   //  std::size_t.
15405   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15406                                   SizeTy,
15407                                   diag::err_operator_new_dependent_param_type,
15408                                   diag::err_operator_new_param_type))
15409     return true;
15410 
15411   // C++ [basic.stc.dynamic.allocation]p1:
15412   //  The first parameter shall not have an associated default argument.
15413   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15414     return SemaRef.Diag(FnDecl->getLocation(),
15415                         diag::err_operator_new_default_arg)
15416       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15417 
15418   return false;
15419 }
15420 
15421 static bool
15422 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15423   // C++ [basic.stc.dynamic.deallocation]p1:
15424   //   A program is ill-formed if deallocation functions are declared in a
15425   //   namespace scope other than global scope or declared static in global
15426   //   scope.
15427   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15428     return true;
15429 
15430   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15431 
15432   // C++ P0722:
15433   //   Within a class C, the first parameter of a destroying operator delete
15434   //   shall be of type C *. The first parameter of any other deallocation
15435   //   function shall be of type void *.
15436   CanQualType ExpectedFirstParamType =
15437       MD && MD->isDestroyingOperatorDelete()
15438           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15439                 SemaRef.Context.getRecordType(MD->getParent())))
15440           : SemaRef.Context.VoidPtrTy;
15441 
15442   // C++ [basic.stc.dynamic.deallocation]p2:
15443   //   Each deallocation function shall return void
15444   if (CheckOperatorNewDeleteTypes(
15445           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15446           diag::err_operator_delete_dependent_param_type,
15447           diag::err_operator_delete_param_type))
15448     return true;
15449 
15450   // C++ P0722:
15451   //   A destroying operator delete shall be a usual deallocation function.
15452   if (MD && !MD->getParent()->isDependentContext() &&
15453       MD->isDestroyingOperatorDelete() &&
15454       !SemaRef.isUsualDeallocationFunction(MD)) {
15455     SemaRef.Diag(MD->getLocation(),
15456                  diag::err_destroying_operator_delete_not_usual);
15457     return true;
15458   }
15459 
15460   return false;
15461 }
15462 
15463 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15464 /// of this overloaded operator is well-formed. If so, returns false;
15465 /// otherwise, emits appropriate diagnostics and returns true.
15466 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15467   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15468          "Expected an overloaded operator declaration");
15469 
15470   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15471 
15472   // C++ [over.oper]p5:
15473   //   The allocation and deallocation functions, operator new,
15474   //   operator new[], operator delete and operator delete[], are
15475   //   described completely in 3.7.3. The attributes and restrictions
15476   //   found in the rest of this subclause do not apply to them unless
15477   //   explicitly stated in 3.7.3.
15478   if (Op == OO_Delete || Op == OO_Array_Delete)
15479     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15480 
15481   if (Op == OO_New || Op == OO_Array_New)
15482     return CheckOperatorNewDeclaration(*this, FnDecl);
15483 
15484   // C++ [over.oper]p6:
15485   //   An operator function shall either be a non-static member
15486   //   function or be a non-member function and have at least one
15487   //   parameter whose type is a class, a reference to a class, an
15488   //   enumeration, or a reference to an enumeration.
15489   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15490     if (MethodDecl->isStatic())
15491       return Diag(FnDecl->getLocation(),
15492                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15493   } else {
15494     bool ClassOrEnumParam = false;
15495     for (auto Param : FnDecl->parameters()) {
15496       QualType ParamType = Param->getType().getNonReferenceType();
15497       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15498           ParamType->isEnumeralType()) {
15499         ClassOrEnumParam = true;
15500         break;
15501       }
15502     }
15503 
15504     if (!ClassOrEnumParam)
15505       return Diag(FnDecl->getLocation(),
15506                   diag::err_operator_overload_needs_class_or_enum)
15507         << FnDecl->getDeclName();
15508   }
15509 
15510   // C++ [over.oper]p8:
15511   //   An operator function cannot have default arguments (8.3.6),
15512   //   except where explicitly stated below.
15513   //
15514   // Only the function-call operator allows default arguments
15515   // (C++ [over.call]p1).
15516   if (Op != OO_Call) {
15517     for (auto Param : FnDecl->parameters()) {
15518       if (Param->hasDefaultArg())
15519         return Diag(Param->getLocation(),
15520                     diag::err_operator_overload_default_arg)
15521           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15522     }
15523   }
15524 
15525   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15526     { false, false, false }
15527 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15528     , { Unary, Binary, MemberOnly }
15529 #include "clang/Basic/OperatorKinds.def"
15530   };
15531 
15532   bool CanBeUnaryOperator = OperatorUses[Op][0];
15533   bool CanBeBinaryOperator = OperatorUses[Op][1];
15534   bool MustBeMemberOperator = OperatorUses[Op][2];
15535 
15536   // C++ [over.oper]p8:
15537   //   [...] Operator functions cannot have more or fewer parameters
15538   //   than the number required for the corresponding operator, as
15539   //   described in the rest of this subclause.
15540   unsigned NumParams = FnDecl->getNumParams()
15541                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15542   if (Op != OO_Call &&
15543       ((NumParams == 1 && !CanBeUnaryOperator) ||
15544        (NumParams == 2 && !CanBeBinaryOperator) ||
15545        (NumParams < 1) || (NumParams > 2))) {
15546     // We have the wrong number of parameters.
15547     unsigned ErrorKind;
15548     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15549       ErrorKind = 2;  // 2 -> unary or binary.
15550     } else if (CanBeUnaryOperator) {
15551       ErrorKind = 0;  // 0 -> unary
15552     } else {
15553       assert(CanBeBinaryOperator &&
15554              "All non-call overloaded operators are unary or binary!");
15555       ErrorKind = 1;  // 1 -> binary
15556     }
15557 
15558     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15559       << FnDecl->getDeclName() << NumParams << ErrorKind;
15560   }
15561 
15562   // Overloaded operators other than operator() cannot be variadic.
15563   if (Op != OO_Call &&
15564       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15565     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15566       << FnDecl->getDeclName();
15567   }
15568 
15569   // Some operators must be non-static member functions.
15570   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15571     return Diag(FnDecl->getLocation(),
15572                 diag::err_operator_overload_must_be_member)
15573       << FnDecl->getDeclName();
15574   }
15575 
15576   // C++ [over.inc]p1:
15577   //   The user-defined function called operator++ implements the
15578   //   prefix and postfix ++ operator. If this function is a member
15579   //   function with no parameters, or a non-member function with one
15580   //   parameter of class or enumeration type, it defines the prefix
15581   //   increment operator ++ for objects of that type. If the function
15582   //   is a member function with one parameter (which shall be of type
15583   //   int) or a non-member function with two parameters (the second
15584   //   of which shall be of type int), it defines the postfix
15585   //   increment operator ++ for objects of that type.
15586   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15587     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15588     QualType ParamType = LastParam->getType();
15589 
15590     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15591         !ParamType->isDependentType())
15592       return Diag(LastParam->getLocation(),
15593                   diag::err_operator_overload_post_incdec_must_be_int)
15594         << LastParam->getType() << (Op == OO_MinusMinus);
15595   }
15596 
15597   return false;
15598 }
15599 
15600 static bool
15601 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15602                                           FunctionTemplateDecl *TpDecl) {
15603   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15604 
15605   // Must have one or two template parameters.
15606   if (TemplateParams->size() == 1) {
15607     NonTypeTemplateParmDecl *PmDecl =
15608         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15609 
15610     // The template parameter must be a char parameter pack.
15611     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15612         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15613       return false;
15614 
15615     // C++20 [over.literal]p5:
15616     //   A string literal operator template is a literal operator template
15617     //   whose template-parameter-list comprises a single non-type
15618     //   template-parameter of class type.
15619     //
15620     // As a DR resolution, we also allow placeholders for deduced class
15621     // template specializations.
15622     if (SemaRef.getLangOpts().CPlusPlus20 &&
15623         !PmDecl->isTemplateParameterPack() &&
15624         (PmDecl->getType()->isRecordType() ||
15625          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15626       return false;
15627   } else if (TemplateParams->size() == 2) {
15628     TemplateTypeParmDecl *PmType =
15629         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15630     NonTypeTemplateParmDecl *PmArgs =
15631         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15632 
15633     // The second template parameter must be a parameter pack with the
15634     // first template parameter as its type.
15635     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15636         PmArgs->isTemplateParameterPack()) {
15637       const TemplateTypeParmType *TArgs =
15638           PmArgs->getType()->getAs<TemplateTypeParmType>();
15639       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15640           TArgs->getIndex() == PmType->getIndex()) {
15641         if (!SemaRef.inTemplateInstantiation())
15642           SemaRef.Diag(TpDecl->getLocation(),
15643                        diag::ext_string_literal_operator_template);
15644         return false;
15645       }
15646     }
15647   }
15648 
15649   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15650                diag::err_literal_operator_template)
15651       << TpDecl->getTemplateParameters()->getSourceRange();
15652   return true;
15653 }
15654 
15655 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15656 /// of this literal operator function is well-formed. If so, returns
15657 /// false; otherwise, emits appropriate diagnostics and returns true.
15658 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15659   if (isa<CXXMethodDecl>(FnDecl)) {
15660     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15661       << FnDecl->getDeclName();
15662     return true;
15663   }
15664 
15665   if (FnDecl->isExternC()) {
15666     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15667     if (const LinkageSpecDecl *LSD =
15668             FnDecl->getDeclContext()->getExternCContext())
15669       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15670     return true;
15671   }
15672 
15673   // This might be the definition of a literal operator template.
15674   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15675 
15676   // This might be a specialization of a literal operator template.
15677   if (!TpDecl)
15678     TpDecl = FnDecl->getPrimaryTemplate();
15679 
15680   // template <char...> type operator "" name() and
15681   // template <class T, T...> type operator "" name() are the only valid
15682   // template signatures, and the only valid signatures with no parameters.
15683   //
15684   // C++20 also allows template <SomeClass T> type operator "" name().
15685   if (TpDecl) {
15686     if (FnDecl->param_size() != 0) {
15687       Diag(FnDecl->getLocation(),
15688            diag::err_literal_operator_template_with_params);
15689       return true;
15690     }
15691 
15692     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15693       return true;
15694 
15695   } else if (FnDecl->param_size() == 1) {
15696     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15697 
15698     QualType ParamType = Param->getType().getUnqualifiedType();
15699 
15700     // Only unsigned long long int, long double, any character type, and const
15701     // char * are allowed as the only parameters.
15702     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15703         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15704         Context.hasSameType(ParamType, Context.CharTy) ||
15705         Context.hasSameType(ParamType, Context.WideCharTy) ||
15706         Context.hasSameType(ParamType, Context.Char8Ty) ||
15707         Context.hasSameType(ParamType, Context.Char16Ty) ||
15708         Context.hasSameType(ParamType, Context.Char32Ty)) {
15709     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15710       QualType InnerType = Ptr->getPointeeType();
15711 
15712       // Pointer parameter must be a const char *.
15713       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15714                                 Context.CharTy) &&
15715             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15716         Diag(Param->getSourceRange().getBegin(),
15717              diag::err_literal_operator_param)
15718             << ParamType << "'const char *'" << Param->getSourceRange();
15719         return true;
15720       }
15721 
15722     } else if (ParamType->isRealFloatingType()) {
15723       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15724           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15725       return true;
15726 
15727     } else if (ParamType->isIntegerType()) {
15728       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15729           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15730       return true;
15731 
15732     } else {
15733       Diag(Param->getSourceRange().getBegin(),
15734            diag::err_literal_operator_invalid_param)
15735           << ParamType << Param->getSourceRange();
15736       return true;
15737     }
15738 
15739   } else if (FnDecl->param_size() == 2) {
15740     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15741 
15742     // First, verify that the first parameter is correct.
15743 
15744     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15745 
15746     // Two parameter function must have a pointer to const as a
15747     // first parameter; let's strip those qualifiers.
15748     const PointerType *PT = FirstParamType->getAs<PointerType>();
15749 
15750     if (!PT) {
15751       Diag((*Param)->getSourceRange().getBegin(),
15752            diag::err_literal_operator_param)
15753           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15754       return true;
15755     }
15756 
15757     QualType PointeeType = PT->getPointeeType();
15758     // First parameter must be const
15759     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15760       Diag((*Param)->getSourceRange().getBegin(),
15761            diag::err_literal_operator_param)
15762           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15763       return true;
15764     }
15765 
15766     QualType InnerType = PointeeType.getUnqualifiedType();
15767     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15768     // const char32_t* are allowed as the first parameter to a two-parameter
15769     // function
15770     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15771           Context.hasSameType(InnerType, Context.WideCharTy) ||
15772           Context.hasSameType(InnerType, Context.Char8Ty) ||
15773           Context.hasSameType(InnerType, Context.Char16Ty) ||
15774           Context.hasSameType(InnerType, Context.Char32Ty))) {
15775       Diag((*Param)->getSourceRange().getBegin(),
15776            diag::err_literal_operator_param)
15777           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15778       return true;
15779     }
15780 
15781     // Move on to the second and final parameter.
15782     ++Param;
15783 
15784     // The second parameter must be a std::size_t.
15785     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15786     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15787       Diag((*Param)->getSourceRange().getBegin(),
15788            diag::err_literal_operator_param)
15789           << SecondParamType << Context.getSizeType()
15790           << (*Param)->getSourceRange();
15791       return true;
15792     }
15793   } else {
15794     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15795     return true;
15796   }
15797 
15798   // Parameters are good.
15799 
15800   // A parameter-declaration-clause containing a default argument is not
15801   // equivalent to any of the permitted forms.
15802   for (auto Param : FnDecl->parameters()) {
15803     if (Param->hasDefaultArg()) {
15804       Diag(Param->getDefaultArgRange().getBegin(),
15805            diag::err_literal_operator_default_argument)
15806         << Param->getDefaultArgRange();
15807       break;
15808     }
15809   }
15810 
15811   StringRef LiteralName
15812     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15813   if (LiteralName[0] != '_' &&
15814       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15815     // C++11 [usrlit.suffix]p1:
15816     //   Literal suffix identifiers that do not start with an underscore
15817     //   are reserved for future standardization.
15818     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15819       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15820   }
15821 
15822   return false;
15823 }
15824 
15825 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15826 /// linkage specification, including the language and (if present)
15827 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15828 /// language string literal. LBraceLoc, if valid, provides the location of
15829 /// the '{' brace. Otherwise, this linkage specification does not
15830 /// have any braces.
15831 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15832                                            Expr *LangStr,
15833                                            SourceLocation LBraceLoc) {
15834   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15835   if (!Lit->isAscii()) {
15836     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15837       << LangStr->getSourceRange();
15838     return nullptr;
15839   }
15840 
15841   StringRef Lang = Lit->getString();
15842   LinkageSpecDecl::LanguageIDs Language;
15843   if (Lang == "C")
15844     Language = LinkageSpecDecl::lang_c;
15845   else if (Lang == "C++")
15846     Language = LinkageSpecDecl::lang_cxx;
15847   else {
15848     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15849       << LangStr->getSourceRange();
15850     return nullptr;
15851   }
15852 
15853   // FIXME: Add all the various semantics of linkage specifications
15854 
15855   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15856                                                LangStr->getExprLoc(), Language,
15857                                                LBraceLoc.isValid());
15858   CurContext->addDecl(D);
15859   PushDeclContext(S, D);
15860   return D;
15861 }
15862 
15863 /// ActOnFinishLinkageSpecification - Complete the definition of
15864 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15865 /// valid, it's the position of the closing '}' brace in a linkage
15866 /// specification that uses braces.
15867 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15868                                             Decl *LinkageSpec,
15869                                             SourceLocation RBraceLoc) {
15870   if (RBraceLoc.isValid()) {
15871     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15872     LSDecl->setRBraceLoc(RBraceLoc);
15873   }
15874   PopDeclContext();
15875   return LinkageSpec;
15876 }
15877 
15878 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15879                                   const ParsedAttributesView &AttrList,
15880                                   SourceLocation SemiLoc) {
15881   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15882   // Attribute declarations appertain to empty declaration so we handle
15883   // them here.
15884   ProcessDeclAttributeList(S, ED, AttrList);
15885 
15886   CurContext->addDecl(ED);
15887   return ED;
15888 }
15889 
15890 /// Perform semantic analysis for the variable declaration that
15891 /// occurs within a C++ catch clause, returning the newly-created
15892 /// variable.
15893 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15894                                          TypeSourceInfo *TInfo,
15895                                          SourceLocation StartLoc,
15896                                          SourceLocation Loc,
15897                                          IdentifierInfo *Name) {
15898   bool Invalid = false;
15899   QualType ExDeclType = TInfo->getType();
15900 
15901   // Arrays and functions decay.
15902   if (ExDeclType->isArrayType())
15903     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15904   else if (ExDeclType->isFunctionType())
15905     ExDeclType = Context.getPointerType(ExDeclType);
15906 
15907   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15908   // The exception-declaration shall not denote a pointer or reference to an
15909   // incomplete type, other than [cv] void*.
15910   // N2844 forbids rvalue references.
15911   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15912     Diag(Loc, diag::err_catch_rvalue_ref);
15913     Invalid = true;
15914   }
15915 
15916   if (ExDeclType->isVariablyModifiedType()) {
15917     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15918     Invalid = true;
15919   }
15920 
15921   QualType BaseType = ExDeclType;
15922   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15923   unsigned DK = diag::err_catch_incomplete;
15924   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15925     BaseType = Ptr->getPointeeType();
15926     Mode = 1;
15927     DK = diag::err_catch_incomplete_ptr;
15928   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15929     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15930     BaseType = Ref->getPointeeType();
15931     Mode = 2;
15932     DK = diag::err_catch_incomplete_ref;
15933   }
15934   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15935       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15936     Invalid = true;
15937 
15938   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15939     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15940     Invalid = true;
15941   }
15942 
15943   if (!Invalid && !ExDeclType->isDependentType() &&
15944       RequireNonAbstractType(Loc, ExDeclType,
15945                              diag::err_abstract_type_in_decl,
15946                              AbstractVariableType))
15947     Invalid = true;
15948 
15949   // Only the non-fragile NeXT runtime currently supports C++ catches
15950   // of ObjC types, and no runtime supports catching ObjC types by value.
15951   if (!Invalid && getLangOpts().ObjC) {
15952     QualType T = ExDeclType;
15953     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15954       T = RT->getPointeeType();
15955 
15956     if (T->isObjCObjectType()) {
15957       Diag(Loc, diag::err_objc_object_catch);
15958       Invalid = true;
15959     } else if (T->isObjCObjectPointerType()) {
15960       // FIXME: should this be a test for macosx-fragile specifically?
15961       if (getLangOpts().ObjCRuntime.isFragile())
15962         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15963     }
15964   }
15965 
15966   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15967                                     ExDeclType, TInfo, SC_None);
15968   ExDecl->setExceptionVariable(true);
15969 
15970   // In ARC, infer 'retaining' for variables of retainable type.
15971   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15972     Invalid = true;
15973 
15974   if (!Invalid && !ExDeclType->isDependentType()) {
15975     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15976       // Insulate this from anything else we might currently be parsing.
15977       EnterExpressionEvaluationContext scope(
15978           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15979 
15980       // C++ [except.handle]p16:
15981       //   The object declared in an exception-declaration or, if the
15982       //   exception-declaration does not specify a name, a temporary (12.2) is
15983       //   copy-initialized (8.5) from the exception object. [...]
15984       //   The object is destroyed when the handler exits, after the destruction
15985       //   of any automatic objects initialized within the handler.
15986       //
15987       // We just pretend to initialize the object with itself, then make sure
15988       // it can be destroyed later.
15989       QualType initType = Context.getExceptionObjectType(ExDeclType);
15990 
15991       InitializedEntity entity =
15992         InitializedEntity::InitializeVariable(ExDecl);
15993       InitializationKind initKind =
15994         InitializationKind::CreateCopy(Loc, SourceLocation());
15995 
15996       Expr *opaqueValue =
15997         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15998       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15999       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16000       if (result.isInvalid())
16001         Invalid = true;
16002       else {
16003         // If the constructor used was non-trivial, set this as the
16004         // "initializer".
16005         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16006         if (!construct->getConstructor()->isTrivial()) {
16007           Expr *init = MaybeCreateExprWithCleanups(construct);
16008           ExDecl->setInit(init);
16009         }
16010 
16011         // And make sure it's destructable.
16012         FinalizeVarWithDestructor(ExDecl, recordType);
16013       }
16014     }
16015   }
16016 
16017   if (Invalid)
16018     ExDecl->setInvalidDecl();
16019 
16020   return ExDecl;
16021 }
16022 
16023 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16024 /// handler.
16025 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16026   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16027   bool Invalid = D.isInvalidType();
16028 
16029   // Check for unexpanded parameter packs.
16030   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16031                                       UPPC_ExceptionType)) {
16032     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16033                                              D.getIdentifierLoc());
16034     Invalid = true;
16035   }
16036 
16037   IdentifierInfo *II = D.getIdentifier();
16038   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16039                                              LookupOrdinaryName,
16040                                              ForVisibleRedeclaration)) {
16041     // The scope should be freshly made just for us. There is just no way
16042     // it contains any previous declaration, except for function parameters in
16043     // a function-try-block's catch statement.
16044     assert(!S->isDeclScope(PrevDecl));
16045     if (isDeclInScope(PrevDecl, CurContext, S)) {
16046       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16047         << D.getIdentifier();
16048       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16049       Invalid = true;
16050     } else if (PrevDecl->isTemplateParameter())
16051       // Maybe we will complain about the shadowed template parameter.
16052       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16053   }
16054 
16055   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16056     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16057       << D.getCXXScopeSpec().getRange();
16058     Invalid = true;
16059   }
16060 
16061   VarDecl *ExDecl = BuildExceptionDeclaration(
16062       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16063   if (Invalid)
16064     ExDecl->setInvalidDecl();
16065 
16066   // Add the exception declaration into this scope.
16067   if (II)
16068     PushOnScopeChains(ExDecl, S);
16069   else
16070     CurContext->addDecl(ExDecl);
16071 
16072   ProcessDeclAttributes(S, ExDecl, D);
16073   return ExDecl;
16074 }
16075 
16076 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16077                                          Expr *AssertExpr,
16078                                          Expr *AssertMessageExpr,
16079                                          SourceLocation RParenLoc) {
16080   StringLiteral *AssertMessage =
16081       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16082 
16083   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16084     return nullptr;
16085 
16086   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16087                                       AssertMessage, RParenLoc, false);
16088 }
16089 
16090 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16091                                          Expr *AssertExpr,
16092                                          StringLiteral *AssertMessage,
16093                                          SourceLocation RParenLoc,
16094                                          bool Failed) {
16095   assert(AssertExpr != nullptr && "Expected non-null condition");
16096   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16097       !Failed) {
16098     // In a static_assert-declaration, the constant-expression shall be a
16099     // constant expression that can be contextually converted to bool.
16100     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16101     if (Converted.isInvalid())
16102       Failed = true;
16103 
16104     ExprResult FullAssertExpr =
16105         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16106                             /*DiscardedValue*/ false,
16107                             /*IsConstexpr*/ true);
16108     if (FullAssertExpr.isInvalid())
16109       Failed = true;
16110     else
16111       AssertExpr = FullAssertExpr.get();
16112 
16113     llvm::APSInt Cond;
16114     if (!Failed && VerifyIntegerConstantExpression(
16115                        AssertExpr, &Cond,
16116                        diag::err_static_assert_expression_is_not_constant)
16117                        .isInvalid())
16118       Failed = true;
16119 
16120     if (!Failed && !Cond) {
16121       SmallString<256> MsgBuffer;
16122       llvm::raw_svector_ostream Msg(MsgBuffer);
16123       if (AssertMessage)
16124         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16125 
16126       Expr *InnerCond = nullptr;
16127       std::string InnerCondDescription;
16128       std::tie(InnerCond, InnerCondDescription) =
16129         findFailedBooleanCondition(Converted.get());
16130       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16131         // Drill down into concept specialization expressions to see why they
16132         // weren't satisfied.
16133         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16134           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16135         ConstraintSatisfaction Satisfaction;
16136         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16137           DiagnoseUnsatisfiedConstraint(Satisfaction);
16138       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16139                            && !isa<IntegerLiteral>(InnerCond)) {
16140         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16141           << InnerCondDescription << !AssertMessage
16142           << Msg.str() << InnerCond->getSourceRange();
16143       } else {
16144         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16145           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16146       }
16147       Failed = true;
16148     }
16149   } else {
16150     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16151                                                     /*DiscardedValue*/false,
16152                                                     /*IsConstexpr*/true);
16153     if (FullAssertExpr.isInvalid())
16154       Failed = true;
16155     else
16156       AssertExpr = FullAssertExpr.get();
16157   }
16158 
16159   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16160                                         AssertExpr, AssertMessage, RParenLoc,
16161                                         Failed);
16162 
16163   CurContext->addDecl(Decl);
16164   return Decl;
16165 }
16166 
16167 /// Perform semantic analysis of the given friend type declaration.
16168 ///
16169 /// \returns A friend declaration that.
16170 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16171                                       SourceLocation FriendLoc,
16172                                       TypeSourceInfo *TSInfo) {
16173   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16174 
16175   QualType T = TSInfo->getType();
16176   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16177 
16178   // C++03 [class.friend]p2:
16179   //   An elaborated-type-specifier shall be used in a friend declaration
16180   //   for a class.*
16181   //
16182   //   * The class-key of the elaborated-type-specifier is required.
16183   if (!CodeSynthesisContexts.empty()) {
16184     // Do not complain about the form of friend template types during any kind
16185     // of code synthesis. For template instantiation, we will have complained
16186     // when the template was defined.
16187   } else {
16188     if (!T->isElaboratedTypeSpecifier()) {
16189       // If we evaluated the type to a record type, suggest putting
16190       // a tag in front.
16191       if (const RecordType *RT = T->getAs<RecordType>()) {
16192         RecordDecl *RD = RT->getDecl();
16193 
16194         SmallString<16> InsertionText(" ");
16195         InsertionText += RD->getKindName();
16196 
16197         Diag(TypeRange.getBegin(),
16198              getLangOpts().CPlusPlus11 ?
16199                diag::warn_cxx98_compat_unelaborated_friend_type :
16200                diag::ext_unelaborated_friend_type)
16201           << (unsigned) RD->getTagKind()
16202           << T
16203           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16204                                         InsertionText);
16205       } else {
16206         Diag(FriendLoc,
16207              getLangOpts().CPlusPlus11 ?
16208                diag::warn_cxx98_compat_nonclass_type_friend :
16209                diag::ext_nonclass_type_friend)
16210           << T
16211           << TypeRange;
16212       }
16213     } else if (T->getAs<EnumType>()) {
16214       Diag(FriendLoc,
16215            getLangOpts().CPlusPlus11 ?
16216              diag::warn_cxx98_compat_enum_friend :
16217              diag::ext_enum_friend)
16218         << T
16219         << TypeRange;
16220     }
16221 
16222     // C++11 [class.friend]p3:
16223     //   A friend declaration that does not declare a function shall have one
16224     //   of the following forms:
16225     //     friend elaborated-type-specifier ;
16226     //     friend simple-type-specifier ;
16227     //     friend typename-specifier ;
16228     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16229       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16230   }
16231 
16232   //   If the type specifier in a friend declaration designates a (possibly
16233   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16234   //   the friend declaration is ignored.
16235   return FriendDecl::Create(Context, CurContext,
16236                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16237                             FriendLoc);
16238 }
16239 
16240 /// Handle a friend tag declaration where the scope specifier was
16241 /// templated.
16242 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16243                                     unsigned TagSpec, SourceLocation TagLoc,
16244                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16245                                     SourceLocation NameLoc,
16246                                     const ParsedAttributesView &Attr,
16247                                     MultiTemplateParamsArg TempParamLists) {
16248   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16249 
16250   bool IsMemberSpecialization = false;
16251   bool Invalid = false;
16252 
16253   if (TemplateParameterList *TemplateParams =
16254           MatchTemplateParametersToScopeSpecifier(
16255               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16256               IsMemberSpecialization, Invalid)) {
16257     if (TemplateParams->size() > 0) {
16258       // This is a declaration of a class template.
16259       if (Invalid)
16260         return nullptr;
16261 
16262       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16263                                 NameLoc, Attr, TemplateParams, AS_public,
16264                                 /*ModulePrivateLoc=*/SourceLocation(),
16265                                 FriendLoc, TempParamLists.size() - 1,
16266                                 TempParamLists.data()).get();
16267     } else {
16268       // The "template<>" header is extraneous.
16269       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16270         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16271       IsMemberSpecialization = true;
16272     }
16273   }
16274 
16275   if (Invalid) return nullptr;
16276 
16277   bool isAllExplicitSpecializations = true;
16278   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16279     if (TempParamLists[I]->size()) {
16280       isAllExplicitSpecializations = false;
16281       break;
16282     }
16283   }
16284 
16285   // FIXME: don't ignore attributes.
16286 
16287   // If it's explicit specializations all the way down, just forget
16288   // about the template header and build an appropriate non-templated
16289   // friend.  TODO: for source fidelity, remember the headers.
16290   if (isAllExplicitSpecializations) {
16291     if (SS.isEmpty()) {
16292       bool Owned = false;
16293       bool IsDependent = false;
16294       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16295                       Attr, AS_public,
16296                       /*ModulePrivateLoc=*/SourceLocation(),
16297                       MultiTemplateParamsArg(), Owned, IsDependent,
16298                       /*ScopedEnumKWLoc=*/SourceLocation(),
16299                       /*ScopedEnumUsesClassTag=*/false,
16300                       /*UnderlyingType=*/TypeResult(),
16301                       /*IsTypeSpecifier=*/false,
16302                       /*IsTemplateParamOrArg=*/false);
16303     }
16304 
16305     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16306     ElaboratedTypeKeyword Keyword
16307       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16308     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16309                                    *Name, NameLoc);
16310     if (T.isNull())
16311       return nullptr;
16312 
16313     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16314     if (isa<DependentNameType>(T)) {
16315       DependentNameTypeLoc TL =
16316           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16317       TL.setElaboratedKeywordLoc(TagLoc);
16318       TL.setQualifierLoc(QualifierLoc);
16319       TL.setNameLoc(NameLoc);
16320     } else {
16321       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16322       TL.setElaboratedKeywordLoc(TagLoc);
16323       TL.setQualifierLoc(QualifierLoc);
16324       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16325     }
16326 
16327     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16328                                             TSI, FriendLoc, TempParamLists);
16329     Friend->setAccess(AS_public);
16330     CurContext->addDecl(Friend);
16331     return Friend;
16332   }
16333 
16334   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16335 
16336 
16337 
16338   // Handle the case of a templated-scope friend class.  e.g.
16339   //   template <class T> class A<T>::B;
16340   // FIXME: we don't support these right now.
16341   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16342     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16343   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16344   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16345   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16346   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16347   TL.setElaboratedKeywordLoc(TagLoc);
16348   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16349   TL.setNameLoc(NameLoc);
16350 
16351   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16352                                           TSI, FriendLoc, TempParamLists);
16353   Friend->setAccess(AS_public);
16354   Friend->setUnsupportedFriend(true);
16355   CurContext->addDecl(Friend);
16356   return Friend;
16357 }
16358 
16359 /// Handle a friend type declaration.  This works in tandem with
16360 /// ActOnTag.
16361 ///
16362 /// Notes on friend class templates:
16363 ///
16364 /// We generally treat friend class declarations as if they were
16365 /// declaring a class.  So, for example, the elaborated type specifier
16366 /// in a friend declaration is required to obey the restrictions of a
16367 /// class-head (i.e. no typedefs in the scope chain), template
16368 /// parameters are required to match up with simple template-ids, &c.
16369 /// However, unlike when declaring a template specialization, it's
16370 /// okay to refer to a template specialization without an empty
16371 /// template parameter declaration, e.g.
16372 ///   friend class A<T>::B<unsigned>;
16373 /// We permit this as a special case; if there are any template
16374 /// parameters present at all, require proper matching, i.e.
16375 ///   template <> template \<class T> friend class A<int>::B;
16376 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16377                                 MultiTemplateParamsArg TempParams) {
16378   SourceLocation Loc = DS.getBeginLoc();
16379 
16380   assert(DS.isFriendSpecified());
16381   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16382 
16383   // C++ [class.friend]p3:
16384   // A friend declaration that does not declare a function shall have one of
16385   // the following forms:
16386   //     friend elaborated-type-specifier ;
16387   //     friend simple-type-specifier ;
16388   //     friend typename-specifier ;
16389   //
16390   // Any declaration with a type qualifier does not have that form. (It's
16391   // legal to specify a qualified type as a friend, you just can't write the
16392   // keywords.)
16393   if (DS.getTypeQualifiers()) {
16394     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16395       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16396     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16397       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16398     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16399       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16400     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16401       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16402     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16403       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16404   }
16405 
16406   // Try to convert the decl specifier to a type.  This works for
16407   // friend templates because ActOnTag never produces a ClassTemplateDecl
16408   // for a TUK_Friend.
16409   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16410   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16411   QualType T = TSI->getType();
16412   if (TheDeclarator.isInvalidType())
16413     return nullptr;
16414 
16415   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16416     return nullptr;
16417 
16418   // This is definitely an error in C++98.  It's probably meant to
16419   // be forbidden in C++0x, too, but the specification is just
16420   // poorly written.
16421   //
16422   // The problem is with declarations like the following:
16423   //   template <T> friend A<T>::foo;
16424   // where deciding whether a class C is a friend or not now hinges
16425   // on whether there exists an instantiation of A that causes
16426   // 'foo' to equal C.  There are restrictions on class-heads
16427   // (which we declare (by fiat) elaborated friend declarations to
16428   // be) that makes this tractable.
16429   //
16430   // FIXME: handle "template <> friend class A<T>;", which
16431   // is possibly well-formed?  Who even knows?
16432   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16433     Diag(Loc, diag::err_tagless_friend_type_template)
16434       << DS.getSourceRange();
16435     return nullptr;
16436   }
16437 
16438   // C++98 [class.friend]p1: A friend of a class is a function
16439   //   or class that is not a member of the class . . .
16440   // This is fixed in DR77, which just barely didn't make the C++03
16441   // deadline.  It's also a very silly restriction that seriously
16442   // affects inner classes and which nobody else seems to implement;
16443   // thus we never diagnose it, not even in -pedantic.
16444   //
16445   // But note that we could warn about it: it's always useless to
16446   // friend one of your own members (it's not, however, worthless to
16447   // friend a member of an arbitrary specialization of your template).
16448 
16449   Decl *D;
16450   if (!TempParams.empty())
16451     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16452                                    TempParams,
16453                                    TSI,
16454                                    DS.getFriendSpecLoc());
16455   else
16456     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16457 
16458   if (!D)
16459     return nullptr;
16460 
16461   D->setAccess(AS_public);
16462   CurContext->addDecl(D);
16463 
16464   return D;
16465 }
16466 
16467 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16468                                         MultiTemplateParamsArg TemplateParams) {
16469   const DeclSpec &DS = D.getDeclSpec();
16470 
16471   assert(DS.isFriendSpecified());
16472   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16473 
16474   SourceLocation Loc = D.getIdentifierLoc();
16475   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16476 
16477   // C++ [class.friend]p1
16478   //   A friend of a class is a function or class....
16479   // Note that this sees through typedefs, which is intended.
16480   // It *doesn't* see through dependent types, which is correct
16481   // according to [temp.arg.type]p3:
16482   //   If a declaration acquires a function type through a
16483   //   type dependent on a template-parameter and this causes
16484   //   a declaration that does not use the syntactic form of a
16485   //   function declarator to have a function type, the program
16486   //   is ill-formed.
16487   if (!TInfo->getType()->isFunctionType()) {
16488     Diag(Loc, diag::err_unexpected_friend);
16489 
16490     // It might be worthwhile to try to recover by creating an
16491     // appropriate declaration.
16492     return nullptr;
16493   }
16494 
16495   // C++ [namespace.memdef]p3
16496   //  - If a friend declaration in a non-local class first declares a
16497   //    class or function, the friend class or function is a member
16498   //    of the innermost enclosing namespace.
16499   //  - The name of the friend is not found by simple name lookup
16500   //    until a matching declaration is provided in that namespace
16501   //    scope (either before or after the class declaration granting
16502   //    friendship).
16503   //  - If a friend function is called, its name may be found by the
16504   //    name lookup that considers functions from namespaces and
16505   //    classes associated with the types of the function arguments.
16506   //  - When looking for a prior declaration of a class or a function
16507   //    declared as a friend, scopes outside the innermost enclosing
16508   //    namespace scope are not considered.
16509 
16510   CXXScopeSpec &SS = D.getCXXScopeSpec();
16511   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16512   assert(NameInfo.getName());
16513 
16514   // Check for unexpanded parameter packs.
16515   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16516       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16517       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16518     return nullptr;
16519 
16520   // The context we found the declaration in, or in which we should
16521   // create the declaration.
16522   DeclContext *DC;
16523   Scope *DCScope = S;
16524   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16525                         ForExternalRedeclaration);
16526 
16527   // There are five cases here.
16528   //   - There's no scope specifier and we're in a local class. Only look
16529   //     for functions declared in the immediately-enclosing block scope.
16530   // We recover from invalid scope qualifiers as if they just weren't there.
16531   FunctionDecl *FunctionContainingLocalClass = nullptr;
16532   if ((SS.isInvalid() || !SS.isSet()) &&
16533       (FunctionContainingLocalClass =
16534            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16535     // C++11 [class.friend]p11:
16536     //   If a friend declaration appears in a local class and the name
16537     //   specified is an unqualified name, a prior declaration is
16538     //   looked up without considering scopes that are outside the
16539     //   innermost enclosing non-class scope. For a friend function
16540     //   declaration, if there is no prior declaration, the program is
16541     //   ill-formed.
16542 
16543     // Find the innermost enclosing non-class scope. This is the block
16544     // scope containing the local class definition (or for a nested class,
16545     // the outer local class).
16546     DCScope = S->getFnParent();
16547 
16548     // Look up the function name in the scope.
16549     Previous.clear(LookupLocalFriendName);
16550     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16551 
16552     if (!Previous.empty()) {
16553       // All possible previous declarations must have the same context:
16554       // either they were declared at block scope or they are members of
16555       // one of the enclosing local classes.
16556       DC = Previous.getRepresentativeDecl()->getDeclContext();
16557     } else {
16558       // This is ill-formed, but provide the context that we would have
16559       // declared the function in, if we were permitted to, for error recovery.
16560       DC = FunctionContainingLocalClass;
16561     }
16562     adjustContextForLocalExternDecl(DC);
16563 
16564     // C++ [class.friend]p6:
16565     //   A function can be defined in a friend declaration of a class if and
16566     //   only if the class is a non-local class (9.8), the function name is
16567     //   unqualified, and the function has namespace scope.
16568     if (D.isFunctionDefinition()) {
16569       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16570     }
16571 
16572   //   - There's no scope specifier, in which case we just go to the
16573   //     appropriate scope and look for a function or function template
16574   //     there as appropriate.
16575   } else if (SS.isInvalid() || !SS.isSet()) {
16576     // C++11 [namespace.memdef]p3:
16577     //   If the name in a friend declaration is neither qualified nor
16578     //   a template-id and the declaration is a function or an
16579     //   elaborated-type-specifier, the lookup to determine whether
16580     //   the entity has been previously declared shall not consider
16581     //   any scopes outside the innermost enclosing namespace.
16582     bool isTemplateId =
16583         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16584 
16585     // Find the appropriate context according to the above.
16586     DC = CurContext;
16587 
16588     // Skip class contexts.  If someone can cite chapter and verse
16589     // for this behavior, that would be nice --- it's what GCC and
16590     // EDG do, and it seems like a reasonable intent, but the spec
16591     // really only says that checks for unqualified existing
16592     // declarations should stop at the nearest enclosing namespace,
16593     // not that they should only consider the nearest enclosing
16594     // namespace.
16595     while (DC->isRecord())
16596       DC = DC->getParent();
16597 
16598     DeclContext *LookupDC = DC;
16599     while (LookupDC->isTransparentContext())
16600       LookupDC = LookupDC->getParent();
16601 
16602     while (true) {
16603       LookupQualifiedName(Previous, LookupDC);
16604 
16605       if (!Previous.empty()) {
16606         DC = LookupDC;
16607         break;
16608       }
16609 
16610       if (isTemplateId) {
16611         if (isa<TranslationUnitDecl>(LookupDC)) break;
16612       } else {
16613         if (LookupDC->isFileContext()) break;
16614       }
16615       LookupDC = LookupDC->getParent();
16616     }
16617 
16618     DCScope = getScopeForDeclContext(S, DC);
16619 
16620   //   - There's a non-dependent scope specifier, in which case we
16621   //     compute it and do a previous lookup there for a function
16622   //     or function template.
16623   } else if (!SS.getScopeRep()->isDependent()) {
16624     DC = computeDeclContext(SS);
16625     if (!DC) return nullptr;
16626 
16627     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16628 
16629     LookupQualifiedName(Previous, DC);
16630 
16631     // C++ [class.friend]p1: A friend of a class is a function or
16632     //   class that is not a member of the class . . .
16633     if (DC->Equals(CurContext))
16634       Diag(DS.getFriendSpecLoc(),
16635            getLangOpts().CPlusPlus11 ?
16636              diag::warn_cxx98_compat_friend_is_member :
16637              diag::err_friend_is_member);
16638 
16639     if (D.isFunctionDefinition()) {
16640       // C++ [class.friend]p6:
16641       //   A function can be defined in a friend declaration of a class if and
16642       //   only if the class is a non-local class (9.8), the function name is
16643       //   unqualified, and the function has namespace scope.
16644       //
16645       // FIXME: We should only do this if the scope specifier names the
16646       // innermost enclosing namespace; otherwise the fixit changes the
16647       // meaning of the code.
16648       SemaDiagnosticBuilder DB
16649         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16650 
16651       DB << SS.getScopeRep();
16652       if (DC->isFileContext())
16653         DB << FixItHint::CreateRemoval(SS.getRange());
16654       SS.clear();
16655     }
16656 
16657   //   - There's a scope specifier that does not match any template
16658   //     parameter lists, in which case we use some arbitrary context,
16659   //     create a method or method template, and wait for instantiation.
16660   //   - There's a scope specifier that does match some template
16661   //     parameter lists, which we don't handle right now.
16662   } else {
16663     if (D.isFunctionDefinition()) {
16664       // C++ [class.friend]p6:
16665       //   A function can be defined in a friend declaration of a class if and
16666       //   only if the class is a non-local class (9.8), the function name is
16667       //   unqualified, and the function has namespace scope.
16668       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16669         << SS.getScopeRep();
16670     }
16671 
16672     DC = CurContext;
16673     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16674   }
16675 
16676   if (!DC->isRecord()) {
16677     int DiagArg = -1;
16678     switch (D.getName().getKind()) {
16679     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16680     case UnqualifiedIdKind::IK_ConstructorName:
16681       DiagArg = 0;
16682       break;
16683     case UnqualifiedIdKind::IK_DestructorName:
16684       DiagArg = 1;
16685       break;
16686     case UnqualifiedIdKind::IK_ConversionFunctionId:
16687       DiagArg = 2;
16688       break;
16689     case UnqualifiedIdKind::IK_DeductionGuideName:
16690       DiagArg = 3;
16691       break;
16692     case UnqualifiedIdKind::IK_Identifier:
16693     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16694     case UnqualifiedIdKind::IK_LiteralOperatorId:
16695     case UnqualifiedIdKind::IK_OperatorFunctionId:
16696     case UnqualifiedIdKind::IK_TemplateId:
16697       break;
16698     }
16699     // This implies that it has to be an operator or function.
16700     if (DiagArg >= 0) {
16701       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16702       return nullptr;
16703     }
16704   }
16705 
16706   // FIXME: This is an egregious hack to cope with cases where the scope stack
16707   // does not contain the declaration context, i.e., in an out-of-line
16708   // definition of a class.
16709   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16710   if (!DCScope) {
16711     FakeDCScope.setEntity(DC);
16712     DCScope = &FakeDCScope;
16713   }
16714 
16715   bool AddToScope = true;
16716   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16717                                           TemplateParams, AddToScope);
16718   if (!ND) return nullptr;
16719 
16720   assert(ND->getLexicalDeclContext() == CurContext);
16721 
16722   // If we performed typo correction, we might have added a scope specifier
16723   // and changed the decl context.
16724   DC = ND->getDeclContext();
16725 
16726   // Add the function declaration to the appropriate lookup tables,
16727   // adjusting the redeclarations list as necessary.  We don't
16728   // want to do this yet if the friending class is dependent.
16729   //
16730   // Also update the scope-based lookup if the target context's
16731   // lookup context is in lexical scope.
16732   if (!CurContext->isDependentContext()) {
16733     DC = DC->getRedeclContext();
16734     DC->makeDeclVisibleInContext(ND);
16735     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16736       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16737   }
16738 
16739   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16740                                        D.getIdentifierLoc(), ND,
16741                                        DS.getFriendSpecLoc());
16742   FrD->setAccess(AS_public);
16743   CurContext->addDecl(FrD);
16744 
16745   if (ND->isInvalidDecl()) {
16746     FrD->setInvalidDecl();
16747   } else {
16748     if (DC->isRecord()) CheckFriendAccess(ND);
16749 
16750     FunctionDecl *FD;
16751     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16752       FD = FTD->getTemplatedDecl();
16753     else
16754       FD = cast<FunctionDecl>(ND);
16755 
16756     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16757     // default argument expression, that declaration shall be a definition
16758     // and shall be the only declaration of the function or function
16759     // template in the translation unit.
16760     if (functionDeclHasDefaultArgument(FD)) {
16761       // We can't look at FD->getPreviousDecl() because it may not have been set
16762       // if we're in a dependent context. If the function is known to be a
16763       // redeclaration, we will have narrowed Previous down to the right decl.
16764       if (D.isRedeclaration()) {
16765         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16766         Diag(Previous.getRepresentativeDecl()->getLocation(),
16767              diag::note_previous_declaration);
16768       } else if (!D.isFunctionDefinition())
16769         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16770     }
16771 
16772     // Mark templated-scope function declarations as unsupported.
16773     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16774       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16775         << SS.getScopeRep() << SS.getRange()
16776         << cast<CXXRecordDecl>(CurContext);
16777       FrD->setUnsupportedFriend(true);
16778     }
16779   }
16780 
16781   warnOnReservedIdentifier(ND);
16782 
16783   return ND;
16784 }
16785 
16786 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16787   AdjustDeclIfTemplate(Dcl);
16788 
16789   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16790   if (!Fn) {
16791     Diag(DelLoc, diag::err_deleted_non_function);
16792     return;
16793   }
16794 
16795   // Deleted function does not have a body.
16796   Fn->setWillHaveBody(false);
16797 
16798   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16799     // Don't consider the implicit declaration we generate for explicit
16800     // specializations. FIXME: Do not generate these implicit declarations.
16801     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16802          Prev->getPreviousDecl()) &&
16803         !Prev->isDefined()) {
16804       Diag(DelLoc, diag::err_deleted_decl_not_first);
16805       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16806            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16807                               : diag::note_previous_declaration);
16808       // We can't recover from this; the declaration might have already
16809       // been used.
16810       Fn->setInvalidDecl();
16811       return;
16812     }
16813 
16814     // To maintain the invariant that functions are only deleted on their first
16815     // declaration, mark the implicitly-instantiated declaration of the
16816     // explicitly-specialized function as deleted instead of marking the
16817     // instantiated redeclaration.
16818     Fn = Fn->getCanonicalDecl();
16819   }
16820 
16821   // dllimport/dllexport cannot be deleted.
16822   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16823     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16824     Fn->setInvalidDecl();
16825   }
16826 
16827   // C++11 [basic.start.main]p3:
16828   //   A program that defines main as deleted [...] is ill-formed.
16829   if (Fn->isMain())
16830     Diag(DelLoc, diag::err_deleted_main);
16831 
16832   // C++11 [dcl.fct.def.delete]p4:
16833   //  A deleted function is implicitly inline.
16834   Fn->setImplicitlyInline();
16835   Fn->setDeletedAsWritten();
16836 }
16837 
16838 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16839   if (!Dcl || Dcl->isInvalidDecl())
16840     return;
16841 
16842   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16843   if (!FD) {
16844     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16845       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16846         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16847         return;
16848       }
16849     }
16850 
16851     Diag(DefaultLoc, diag::err_default_special_members)
16852         << getLangOpts().CPlusPlus20;
16853     return;
16854   }
16855 
16856   // Reject if this can't possibly be a defaultable function.
16857   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16858   if (!DefKind &&
16859       // A dependent function that doesn't locally look defaultable can
16860       // still instantiate to a defaultable function if it's a constructor
16861       // or assignment operator.
16862       (!FD->isDependentContext() ||
16863        (!isa<CXXConstructorDecl>(FD) &&
16864         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16865     Diag(DefaultLoc, diag::err_default_special_members)
16866         << getLangOpts().CPlusPlus20;
16867     return;
16868   }
16869 
16870   if (DefKind.isComparison() &&
16871       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16872     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16873         << (int)DefKind.asComparison();
16874     return;
16875   }
16876 
16877   // Issue compatibility warning. We already warned if the operator is
16878   // 'operator<=>' when parsing the '<=>' token.
16879   if (DefKind.isComparison() &&
16880       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16881     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16882                          ? diag::warn_cxx17_compat_defaulted_comparison
16883                          : diag::ext_defaulted_comparison);
16884   }
16885 
16886   FD->setDefaulted();
16887   FD->setExplicitlyDefaulted();
16888 
16889   // Defer checking functions that are defaulted in a dependent context.
16890   if (FD->isDependentContext())
16891     return;
16892 
16893   // Unset that we will have a body for this function. We might not,
16894   // if it turns out to be trivial, and we don't need this marking now
16895   // that we've marked it as defaulted.
16896   FD->setWillHaveBody(false);
16897 
16898   // If this definition appears within the record, do the checking when
16899   // the record is complete. This is always the case for a defaulted
16900   // comparison.
16901   if (DefKind.isComparison())
16902     return;
16903   auto *MD = cast<CXXMethodDecl>(FD);
16904 
16905   const FunctionDecl *Primary = FD;
16906   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16907     // Ask the template instantiation pattern that actually had the
16908     // '= default' on it.
16909     Primary = Pattern;
16910 
16911   // If the method was defaulted on its first declaration, we will have
16912   // already performed the checking in CheckCompletedCXXClass. Such a
16913   // declaration doesn't trigger an implicit definition.
16914   if (Primary->getCanonicalDecl()->isDefaulted())
16915     return;
16916 
16917   // FIXME: Once we support defining comparisons out of class, check for a
16918   // defaulted comparison here.
16919   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16920     MD->setInvalidDecl();
16921   else
16922     DefineDefaultedFunction(*this, MD, DefaultLoc);
16923 }
16924 
16925 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16926   for (Stmt *SubStmt : S->children()) {
16927     if (!SubStmt)
16928       continue;
16929     if (isa<ReturnStmt>(SubStmt))
16930       Self.Diag(SubStmt->getBeginLoc(),
16931                 diag::err_return_in_constructor_handler);
16932     if (!isa<Expr>(SubStmt))
16933       SearchForReturnInStmt(Self, SubStmt);
16934   }
16935 }
16936 
16937 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16938   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16939     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16940     SearchForReturnInStmt(*this, Handler);
16941   }
16942 }
16943 
16944 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16945                                              const CXXMethodDecl *Old) {
16946   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16947   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16948 
16949   if (OldFT->hasExtParameterInfos()) {
16950     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16951       // A parameter of the overriding method should be annotated with noescape
16952       // if the corresponding parameter of the overridden method is annotated.
16953       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16954           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16955         Diag(New->getParamDecl(I)->getLocation(),
16956              diag::warn_overriding_method_missing_noescape);
16957         Diag(Old->getParamDecl(I)->getLocation(),
16958              diag::note_overridden_marked_noescape);
16959       }
16960   }
16961 
16962   // Virtual overrides must have the same code_seg.
16963   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16964   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16965   if ((NewCSA || OldCSA) &&
16966       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16967     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16968     Diag(Old->getLocation(), diag::note_previous_declaration);
16969     return true;
16970   }
16971 
16972   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16973 
16974   // If the calling conventions match, everything is fine
16975   if (NewCC == OldCC)
16976     return false;
16977 
16978   // If the calling conventions mismatch because the new function is static,
16979   // suppress the calling convention mismatch error; the error about static
16980   // function override (err_static_overrides_virtual from
16981   // Sema::CheckFunctionDeclaration) is more clear.
16982   if (New->getStorageClass() == SC_Static)
16983     return false;
16984 
16985   Diag(New->getLocation(),
16986        diag::err_conflicting_overriding_cc_attributes)
16987     << New->getDeclName() << New->getType() << Old->getType();
16988   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16989   return true;
16990 }
16991 
16992 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16993                                              const CXXMethodDecl *Old) {
16994   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16995   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16996 
16997   if (Context.hasSameType(NewTy, OldTy) ||
16998       NewTy->isDependentType() || OldTy->isDependentType())
16999     return false;
17000 
17001   // Check if the return types are covariant
17002   QualType NewClassTy, OldClassTy;
17003 
17004   /// Both types must be pointers or references to classes.
17005   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17006     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17007       NewClassTy = NewPT->getPointeeType();
17008       OldClassTy = OldPT->getPointeeType();
17009     }
17010   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17011     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17012       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17013         NewClassTy = NewRT->getPointeeType();
17014         OldClassTy = OldRT->getPointeeType();
17015       }
17016     }
17017   }
17018 
17019   // The return types aren't either both pointers or references to a class type.
17020   if (NewClassTy.isNull()) {
17021     Diag(New->getLocation(),
17022          diag::err_different_return_type_for_overriding_virtual_function)
17023         << New->getDeclName() << NewTy << OldTy
17024         << New->getReturnTypeSourceRange();
17025     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17026         << Old->getReturnTypeSourceRange();
17027 
17028     return true;
17029   }
17030 
17031   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17032     // C++14 [class.virtual]p8:
17033     //   If the class type in the covariant return type of D::f differs from
17034     //   that of B::f, the class type in the return type of D::f shall be
17035     //   complete at the point of declaration of D::f or shall be the class
17036     //   type D.
17037     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17038       if (!RT->isBeingDefined() &&
17039           RequireCompleteType(New->getLocation(), NewClassTy,
17040                               diag::err_covariant_return_incomplete,
17041                               New->getDeclName()))
17042         return true;
17043     }
17044 
17045     // Check if the new class derives from the old class.
17046     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17047       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17048           << New->getDeclName() << NewTy << OldTy
17049           << New->getReturnTypeSourceRange();
17050       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17051           << Old->getReturnTypeSourceRange();
17052       return true;
17053     }
17054 
17055     // Check if we the conversion from derived to base is valid.
17056     if (CheckDerivedToBaseConversion(
17057             NewClassTy, OldClassTy,
17058             diag::err_covariant_return_inaccessible_base,
17059             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17060             New->getLocation(), New->getReturnTypeSourceRange(),
17061             New->getDeclName(), nullptr)) {
17062       // FIXME: this note won't trigger for delayed access control
17063       // diagnostics, and it's impossible to get an undelayed error
17064       // here from access control during the original parse because
17065       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17066       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17067           << Old->getReturnTypeSourceRange();
17068       return true;
17069     }
17070   }
17071 
17072   // The qualifiers of the return types must be the same.
17073   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17074     Diag(New->getLocation(),
17075          diag::err_covariant_return_type_different_qualifications)
17076         << New->getDeclName() << NewTy << OldTy
17077         << New->getReturnTypeSourceRange();
17078     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17079         << Old->getReturnTypeSourceRange();
17080     return true;
17081   }
17082 
17083 
17084   // The new class type must have the same or less qualifiers as the old type.
17085   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17086     Diag(New->getLocation(),
17087          diag::err_covariant_return_type_class_type_more_qualified)
17088         << New->getDeclName() << NewTy << OldTy
17089         << New->getReturnTypeSourceRange();
17090     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17091         << Old->getReturnTypeSourceRange();
17092     return true;
17093   }
17094 
17095   return false;
17096 }
17097 
17098 /// Mark the given method pure.
17099 ///
17100 /// \param Method the method to be marked pure.
17101 ///
17102 /// \param InitRange the source range that covers the "0" initializer.
17103 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17104   SourceLocation EndLoc = InitRange.getEnd();
17105   if (EndLoc.isValid())
17106     Method->setRangeEnd(EndLoc);
17107 
17108   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17109     Method->setPure();
17110     return false;
17111   }
17112 
17113   if (!Method->isInvalidDecl())
17114     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17115       << Method->getDeclName() << InitRange;
17116   return true;
17117 }
17118 
17119 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17120   if (D->getFriendObjectKind())
17121     Diag(D->getLocation(), diag::err_pure_friend);
17122   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17123     CheckPureMethod(M, ZeroLoc);
17124   else
17125     Diag(D->getLocation(), diag::err_illegal_initializer);
17126 }
17127 
17128 /// Determine whether the given declaration is a global variable or
17129 /// static data member.
17130 static bool isNonlocalVariable(const Decl *D) {
17131   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17132     return Var->hasGlobalStorage();
17133 
17134   return false;
17135 }
17136 
17137 /// Invoked when we are about to parse an initializer for the declaration
17138 /// 'Dcl'.
17139 ///
17140 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17141 /// static data member of class X, names should be looked up in the scope of
17142 /// class X. If the declaration had a scope specifier, a scope will have
17143 /// been created and passed in for this purpose. Otherwise, S will be null.
17144 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17145   // If there is no declaration, there was an error parsing it.
17146   if (!D || D->isInvalidDecl())
17147     return;
17148 
17149   // We will always have a nested name specifier here, but this declaration
17150   // might not be out of line if the specifier names the current namespace:
17151   //   extern int n;
17152   //   int ::n = 0;
17153   if (S && D->isOutOfLine())
17154     EnterDeclaratorContext(S, D->getDeclContext());
17155 
17156   // If we are parsing the initializer for a static data member, push a
17157   // new expression evaluation context that is associated with this static
17158   // data member.
17159   if (isNonlocalVariable(D))
17160     PushExpressionEvaluationContext(
17161         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17162 }
17163 
17164 /// Invoked after we are finished parsing an initializer for the declaration D.
17165 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17166   // If there is no declaration, there was an error parsing it.
17167   if (!D || D->isInvalidDecl())
17168     return;
17169 
17170   if (isNonlocalVariable(D))
17171     PopExpressionEvaluationContext();
17172 
17173   if (S && D->isOutOfLine())
17174     ExitDeclaratorContext(S);
17175 }
17176 
17177 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17178 /// C++ if/switch/while/for statement.
17179 /// e.g: "if (int x = f()) {...}"
17180 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17181   // C++ 6.4p2:
17182   // The declarator shall not specify a function or an array.
17183   // The type-specifier-seq shall not contain typedef and shall not declare a
17184   // new class or enumeration.
17185   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17186          "Parser allowed 'typedef' as storage class of condition decl.");
17187 
17188   Decl *Dcl = ActOnDeclarator(S, D);
17189   if (!Dcl)
17190     return true;
17191 
17192   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17193     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17194       << D.getSourceRange();
17195     return true;
17196   }
17197 
17198   return Dcl;
17199 }
17200 
17201 void Sema::LoadExternalVTableUses() {
17202   if (!ExternalSource)
17203     return;
17204 
17205   SmallVector<ExternalVTableUse, 4> VTables;
17206   ExternalSource->ReadUsedVTables(VTables);
17207   SmallVector<VTableUse, 4> NewUses;
17208   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17209     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17210       = VTablesUsed.find(VTables[I].Record);
17211     // Even if a definition wasn't required before, it may be required now.
17212     if (Pos != VTablesUsed.end()) {
17213       if (!Pos->second && VTables[I].DefinitionRequired)
17214         Pos->second = true;
17215       continue;
17216     }
17217 
17218     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17219     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17220   }
17221 
17222   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17223 }
17224 
17225 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17226                           bool DefinitionRequired) {
17227   // Ignore any vtable uses in unevaluated operands or for classes that do
17228   // not have a vtable.
17229   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17230       CurContext->isDependentContext() || isUnevaluatedContext())
17231     return;
17232   // Do not mark as used if compiling for the device outside of the target
17233   // region.
17234   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17235       !isInOpenMPDeclareTargetContext() &&
17236       !isInOpenMPTargetExecutionDirective()) {
17237     if (!DefinitionRequired)
17238       MarkVirtualMembersReferenced(Loc, Class);
17239     return;
17240   }
17241 
17242   // Try to insert this class into the map.
17243   LoadExternalVTableUses();
17244   Class = Class->getCanonicalDecl();
17245   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17246     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17247   if (!Pos.second) {
17248     // If we already had an entry, check to see if we are promoting this vtable
17249     // to require a definition. If so, we need to reappend to the VTableUses
17250     // list, since we may have already processed the first entry.
17251     if (DefinitionRequired && !Pos.first->second) {
17252       Pos.first->second = true;
17253     } else {
17254       // Otherwise, we can early exit.
17255       return;
17256     }
17257   } else {
17258     // The Microsoft ABI requires that we perform the destructor body
17259     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17260     // the deleting destructor is emitted with the vtable, not with the
17261     // destructor definition as in the Itanium ABI.
17262     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17263       CXXDestructorDecl *DD = Class->getDestructor();
17264       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17265         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17266           // If this is an out-of-line declaration, marking it referenced will
17267           // not do anything. Manually call CheckDestructor to look up operator
17268           // delete().
17269           ContextRAII SavedContext(*this, DD);
17270           CheckDestructor(DD);
17271         } else {
17272           MarkFunctionReferenced(Loc, Class->getDestructor());
17273         }
17274       }
17275     }
17276   }
17277 
17278   // Local classes need to have their virtual members marked
17279   // immediately. For all other classes, we mark their virtual members
17280   // at the end of the translation unit.
17281   if (Class->isLocalClass())
17282     MarkVirtualMembersReferenced(Loc, Class);
17283   else
17284     VTableUses.push_back(std::make_pair(Class, Loc));
17285 }
17286 
17287 bool Sema::DefineUsedVTables() {
17288   LoadExternalVTableUses();
17289   if (VTableUses.empty())
17290     return false;
17291 
17292   // Note: The VTableUses vector could grow as a result of marking
17293   // the members of a class as "used", so we check the size each
17294   // time through the loop and prefer indices (which are stable) to
17295   // iterators (which are not).
17296   bool DefinedAnything = false;
17297   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17298     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17299     if (!Class)
17300       continue;
17301     TemplateSpecializationKind ClassTSK =
17302         Class->getTemplateSpecializationKind();
17303 
17304     SourceLocation Loc = VTableUses[I].second;
17305 
17306     bool DefineVTable = true;
17307 
17308     // If this class has a key function, but that key function is
17309     // defined in another translation unit, we don't need to emit the
17310     // vtable even though we're using it.
17311     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17312     if (KeyFunction && !KeyFunction->hasBody()) {
17313       // The key function is in another translation unit.
17314       DefineVTable = false;
17315       TemplateSpecializationKind TSK =
17316           KeyFunction->getTemplateSpecializationKind();
17317       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17318              TSK != TSK_ImplicitInstantiation &&
17319              "Instantiations don't have key functions");
17320       (void)TSK;
17321     } else if (!KeyFunction) {
17322       // If we have a class with no key function that is the subject
17323       // of an explicit instantiation declaration, suppress the
17324       // vtable; it will live with the explicit instantiation
17325       // definition.
17326       bool IsExplicitInstantiationDeclaration =
17327           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17328       for (auto R : Class->redecls()) {
17329         TemplateSpecializationKind TSK
17330           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17331         if (TSK == TSK_ExplicitInstantiationDeclaration)
17332           IsExplicitInstantiationDeclaration = true;
17333         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17334           IsExplicitInstantiationDeclaration = false;
17335           break;
17336         }
17337       }
17338 
17339       if (IsExplicitInstantiationDeclaration)
17340         DefineVTable = false;
17341     }
17342 
17343     // The exception specifications for all virtual members may be needed even
17344     // if we are not providing an authoritative form of the vtable in this TU.
17345     // We may choose to emit it available_externally anyway.
17346     if (!DefineVTable) {
17347       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17348       continue;
17349     }
17350 
17351     // Mark all of the virtual members of this class as referenced, so
17352     // that we can build a vtable. Then, tell the AST consumer that a
17353     // vtable for this class is required.
17354     DefinedAnything = true;
17355     MarkVirtualMembersReferenced(Loc, Class);
17356     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17357     if (VTablesUsed[Canonical])
17358       Consumer.HandleVTable(Class);
17359 
17360     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17361     // no key function or the key function is inlined. Don't warn in C++ ABIs
17362     // that lack key functions, since the user won't be able to make one.
17363     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17364         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17365       const FunctionDecl *KeyFunctionDef = nullptr;
17366       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17367                            KeyFunctionDef->isInlined())) {
17368         Diag(Class->getLocation(),
17369              ClassTSK == TSK_ExplicitInstantiationDefinition
17370                  ? diag::warn_weak_template_vtable
17371                  : diag::warn_weak_vtable)
17372             << Class;
17373       }
17374     }
17375   }
17376   VTableUses.clear();
17377 
17378   return DefinedAnything;
17379 }
17380 
17381 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17382                                                  const CXXRecordDecl *RD) {
17383   for (const auto *I : RD->methods())
17384     if (I->isVirtual() && !I->isPure())
17385       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17386 }
17387 
17388 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17389                                         const CXXRecordDecl *RD,
17390                                         bool ConstexprOnly) {
17391   // Mark all functions which will appear in RD's vtable as used.
17392   CXXFinalOverriderMap FinalOverriders;
17393   RD->getFinalOverriders(FinalOverriders);
17394   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17395                                             E = FinalOverriders.end();
17396        I != E; ++I) {
17397     for (OverridingMethods::const_iterator OI = I->second.begin(),
17398                                            OE = I->second.end();
17399          OI != OE; ++OI) {
17400       assert(OI->second.size() > 0 && "no final overrider");
17401       CXXMethodDecl *Overrider = OI->second.front().Method;
17402 
17403       // C++ [basic.def.odr]p2:
17404       //   [...] A virtual member function is used if it is not pure. [...]
17405       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17406         MarkFunctionReferenced(Loc, Overrider);
17407     }
17408   }
17409 
17410   // Only classes that have virtual bases need a VTT.
17411   if (RD->getNumVBases() == 0)
17412     return;
17413 
17414   for (const auto &I : RD->bases()) {
17415     const auto *Base =
17416         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17417     if (Base->getNumVBases() == 0)
17418       continue;
17419     MarkVirtualMembersReferenced(Loc, Base);
17420   }
17421 }
17422 
17423 /// SetIvarInitializers - This routine builds initialization ASTs for the
17424 /// Objective-C implementation whose ivars need be initialized.
17425 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17426   if (!getLangOpts().CPlusPlus)
17427     return;
17428   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17429     SmallVector<ObjCIvarDecl*, 8> ivars;
17430     CollectIvarsToConstructOrDestruct(OID, ivars);
17431     if (ivars.empty())
17432       return;
17433     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17434     for (unsigned i = 0; i < ivars.size(); i++) {
17435       FieldDecl *Field = ivars[i];
17436       if (Field->isInvalidDecl())
17437         continue;
17438 
17439       CXXCtorInitializer *Member;
17440       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17441       InitializationKind InitKind =
17442         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17443 
17444       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17445       ExprResult MemberInit =
17446         InitSeq.Perform(*this, InitEntity, InitKind, None);
17447       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17448       // Note, MemberInit could actually come back empty if no initialization
17449       // is required (e.g., because it would call a trivial default constructor)
17450       if (!MemberInit.get() || MemberInit.isInvalid())
17451         continue;
17452 
17453       Member =
17454         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17455                                          SourceLocation(),
17456                                          MemberInit.getAs<Expr>(),
17457                                          SourceLocation());
17458       AllToInit.push_back(Member);
17459 
17460       // Be sure that the destructor is accessible and is marked as referenced.
17461       if (const RecordType *RecordTy =
17462               Context.getBaseElementType(Field->getType())
17463                   ->getAs<RecordType>()) {
17464         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17465         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17466           MarkFunctionReferenced(Field->getLocation(), Destructor);
17467           CheckDestructorAccess(Field->getLocation(), Destructor,
17468                             PDiag(diag::err_access_dtor_ivar)
17469                               << Context.getBaseElementType(Field->getType()));
17470         }
17471       }
17472     }
17473     ObjCImplementation->setIvarInitializers(Context,
17474                                             AllToInit.data(), AllToInit.size());
17475   }
17476 }
17477 
17478 static
17479 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17480                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17481                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17482                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17483                            Sema &S) {
17484   if (Ctor->isInvalidDecl())
17485     return;
17486 
17487   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17488 
17489   // Target may not be determinable yet, for instance if this is a dependent
17490   // call in an uninstantiated template.
17491   if (Target) {
17492     const FunctionDecl *FNTarget = nullptr;
17493     (void)Target->hasBody(FNTarget);
17494     Target = const_cast<CXXConstructorDecl*>(
17495       cast_or_null<CXXConstructorDecl>(FNTarget));
17496   }
17497 
17498   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17499                      // Avoid dereferencing a null pointer here.
17500                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17501 
17502   if (!Current.insert(Canonical).second)
17503     return;
17504 
17505   // We know that beyond here, we aren't chaining into a cycle.
17506   if (!Target || !Target->isDelegatingConstructor() ||
17507       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17508     Valid.insert(Current.begin(), Current.end());
17509     Current.clear();
17510   // We've hit a cycle.
17511   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17512              Current.count(TCanonical)) {
17513     // If we haven't diagnosed this cycle yet, do so now.
17514     if (!Invalid.count(TCanonical)) {
17515       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17516              diag::warn_delegating_ctor_cycle)
17517         << Ctor;
17518 
17519       // Don't add a note for a function delegating directly to itself.
17520       if (TCanonical != Canonical)
17521         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17522 
17523       CXXConstructorDecl *C = Target;
17524       while (C->getCanonicalDecl() != Canonical) {
17525         const FunctionDecl *FNTarget = nullptr;
17526         (void)C->getTargetConstructor()->hasBody(FNTarget);
17527         assert(FNTarget && "Ctor cycle through bodiless function");
17528 
17529         C = const_cast<CXXConstructorDecl*>(
17530           cast<CXXConstructorDecl>(FNTarget));
17531         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17532       }
17533     }
17534 
17535     Invalid.insert(Current.begin(), Current.end());
17536     Current.clear();
17537   } else {
17538     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17539   }
17540 }
17541 
17542 
17543 void Sema::CheckDelegatingCtorCycles() {
17544   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17545 
17546   for (DelegatingCtorDeclsType::iterator
17547          I = DelegatingCtorDecls.begin(ExternalSource),
17548          E = DelegatingCtorDecls.end();
17549        I != E; ++I)
17550     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17551 
17552   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17553     (*CI)->setInvalidDecl();
17554 }
17555 
17556 namespace {
17557   /// AST visitor that finds references to the 'this' expression.
17558   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17559     Sema &S;
17560 
17561   public:
17562     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17563 
17564     bool VisitCXXThisExpr(CXXThisExpr *E) {
17565       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17566         << E->isImplicit();
17567       return false;
17568     }
17569   };
17570 }
17571 
17572 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17573   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17574   if (!TSInfo)
17575     return false;
17576 
17577   TypeLoc TL = TSInfo->getTypeLoc();
17578   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17579   if (!ProtoTL)
17580     return false;
17581 
17582   // C++11 [expr.prim.general]p3:
17583   //   [The expression this] shall not appear before the optional
17584   //   cv-qualifier-seq and it shall not appear within the declaration of a
17585   //   static member function (although its type and value category are defined
17586   //   within a static member function as they are within a non-static member
17587   //   function). [ Note: this is because declaration matching does not occur
17588   //  until the complete declarator is known. - end note ]
17589   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17590   FindCXXThisExpr Finder(*this);
17591 
17592   // If the return type came after the cv-qualifier-seq, check it now.
17593   if (Proto->hasTrailingReturn() &&
17594       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17595     return true;
17596 
17597   // Check the exception specification.
17598   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17599     return true;
17600 
17601   // Check the trailing requires clause
17602   if (Expr *E = Method->getTrailingRequiresClause())
17603     if (!Finder.TraverseStmt(E))
17604       return true;
17605 
17606   return checkThisInStaticMemberFunctionAttributes(Method);
17607 }
17608 
17609 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17610   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17611   if (!TSInfo)
17612     return false;
17613 
17614   TypeLoc TL = TSInfo->getTypeLoc();
17615   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17616   if (!ProtoTL)
17617     return false;
17618 
17619   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17620   FindCXXThisExpr Finder(*this);
17621 
17622   switch (Proto->getExceptionSpecType()) {
17623   case EST_Unparsed:
17624   case EST_Uninstantiated:
17625   case EST_Unevaluated:
17626   case EST_BasicNoexcept:
17627   case EST_NoThrow:
17628   case EST_DynamicNone:
17629   case EST_MSAny:
17630   case EST_None:
17631     break;
17632 
17633   case EST_DependentNoexcept:
17634   case EST_NoexceptFalse:
17635   case EST_NoexceptTrue:
17636     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17637       return true;
17638     LLVM_FALLTHROUGH;
17639 
17640   case EST_Dynamic:
17641     for (const auto &E : Proto->exceptions()) {
17642       if (!Finder.TraverseType(E))
17643         return true;
17644     }
17645     break;
17646   }
17647 
17648   return false;
17649 }
17650 
17651 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17652   FindCXXThisExpr Finder(*this);
17653 
17654   // Check attributes.
17655   for (const auto *A : Method->attrs()) {
17656     // FIXME: This should be emitted by tblgen.
17657     Expr *Arg = nullptr;
17658     ArrayRef<Expr *> Args;
17659     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17660       Arg = G->getArg();
17661     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17662       Arg = G->getArg();
17663     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17664       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17665     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17666       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17667     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17668       Arg = ETLF->getSuccessValue();
17669       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17670     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17671       Arg = STLF->getSuccessValue();
17672       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17673     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17674       Arg = LR->getArg();
17675     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17676       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17677     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17678       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17679     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17680       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17681     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17682       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17683     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17684       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17685 
17686     if (Arg && !Finder.TraverseStmt(Arg))
17687       return true;
17688 
17689     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17690       if (!Finder.TraverseStmt(Args[I]))
17691         return true;
17692     }
17693   }
17694 
17695   return false;
17696 }
17697 
17698 void Sema::checkExceptionSpecification(
17699     bool IsTopLevel, ExceptionSpecificationType EST,
17700     ArrayRef<ParsedType> DynamicExceptions,
17701     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17702     SmallVectorImpl<QualType> &Exceptions,
17703     FunctionProtoType::ExceptionSpecInfo &ESI) {
17704   Exceptions.clear();
17705   ESI.Type = EST;
17706   if (EST == EST_Dynamic) {
17707     Exceptions.reserve(DynamicExceptions.size());
17708     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17709       // FIXME: Preserve type source info.
17710       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17711 
17712       if (IsTopLevel) {
17713         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17714         collectUnexpandedParameterPacks(ET, Unexpanded);
17715         if (!Unexpanded.empty()) {
17716           DiagnoseUnexpandedParameterPacks(
17717               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17718               Unexpanded);
17719           continue;
17720         }
17721       }
17722 
17723       // Check that the type is valid for an exception spec, and
17724       // drop it if not.
17725       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17726         Exceptions.push_back(ET);
17727     }
17728     ESI.Exceptions = Exceptions;
17729     return;
17730   }
17731 
17732   if (isComputedNoexcept(EST)) {
17733     assert((NoexceptExpr->isTypeDependent() ||
17734             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17735             Context.BoolTy) &&
17736            "Parser should have made sure that the expression is boolean");
17737     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17738       ESI.Type = EST_BasicNoexcept;
17739       return;
17740     }
17741 
17742     ESI.NoexceptExpr = NoexceptExpr;
17743     return;
17744   }
17745 }
17746 
17747 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17748              ExceptionSpecificationType EST,
17749              SourceRange SpecificationRange,
17750              ArrayRef<ParsedType> DynamicExceptions,
17751              ArrayRef<SourceRange> DynamicExceptionRanges,
17752              Expr *NoexceptExpr) {
17753   if (!MethodD)
17754     return;
17755 
17756   // Dig out the method we're referring to.
17757   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17758     MethodD = FunTmpl->getTemplatedDecl();
17759 
17760   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17761   if (!Method)
17762     return;
17763 
17764   // Check the exception specification.
17765   llvm::SmallVector<QualType, 4> Exceptions;
17766   FunctionProtoType::ExceptionSpecInfo ESI;
17767   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17768                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17769                               ESI);
17770 
17771   // Update the exception specification on the function type.
17772   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17773 
17774   if (Method->isStatic())
17775     checkThisInStaticMemberFunctionExceptionSpec(Method);
17776 
17777   if (Method->isVirtual()) {
17778     // Check overrides, which we previously had to delay.
17779     for (const CXXMethodDecl *O : Method->overridden_methods())
17780       CheckOverridingFunctionExceptionSpec(Method, O);
17781   }
17782 }
17783 
17784 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17785 ///
17786 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17787                                        SourceLocation DeclStart, Declarator &D,
17788                                        Expr *BitWidth,
17789                                        InClassInitStyle InitStyle,
17790                                        AccessSpecifier AS,
17791                                        const ParsedAttr &MSPropertyAttr) {
17792   IdentifierInfo *II = D.getIdentifier();
17793   if (!II) {
17794     Diag(DeclStart, diag::err_anonymous_property);
17795     return nullptr;
17796   }
17797   SourceLocation Loc = D.getIdentifierLoc();
17798 
17799   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17800   QualType T = TInfo->getType();
17801   if (getLangOpts().CPlusPlus) {
17802     CheckExtraCXXDefaultArguments(D);
17803 
17804     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17805                                         UPPC_DataMemberType)) {
17806       D.setInvalidType();
17807       T = Context.IntTy;
17808       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17809     }
17810   }
17811 
17812   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17813 
17814   if (D.getDeclSpec().isInlineSpecified())
17815     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17816         << getLangOpts().CPlusPlus17;
17817   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17818     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17819          diag::err_invalid_thread)
17820       << DeclSpec::getSpecifierName(TSCS);
17821 
17822   // Check to see if this name was declared as a member previously
17823   NamedDecl *PrevDecl = nullptr;
17824   LookupResult Previous(*this, II, Loc, LookupMemberName,
17825                         ForVisibleRedeclaration);
17826   LookupName(Previous, S);
17827   switch (Previous.getResultKind()) {
17828   case LookupResult::Found:
17829   case LookupResult::FoundUnresolvedValue:
17830     PrevDecl = Previous.getAsSingle<NamedDecl>();
17831     break;
17832 
17833   case LookupResult::FoundOverloaded:
17834     PrevDecl = Previous.getRepresentativeDecl();
17835     break;
17836 
17837   case LookupResult::NotFound:
17838   case LookupResult::NotFoundInCurrentInstantiation:
17839   case LookupResult::Ambiguous:
17840     break;
17841   }
17842 
17843   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17844     // Maybe we will complain about the shadowed template parameter.
17845     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17846     // Just pretend that we didn't see the previous declaration.
17847     PrevDecl = nullptr;
17848   }
17849 
17850   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17851     PrevDecl = nullptr;
17852 
17853   SourceLocation TSSL = D.getBeginLoc();
17854   MSPropertyDecl *NewPD =
17855       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17856                              MSPropertyAttr.getPropertyDataGetter(),
17857                              MSPropertyAttr.getPropertyDataSetter());
17858   ProcessDeclAttributes(TUScope, NewPD, D);
17859   NewPD->setAccess(AS);
17860 
17861   if (NewPD->isInvalidDecl())
17862     Record->setInvalidDecl();
17863 
17864   if (D.getDeclSpec().isModulePrivateSpecified())
17865     NewPD->setModulePrivate();
17866 
17867   if (NewPD->isInvalidDecl() && PrevDecl) {
17868     // Don't introduce NewFD into scope; there's already something
17869     // with the same name in the same scope.
17870   } else if (II) {
17871     PushOnScopeChains(NewPD, S);
17872   } else
17873     Record->addDecl(NewPD);
17874 
17875   return NewPD;
17876 }
17877 
17878 void Sema::ActOnStartFunctionDeclarationDeclarator(
17879     Declarator &Declarator, unsigned TemplateParameterDepth) {
17880   auto &Info = InventedParameterInfos.emplace_back();
17881   TemplateParameterList *ExplicitParams = nullptr;
17882   ArrayRef<TemplateParameterList *> ExplicitLists =
17883       Declarator.getTemplateParameterLists();
17884   if (!ExplicitLists.empty()) {
17885     bool IsMemberSpecialization, IsInvalid;
17886     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17887         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17888         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17889         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17890         /*SuppressDiagnostic=*/true);
17891   }
17892   if (ExplicitParams) {
17893     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17894     for (NamedDecl *Param : *ExplicitParams)
17895       Info.TemplateParams.push_back(Param);
17896     Info.NumExplicitTemplateParams = ExplicitParams->size();
17897   } else {
17898     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17899     Info.NumExplicitTemplateParams = 0;
17900   }
17901 }
17902 
17903 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17904   auto &FSI = InventedParameterInfos.back();
17905   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17906     if (FSI.NumExplicitTemplateParams != 0) {
17907       TemplateParameterList *ExplicitParams =
17908           Declarator.getTemplateParameterLists().back();
17909       Declarator.setInventedTemplateParameterList(
17910           TemplateParameterList::Create(
17911               Context, ExplicitParams->getTemplateLoc(),
17912               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17913               ExplicitParams->getRAngleLoc(),
17914               ExplicitParams->getRequiresClause()));
17915     } else {
17916       Declarator.setInventedTemplateParameterList(
17917           TemplateParameterList::Create(
17918               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17919               SourceLocation(), /*RequiresClause=*/nullptr));
17920     }
17921   }
17922   InventedParameterInfos.pop_back();
17923 }
17924